Python locals() Function

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


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\\\\', '__cached__': None}

Now if you execute the following code:

v = locals()

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:


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:")

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\\ 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 »

Follow/Like Us on Facebook

Subscribe Us on YouTube