问题
name = "Lenin Mishra"
def home():
name = "Sonu"
print(name)
home()
print(locals())
When I run the above code, Python returns me a dictionary containing the variable name, which has a value of Lenin Mishra.
{'__name__': '__main__', '__doc__': '\nExperimenting with scope\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10323b400>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/leninmishra/Desktop/python_basics/scope.py', '__cached__': None, 'name': 'Lenin Mishra', 'home': <function home at 0x101db5e18>}
But as far as I understand, the variable name which has been assigned the value of Lenin Mishra is in the global scope.
Why is this happening?
回答1:
In your code, locals() executed at global scope, so you got that output.
If you execute that locals() as part of another function, you could get the local variables to that specific function's scope.
For example, if you write your code as below, you could get out-put as empty brackets. python works based on indentation.
Sample-code
def myfun():
print(locals())
myfun()
Output
{}
Sample code2
def home():
name = "Sonu"
print(locals())
home()
output
{'name': 'Sonu'}
This sample 2 code explains only name variable is available in its local scope.
Help of locals function says as follows:
In [1]: ?locals
Signature: locals()
Docstring:
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
Type: builtin_function_or_method
来源:https://stackoverflow.com/questions/53414407/locals-built-in-method-in-python3-returns-the-variable-in-the-global-namespace