I checked some answers like this, but I have another question about which attributes get imported from a module in python.
For example, I have a module temp9.py:
a=10
b=20
print('a={0}, b={1}'.format(a,b))
def t9outer():
print('in imported module')
def t9inner():
print('inner function')
Then I import this module like so: import temp9. If I get the attributes of the imported file using this command:
list(filter(lambda x: not x.startswith('__'),dir(temp9)))
I get this output:
['a', 'b', 't9outer']
My questions are
aandbare global only in the scope oftemp9, not across the modules (as the above answer says), so how does it get exported?Why was
t9inner()not imported even though it is enclosed byt9outer(), which gets imported?
a,bare actually gloabal in scope oftemp9. If you try to access them in your main module - you will get NameError. But, you can access them viatemp9.aortemp9.b. Andt9innerin not listed in dir of module, because it's in scope oft9outer. You can check this viadir(temp9.t9outer)t9innerdoesn't exist at all until you actually callt9outer, and even then the name is only in scope in the body of the function. You can think of adefstatement as a souped-up assignment statement.