i cant seem to make this work.
I have 2 python files, lets say a.py and b.py
in a.py is this:
def foo():
global name
name = "foo"
import b
b.bar()
if __name__ == "__main__":
foo()
in b.py this:
import a
def bar():
name = a.name
print(name)
I have three different question in relation to this code:
- Why do i get the error:
AttributeError: 'module' object has no attribute 'name'
I know for certain that b.py cant access the variable defined in the function in b.py but how do i solve this? - does global in this case changes anything? if not, why?
- i tried doing
name = a.foo.name
instead ofname = a.name
but this doesnt do the trick either and gives me:AttributeError: 'function' object has no attribute 'name'
, is this even practicable in any case and what did i do wrong?
Thanks for taking the time and sorry if this seems obvious to some of you, i'am still getting into this.
Scripts aren't modules. Its something of a mind bender but when you run
python3 a.py
,a.py
isn't a module (or more properly, its a module named__main__
) and it will be reloaded when you import.Suppose I have c.py
When I run it I get
To illustrate with your example, if I change b.py to
It works. But only kindof because if somebody imports
a
you've still got two modules and two copies of the variable.If you want shared data, they have to be in imported modules, not top level scripts. When I want shared data, I create a separate module that doesn't import anything (or only imports from the standard library) and it is either empty or has defaults for the variables I want to share.