Import from a subpackage or the full path difference

Importing the same Python module from another path will result in two different module references.

For example, take the following three Python scripts. Script1 and Script2 are in OuterPackage, TestWithGlobals is in SubPackage.

+ Root
|_+ OuterPackage
  | - Script1
  | - Script2
  |_+ SubPackage
    | - TestWithGlobals

script1:

from OuterPackage.SubPackage import TestWithGlobals
import Script2
print TestWithGlobals.__name__

print TestWithGlobals.global_string
Script2.MakeStringBall()
print TestWithGlobals.global_string

and Script2:

from SubPackage import TestWithGlobals
print TestWithGlobals.__name__

def MakeStringBall():
    TestWithGlobals.global_string = "ball"

and finally TestWithGlobals itself

global_string = "test"

Now that Script1 is running, the output is as follows:

SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
test
test

Changing from SubPackageto from OuterPackage.SubPackagein Script2 will produce a different result for Script1:

OuterPackage.SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
test
ball

The root is added to pythonpath before running Script1.

Why is TestWithGlobals different between Script1 and Script2 while the same module is referencing? What are the reasons for this?

+4
1

, , :

Script1.py

import sys
from OuterPackage.SubPackage import TestWithGlobals
print "In Script1", id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
import Script2
print TestWithGlobals.__name__

print "TestWithGlobals:", TestWithGlobals.global_string
Script2.MakeStringBall()
print "TestWithGlobals:", TestWithGlobals.global_string
print "Script2.TestWithGlobals:", Script2.TestWithGlobals.global_string

Script2.py

from SubPackage import TestWithGlobals
print TestWithGlobals.__name__
import sys

def MakeStringBall():
    print "In MakeStringBall", id(TestWithGlobals)
    print "In MakeStringBall Subpackage.TestWithGlobals", id(sys.modules['SubPackage.TestWithGlobals'])
    print "In MakeStringBall OuterPackage.SubPackage.TestWithGlobals", id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
    TestWithGlobals.global_string = "ball"

:

In Script1 4301912560
SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
TestWithGlobals: test
In MakeStringBall 4301912784
In MakeStringBall Subpackage.TestWithGlobals 4301912784
In MakeStringBall OuterPackage.SubPackage.TestWithGlobals 4301912560
TestWithGlobals: test
Script2.TestWithGlobals: ball

python sys.modules. , 2 ( id).

+1

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


All Articles