Reason for globals() in Python?
It's also useful when you need to call a function using function's string name. For example:
def foo():
pass
function_name_as_string = 'foo'
globals()[function_name_as_string]() # foo().
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.
The rationale behind it, I'm sure, is the same as that of using locals()
to see the variables defined in a function, or using dir
to see the contents of a module, or the attributes of an object.
Coming from a C++ background, I can understand that these things seem unnecessary. In a statically linked, statically typed environment, they absolutely would be. In that case, it is known at compile time exactly what variables are global, and what members an object will have, and even what names are exported by another compilation unit.
In a dynamic language, however, these things are not fixed; they can change depending on how code is imported, or even during run time. For that reason at least, having access to this sort of information in a debugger can be invaluable.