Python globals() function


(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


The globals() function returns a dictionary containing the variables defined in the global namespace. When globals() is called from a function or method, it returns the dictionary representing the global namespace of the module where the function or method is defined, not from where it is called.

Its syntax is as follows:

Let’s take some examples:

Example 1:

module1.py

Expected Output:

The names which start and end with double underscores are special and are defined by the Python interpreter. The variable we have defined in the module comes at last.

Notice that the local variable x defined inside the foo() is not included in the result. To access the local namespace use the locals() function.

Example 2:

module1.py

module2.py

Expected Output:

In this case, globals() call is placed inside the foo() function. When the foo()  function is called from module2, it prints the variables defined in the global namespace of module1 .


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


Leave a Reply

Your email address will not be published. Required fields are marked *