Python Built-in Methods – Python globals() Function

Python globals() Function

Returns the global symbol table as a dictionary

Usage

The globals() function returns the global symbol table as a dictionary. It contains information about all global variables.

Each key in the dictionary holds the name of the variable. This dictionary is also accessible from within functions and can be used to update global variables directly.

For example,

# Declare some global variables
a = 10
b = 20
c = 30
d = 40

# Print the current global symbol table
print(globals())

# Prints {'__name__': '__main__',
#        '__doc__': None,
#        '__package__': None,
#        '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fed1a254358>,
#        '__spec__': None,
#        '__annotations__': {},
#        '__builtins__': <module 'builtins' (built-in)>,
#        '__file__': 'main.py',
#        '__cached__': None,
#        'a': 10,
#        'b': 20,
#        'c': 30,
#        'd': 40 }

Highlighted pairs are global variables, declared earlier.

Syntax

globals()

What is a symbol table?

A symbol table is maintained by a compiler. It contains necessary information about the current program.

There are two kinds of symbol table.

  • Local symbol table – contains information related to the local scope of the program
  • Global symbol table – contains information related to the global scope of the program

Why is it necessary?

Python gives the programmer a large number of tools for introspecting the running environment. globals() is just one of those, and it can be very useful in a debugging session to see what objects the global scope actually contains.

Global and Local Scope

A variable declared outside a function has a Global Scope and can be accessed inside or outside of a function. But you cannot update it inside a function.

However, a variable declared within a function has a Local Scope and can only be accessed within that function.

x = 5       # global scope

def myfunc():
    x = 10  # local scope
    print('x inside function is', x)    

myfunc()
# Prints x inside function is 10

print('x outside function is', x)
# Prints x outside function is 5

Here, the value of global variable x didn’t change. Because, Python created a new local variable named x; which disappears when the function ends, and has no effect on the global variable.

Access global variables

As globals() method returns a dictionary, you can perform any operation that a dictionary supports, like indexing, iteration etc.

# Get the value of global variable 'x'
x = 10
print(globals()['x'])
# Prints 10

You can access other global variables such as filename, package, or docstring from current global symbol table.

# Get the filename of the current program
print(globals()['__file__'])
# Prints main.py

Modify global variables

Using globals() function you can update a global variable from a no-global scope, e.g. inside a function.

# Update global variable x inside a function

x = 5       # global scope

def myfunc():
    x = 10  # local scope
    globals()['x'] = 99    # update global x
    print('x inside function is', x)    

myfunc()
# Prints x inside function is 10

print('x outside function is', x)
# Prints x outside function is 99

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.