global variable across modules

John Pote johnhpote at o2.co.uk
Wed Sep 11 17:49:09 EDT 2013


Chris,
Interesting. 
> 
> # Test1.py
> Debug_Value = " "
> 
> # Test2.py
> from Test1 import *
> # is exactly equivalent to
> Debug_Value = " "
> 
I take it then that assigning to Debug_Value in Test2.py will not change the value of Debug_Value in Test1.py.

That being the case it would be wrong to assume that the following are identical

import sys

and

from sys import *

(the latter being a convenience  to avoid having to write sys. before every variable).

Thus assigning to sys.stdout would change the standard out destination in every module importing sys whereas

from sys import *
stdout = foo.dst

would only change stdout in the current module and sys.stdout would remain unchanged.

Is my understanding here correct?

As to global usage I do find it useful to have a file called something like 'preferences.py' and put in there constants to be used throughout the application. But I use these strictly read only. It is good in that system wide constants are defined in one place only. Also if the constants are put inside a class, possibly with getter methods, instantiated as a singleton then initially the values can be typed directly into the preferences file. Later the constructor could be changed to read the constants from an initialisation file of your own format (e.g. .ini or JSON). Thus users without python experience might find it easier to change them without having to look at any python code. On the other hand I appreciate simple constant assignments should be easy enough to change without needing to know any Python.

Also remember that accessing any form of global that is shared between multiple threads is a recipe for disaster unless appropriate locks are used. A significant advantage of not using globals (except for system wide constants) is that is makes testing of individual modules easier. The less coupling there is between modules the easier it is to understand and test.

Regards all,
John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130911/82a1f809/attachment.html>


More information about the Python-list mailing list