Import behavior when accessing global variables in Python

In bar.py :

var = 1
def set_var():
    global var
    var = 2

In foo.py :

from bar import *

print(var)
set_var()
print(var)

In foo2.py :

import bar

print(bar.var)
bar.set_var()
print(bar.var)

If I run foo.py, the output will be as follows:

1
1

but if I run foo2.py, the output will look like this:

1
2

as I expected.

I would only like to understand this behavior, as I am new to Python and have not found a good reason for this.

PD: More information. I want to develop a module that uses a singleton object, and I have old code that uses this object. I would prefer not to prefix every link to this object in the inherited code, so I would nevertheless want the import of the module using the import object library to help.

, , , , (bar.py). , - , foo.py.

.

EDITED:

bar.py

var_list = list(range(0, 2))
var_list2 = list(range(0, 2))

def set_var():
    global var_list
    var_list = list(range(0, 3))
    var_list2.append(2)

foo.py

from bar import *

print(var_list)
print(var_list2)
set_var()
print(var_list)
print(var_list2) 

:

[0, 1]
[0, 1]
[0, 1]
[0, 1, 2]

, set_var list(), foo.py , var_list ( , bar.var_list). .

+3
2

"var" bar.py - bar.var. ( __main__.var, ). / , , - , , from bar import ....

+1

:

  • @Ignacio, "" python .

  • python ( , , ). , , .

, foo :

# import
foo.var = bar.var
foo.set_var = bar.set_var

print(foo.var)
foo.set_var()   # sets bar.var
print(foo.var)

foo2, , bar.var.

: , , . , var_list2 ( , ). var_list, var.

+1

All Articles