Python global variables: import vs. execfile

I put the method in mymodule.py file:

def do_something():
    global a
    a=1

If i try

>>> execfile('mymodule.py')
>>> do_something()
>>> print a

I get "1" as I expect. But if I import a module,

>>> from mymodule import *

and then run do_something (), then the python session knows nothing about the variable "a".

Can someone explain the difference to me? Thanks.

+4
source share
2 answers

In the second part, where you import mymodule, the reason why it does not appear is because it ais global for the namespace mymodule, as it is done.

Try:

print mymodule.a

Fingerprints:

1

As expected.

According to the Python Documentation :

- , . , . , .

, , .

, , , , .

+1

execfile globals, locals, . ( , execfile)

import mymodule .

+3

Source: https://habr.com/ru/post/1525154/


All Articles