the global keyword:

Ned Batchelder ned at nedbatchelder.com
Sat Jun 11 23:41:12 EDT 2016


On Saturday, June 11, 2016 at 8:13:50 PM UTC-4, Marcin Rak wrote:
> On Saturday, 11 June 2016 19:09:29 UTC-5, MRAB  wrote:
> > On 2016-06-12 00:50, Random832 wrote:
> > > On Sat, Jun 11, 2016, at 19:44, Marcin Rak wrote:
> > >> So my question is, how the heck is it possible that I get 5 as the last
> > >> value printed? the global test_var (global to Test.py) I set to 44 when I
> > >> ran some_function()???  does anyone have a clue they could throw my way?
> > >
> > > Importing a variable from a module copies its value into your own
> > > module's variable. Updates to the source module's variable will not be
> > > reflected in your module.
> > >
> > Not true. Importing doesn't copy the value.
> > 
> > Importing a name creates a new name in the local scope that refers to 
> > the same object that the imported name referred to.
> 
> If that's the case, how is it that I get 5 for test_var???

Assignment makes a name refer to a value:

    x = 12        # Now x refers to 12

More than one name can refer to a value:

    x = 12
    y = x         # Now x and y both refer to 12

Re-assigning one name doesn't affect other names referring to 
the old value:

    x = 12
    y = x
    x = 24        # Now x refers to 24, and y still refers to 12

Each module has its own globals (this makes the name "global" a bit
of a misnomer.  Importing a name from a module is an assignment
statement in disguise, and each module has its own names:

    # Test.py
    test_var = 5

    # Solver.py
    from Test import test_var
        # This import is effectively:
        #    Solver.test_var = Test.test_var
        #
        # Now Test.test_var and Solver.test_var both refer to 5

Reassigning one name doesn't affect other names referring to
the old value:

    # Test.py
        global test_var
        test_var = 44 
            # Test.test_var refers to 44
            # Solver.test_var still refers to 5

After all of your code is run, the test_var in Solver.py is still 5.

A longer explanation is at http://bit.ly/pynames1 that may help.

--Ned.



More information about the Python-list mailing list