Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is globals() a function in Python?

Tags:

python

global

Python offers the function globals() to access a dictionary of all global variables. Why is that a function and not a variable? The following works:

g = globals()
g["foo"] = "bar"
print foo # Works and outputs "bar"

What is the rationale behind hiding globals in a function? And is it better to call it only once and store a reference somewhere or should I call it each time I need it?

IMHO, this is not a duplicate of Reason for globals() in Python?, because I'm not asking why globals() exist but rather why it must be a function (instead of a variable __globals__).

like image 264
Rolf Kreibaum Avatar asked Jun 20 '15 21:06

Rolf Kreibaum


People also ask

What is globals () function in Python?

Python – globals() function globals() function in Python returns the dictionary of current global symbol table. Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.

Why global is used in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

What does global mean in Python?

In the programming world, a global variable in Python means having a scope throughout the program, i.e., a global variable value is accessible throughout the program unless shadowed. A global variable in Python is often declared as the top of the program.

Can you define a global variable in a function?

Global variables are variables that are accessible regardless of scope. Traditionally, functions operate within a local scope with limited access to variables that are not passed as a parameter. Setting a variable as global breaks the rules of encapsulation so that the specified variable is more accessible.


1 Answers

Because it may depend on the Python implementation how much work it is to build that dictionary.

In CPython, globals are kept in just another mapping, and calling the globals() function returns a reference to that mapping. But other Python implementations are free to create a separate dictionary for the object, as needed, on demand.

This mirrors the locals() function, which in CPython has to create a dictionary on demand because locals are normally stored in an array (local names are translated to array access in CPython bytecode).

So you'd call globals() when you need access to the mapping of global names. Storing a reference to that mapping works in CPython, but don't count on other this in other implementations.

like image 135
Martijn Pieters Avatar answered Oct 13 '22 19:10

Martijn Pieters