Python locals() Function

The locals() function in Python is used to get the current local symbol table in the form of dictionary. For example:

print(locals())

The above program produces the output that looks like:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001CFA47A6D00>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\DEV\\codescracker.com\\codescracker.py', '__cached__': None}

Now if you execute the following code:

v = locals()
print(type(v))

then the output would be:

<class 'dict'>

means that the function locals() returns dict type object

Python locals() Function Syntax

The syntax of locals() function in Python is:

locals()

Python locals() Function Example

Here is an example of locals() function in Python. This program prints the name of current Python program source code's file along with complete directory:

x = locals()
print("This program's source code file with directory:")
print(x["__file__"])

The snapshot given below shows the sample output produced by this program, demonstrating the locals() function:

python locals function

That is, the above Python program file is saved inside the directory C:\Users\DEV\codescracker.com\ with its name as codescracker.txt. But in your case, the output may be different, if you've different file name and/or directory.

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋