Skip to content Skip to sidebar Skip to footer

Python - What Priority Does Global Have?

I'm a bit confused about globals when it comes to packages using other packages. From a quick google search; there's not much that explains. Simply put: at what level is a variable

Solution 1:

How global are global variables?

So-called "global" variables in Python are really module-level. There are actually-global globals, which live in the __builtin__ module in Python 2 or builtins in Python 3, but you shouldn't touch those. (Also, note the presence or lack of an s. __builtins__ is its own weird thing.)

What does the global statement do?

The global statement means that, for just the function in which it appears, the specified variable name or names refer to the "global" (module-level) variable(s), rather than local variables.

What about import *?

Oh god, don't do that. Globals are bad enough, but importing them is worse, and doing it with import * is just about the worst way you could do it. What the import system does with global variables is horribly surprising to new programmers and almost never what you want.

When you do import *, that doesn't mean that your module starts looking in the imported module's global variables for variable lookup. It means that Python looks in the imported module, finds its "public" global variables*, and assigns their current values to identically-named new global variables in the current module.

That means that any assignments to your new global variables won't affect the originals, and any assignments to the originals won't affect your new variables. Any functions you imported with import * are still looking at the original variables, so they won't see changes you make to your copies, and you won't see changes they make to theirs. The results are a confusing mess.

Seriously, if you absolutely must use another module's global variables, import it with the import othermodule syntax and access the globals with othermodule.whatever_global.


*If the module defines an __all__ list, the "public" globals are the variables whose names appear in that list. Otherwise, they're the variables whose names don't start with an underscore. defined functions are stored in ordinary variables, so those get included under the same criteria as other variables.

Post a Comment for "Python - What Priority Does Global Have?"