简体   繁体   中英

Why is globals() a function in Python?

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__ ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM