python logo

Python Commandments

Python locals function

The locals() function returns all local variables for the current location with a dictionary type.

It returns True for functions, methods, lambda functions, classes, and class instances that implement the call method.

syntax

locals()

Description of parameters.

  • none

Return value.

  • Returns local variables of the dictionary type

locals() example

The locals() function returns all the variables in the local scope, as opposed to the variables in the global scope. The following example shows how to use the locals() function

def adult(name): #2 local variables name, age
    age = 18
    print(locals())
adult('Tom') # returns a dictionary of name/value pairs

output

{'age': 18, 'name': 'Tom'}

example 2

The following example shows how locals() can be used.

def localexp(arg):
    z = 1
    print(locals())

localexp(4)

results in:

{'z': 1, 'arg': 4}

example 3

Another example of using the locals() function. It returns the local variables for various scopes.

>>> a = 2
>>> b = 4
>>> print(locals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 4}
>>>

Get local variables in a loop:

>>> for i in range(5):
...     c = 3
...     print(locals())
... 
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 4, 'i':     0, 'c': 3}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 4, 'i':     1, 'c': 3}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 4, 'i':     2, 'c': 3}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 4, 'i':     3, 'c': 3}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 4, 'i':     4, 'c': 3}
>>>

Get local variables in a function:

>>> def function(x):
...     b = 3
...     print(locals())
... 
>>> function(4)
{'x': 4, 'b': 3}
>>>