What happens to module's variables after a "from module import" ?

Paul Moore p.f.moore at gmail.com
Tue Nov 7 10:50:23 EST 2017


On 7 November 2017 at 15:39, ast <nomail at com.invalid> wrote:
> Hello
>> Here is my module tmp.py:
>> a=0
>> def test():
> global a
> print(a)
> a+=1
>> If I import function "test" from module "tmp" with:
>>>>> from tmp import test
>>> it works
>>>>> test()
>> 0
>>>>>>>> test()
>> 1
>> But where variable "a" is located ? I can't find it anywhere

It's in the "tmp" module, where you defined it. But because you didn't
ask for a reference to it in your import statement, it's not
accessible to you[1].
Do
 import tmp
 print(tmp.a)
and you can see it.
Paul
[1] Technically you can find it via the globals of the function test,
as test.__globals__['a'], but if you understand how that works, you
wouldn't have been asking the question in the first place :-)


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /