Python globals() Function

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


Because a symbol table contains all the necessary information of the current program. Therefore the above program produces the output that looks like:

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

If you execute the following program:

x = globals()

then the output would be:

<class 'dict'>

means that the function globals() returns global symbol table in the form of dictionary.

Python globals() Function Syntax

The syntax of globals() function in Python is:


Python globals() Function Example

An example of globals() function is already given at the start of this article. But here is another example of this function. This program uses globals() function to find and print the name of current Python program's file.

ob = globals()
print("The name of this Python program's file is:")

The snapshot given below shows the sample output produced by this program, in my case:

python globals function

I've said, that this output is produced using above program, in my case. Because I've named my Python source code's file as codescracker.txt, which is available inside the directory C:\Users\DEV\\. But in your case, the output may be different, if you've different name and/or directory.

Now the question is, what if we provide an invalid key ?
Let's find output using the program given below:

ob = globals()

On executing the above program, the output produced is shown in the snapshot given below:

python globals function example

It means that an exception named KeyError will get raised, when the specified key does not matched. Therefore, I've to modify the above program, that handles this exception using the except block. Here is the program:

ob = globals()
except KeyError:
    print("Invalid Key!")

Now the output would be:

Invalid Key!

Here is another example program of globals() function in Python. This program allows user to define the key's value to find and print whatever the information about the current program, user wants to get:

ob = globals()
print("Enter the Key: ", end="")
key = input()
    val = ob[key]
except KeyError:
    print("\nInvalid Key!")

The sample run with user input __loader__ is shown in the snapshot given below:

python globals function program

Python Online Test

« Previous Function Next Function »

Like/Share Us on Facebook 😋