简体   繁体   中英

Importing the same Python object from the same file but from two different locations results in two different object types

I have a project organized in directories as follows:

|main_dir/
|        /__init__.py
|        /core/
|             /__init__.py
|             /foo.py
|             /test1.py            
|        /scr/
|            /test2.py

In foo.py, I define a class as follows

class foo(object):
    def __init__(self):
        pass

This is what I have in core/test1.py

from foo import foo
f1=foo()
print(type(f1))

This is what I have in scr/test2.py:

import sys
sys.path.append('../')
from core.foo import foo

f2 = foo()
print(type(f2))

main_dir/__init__.py contains this:

__all__ = ["core"]

import sys, os
dir = os.path.dirname(__file__)

for subpackage in __all__:
     sys.path.append(os.path.join(dir,subpackage))

and core/__init__.py contains:

__all__ = ["foo"]
import sys, os
dir = os.path.dirname(__file__)

for subpackage in __all__:
   sys.path.append(os.path.join(dir,subpackage))

When I run test1.py, the result is class 'foo.foo'> while when I run test2.py, I get <class 'core.foo.foo'> . I understand that this is how Python behaves, but I am not sure how to get around it. I would like to get True when checking type(f1) == type(f2) as I need to access the object foo for different locations.

Add the first two lines from test2.py:

import sys
sys.path.append('../')

to the top of test1.py. Then change your imports of foo in test1.py and test2.py to use the fully-qualified name:

from main_dir.core.foo import foo

Afterward:

# core/test.py
<class 'main_dir.core.foo.foo'>
# scr/test2.py
<class 'main_dir.core.foo.foo'>

I think in file core/test1.py You can try to import foo like this

from .foo import foo

with the dot before the file name to ensure that is the file in the same directory gave it a try

or

You can import foo using as like it down

from .foo import foo as foo_one
from core.foo import foo as foo_core

I hope I understand what do you need and I hope it will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM