w3resource

Python: locals() function

locals()

The locals() function is used to get the local symbol table as a dictionary. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

Version:

(Python 3.2.5)

Syntax:

locals()

Return value:

dictionary representing the current local symbol table

Example: Python locals()

print(locals())

Output:

{'__builtins__': <module 'builtins' (built-in)>, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f778c2ac3c8>, '__spec__': None, '__name__': '__main__', '__file__': '/tmp/sessions/5fae3ce520bc4911/main.py', '__doc__': None, '__cached__': None, '__package__': None}

Example: Python locals() function with Dictionary

def localsExample():
    Example = True
    print(Example)
    locals()['Example'] = False;
    print(Example)

localsExample()

Output:

True
True

Python Code Editor:

Previous: list()
Next: map()

Test your Python skills with w3resource's quiz



Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9