搜尋此網誌

2026年8月5日星期三

Variables and scope

def function1(varA, varB):

    message = 'Some local data'

    print(varA)

    def inner_function(varA, varB):

        print(f'inner_function local scope: {locals()}')

    

    print(locals())

    inner_function(123, 456)


function1(1, 2)


Call function1(1, 2)

Parameters: varA = 1, varB = 2.

Inside function1

message = 'Some local data' is created.

print(varA) → prints 1.


Define inner_function

At this point, Python just defines the nested function. It doesn’t run yet.

print(locals()) inside function1

locals() returns a dictionary of all local variables in function1 at that moment:

{ 'varA': 1, 'varB': 2, 'message': 'Some local data', 'inner_function': <function function1.<locals>.inner_function at 0x...> }

So you’ll see a dictionary printed with those names and values.

inner_function → the variable name in the local scope dictionary.
<function ... > → Python is showing you that the value is a function object.
function1.<locals>.inner_function → the fully qualified name of the function:
function1 → the outer function where it was defined.
<locals> → indicates this function was defined inside another function (not at the module/global level).
inner_function → the actual name of the nested function.
at 0x... → the memory address (hexadecimal) where the function object is stored. This is just an identifier for debugging, not something you usually use directly.

Call inner_function(123, 456)

  • New scope is created for inner_function.

  • Parameters: varA = 123, varB = 456.

  • locals() inside inner_function shows:

{ 'varA': 123, 'varB': 456 }

That’s printed as: inner_function local scope: {'varA': 123, 'varB': 456}

Microsoft Copilot

沒有留言:

發佈留言