best way to share an instance of a class among modules?

Michael Torrie torriem at gmail.com
Fri Feb 8 07:05:59 CET 2013


On 02/07/2013 07:14 PM, Rick Johnson wrote:
> On Wednesday, February 6, 2013 7:36:28 PM UTC-6, Ethan Furman wrote:
>> As Michael Torrie pointed out, the 'global' keyword is needed:
> 
> Wrong. The global keyword is in fact NOT needed and something i
> consider to be another wart of the language (PyWart on this subject
> coming soon!).

Actually in both Python 2 and 3, the global keyword is, in fact needed.
 Otherwise the name binding in the function hides the global name.  So
no matter if you declare the variable in the module itself (which yes I
agree you should always do!), you need the global keyword in the
function if you want to overwrite the name in the module's global namespace.

Observe the following code which I tested on both python2 and python3:
--------
from __future__ import print_function

my_global_var = 4

def test_func():
    #global my_global_var
    my_global_var = 6

if __name__ == "__main__":
    print(my_global_var)
    test_func()
    print(my_global_var)

---------

Without the global statement, you get 4 printed out both times.  At
least on the python interpreters I have handy.  With the global
statement uncommented, I get 4 and 6.

Do you understand the difference between binding a name to an object and
variable assignment?  Because that's the reason we see this behavior.
This would be a gotcha in this case.  Not a wart, but simply something
to be aware of.



More information about the Python-list mailing list