Python globals() Built in Function

Python globals() is a built-in function that returns a dictionary containing the current global symbol table. A symbol table is a data structure that stores information about the names and values of variables, functions, classes, etc. in a program. A global symbol table contains the names and values that are accessible from any scope in the program.

Here are some examples of how to use Python globals():

To access and modify a global variable using globals():

x = 10 # global variable
print("The value of x is:", x) # prints 10
globals()["x"] = 20 # modifies x using globals()
print("The value of x is:", x) # prints 20

To get information about the current program using globals():

print("The name of this module is:", globals()["__name__"]) # prints __main__
print("The file name of this module is:", globals()["__file__"]) # prints the file name

To define a new global variable using globals()

globals()["y"] = 30 # defines y as a global variable
print("The value of y is:", y) # prints 30

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions