Python locals () function
The locals () function in Python returns a dictionary containing the variables defined in the local namespace.
The locals () function in Python returns a dictionary containing the variables defined in the local namespace. Call locals () in the global namespace like calling globals () and return a dictionary representing the module's global namespace. So how does the syntax of locals () function, what parameters do it have, and how is it used? Invites you to read the track.
Python syntax of locals () function
locals()
- There are no parameters and arguments in the function.
Value returned from locals
The locals () function updates and returns the dictionary associated with the current local symbol table.
Example: How does the locals () function work?
locals()
Run the program, the result is:
{'In': ['', 'locals()'],
'Out': {},
'_': '',
'__': '',
'___': '',
'__builtin__': ,'__builtin__': ,
'__builtins__': ,'__builtins__': ,
'__name__': '__main__',
'_dh': ['/tmp/tmp98r7zamj'],
'_i': '',
'_i1': 'locals()',
'_ih': ['', 'locals()'],
'_ii': '',
'_iii': '',
'_oh': {},
'_sh': ,'_sh': ,
'exit': ,
'get_ipython': >,
'quit': }
Example 2: How does Locals () work in local scope?
def localsNotPresent():
return locals()
def localsPresent():
present = True
return locals()
print('localsNotPresent:', localsNotPresent())
print('localsPresent:', localsPresent())
Running the program results in:
localsNotPresent: {}
localsPresent: {'present': True}
Example 3: Update values with locals ()
def localsPresent():
present = True
print(present)
locals()['present'] = False;
print(present)
localsPresent()
Running the program results in:
True
True
Unlike the globals dictionary that can change the value of a variable, locals do not change information inside the local namespace.
Previous post: The globals () function in Python
Next lesson: List () function in Python
You've just finished reading the article "Python locals () function" edited by the TipsMake team. You can save python-locals-function.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.