accessing "module scope" vars
Solution 1
You probably want to read up on Python's namespaces. Way 1 is correct but generally unnecessary, never use 2. An easier approach is to just use a dict (or class or some other object):
my_globals = {'var': None}
def my_func():
my_globals['var'] = 'something else'
Assignments always go into the innermost scope and the innermost scope is always searched first, thus the need for the global keyword. In this case you aren't assigning to a name, so it's unnecessary.
Solution 2
Way 1 is the correct way when you absolutely must rebind a global variable. However you should ask yourself why you are modifying a global and whether there is something better you can do (such as encapsulating the behaviour in a class).
Importing a module into itself should be avoided as it is error prone. If the module is also a script you would sometimes need to import __main__
instead, or if the module is part of a package maybe you should be importing foo.my_module
. In short, don't do that.
Solution 3
Importing a module within itself can have unwanted side effects (like evaluating statements more than once.) I would suggest using "Way 1" and a tool like pylint to help verify your code and enforce common practices.
PyLint can be found at: http://www.logilab.org/project/pylint
Solution 4
Avoid setting globals at all. You can create new namespaces with classes quite easily, so use class variables if you must.
For anything serious you need a proper design with classes anyways.
![Frosty Z](https://i.stack.imgur.com/5mhgK.jpg?s=256&g=1)
Comments
-
Frosty Z over 3 years
I'm currently learning Python, and I have to work on a Python 2.7 project.
Accessing "module scope" variables in functions of the module itself is a bit confusing for me, and I didn't succeed in finding a satisfying way.
My attempts so far:
Way 1:
my_module.py
my_global_var = None def my_func(): global my_global_var my_global_var = 'something_else'
Here I think that confusing local and "module scope" vars may be quite easy.
Way 2:
my_module.py
import my_module my_global_var = None def my_func(): my_module.my_global_var = 'something_else'
Here, the name of "my_module" could not be as easily changed as "way 1" when necessary. Plus, importing a module into itself sounds quite weird.
What would you recommend? Or would you suggest something else? Thanks.
-
Frosty Z almost 13 yearsAh. So dict values can be modified in function scope, but not raw string values. Python seems quite counter-intuitive here. Anyway, this works and suits exactly my need. thanks
-
Frosty Z almost 13 yearsThanks for your answer. I would like to create a singleton, and the recommended way seems to simply create a module (see stackoverflow.com/questions/31875/…), so I would prefer avoid a class in this particular case.
-
zeekay almost 13 yearsAssignments always go into the innermost scope and are always searched first, thus the need for the
global
keyword. In this case you aren't assigning to a name, so it's unnecessary (Python will search innermost scope, and not findingmy_globals
eventually reach the module-level scope. -
Frosty Z almost 13 yearsThanks for the detailed explanations on this behavior. I understand better.
-
Mark Evans almost 13 years@FrostyZ - I'd advise against using the module as a singleton, if for no other reason than it makes unit testing really difficult. See <stackoverflow.com/questions/31875/…>
-
Frosty Z almost 13 yearsEven for testing, some singletons seem acceptable (e.g. a logger). See googletesting.blogspot.com/2008/08/…
-
High schooler about 10 years@FrostyZ You can modify any mutable object without using global keyword.
-
yair about 5 yearsThanks for this answer. One question please: so using a dict is good just as long as you don't have any local variables carrying the same name as the dict? Doesn't that mean relying on a convention between the developers that might not be respected? I guess that preventing name clashes with one global variable is a lot better than preventing clashes with an unlimited number of global variables. However, wouldn't it just be better off explicitly declaring
global
before using the variable(s)?