简体   繁体   中英

Absolute import doesn't work in Python 3.7

I have a directory set up like this

Project
   |
   |folder1
   |  |folder2
   |  |  |Script_A.py
   |
   |folder3
   |  |Script_B.py

I am trying to access a class named ClassB residing in Script_B.py from Script_A.py in Python 3.7. I am trying to achieve this using absolute imports. Here is the content of Script_A.py:

from folder3.Script_B import ClassB

There seems to be something I am missing. I don't understand how Script_A is supposed to be aware of the existence of Script_B or even of the folder folder3 or even of Project . What tells python to look for these folders?

I have read PEP328 and this doesn't answer any of my questions.

I would use __init__.py , just an empty file, that transform folders to modules:

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
        subpackage2_1/
              __init___.py
              deep_module.py
module_test.py

This will allow(in module_test.py )

from package.subpackage2.subpackage2_1 import deep_module

If deep_module has a class Foo

# deep_module.py
class Foo: pass

We can import Foo as

from package.subpackage2.subpackage2_1.deep_module import Foo

I would not recommend this kind of imports as they are hard to debug.

You could do:

from package.subpackage2.subpackage2_1 import deep_module

# it helps to know where class is coming from
foo = deep_module.Foo()

Which is better than importing Foo directly but yet still I will always try to avoid it for readability sake ;)

If the call is made in package directory, then

from subpackage2.subpackage2_1 import deep_module

Terrible Idea

Or this, that will work everywhere

# terrible hack is to add your package to your sys path
import sys
sys.path.insert(0,'path_to_package')

from package.subpackage2.subpackage2_1 import deep_module

Better Idea

Run your script with PYTHONPATH

PYTHONPATH="$PWD/path_to_package"  python code.py

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