简体   繁体   中英

python module imports issue

here's a picture of my directory structure:

parts.py
machine/
    __init__.py
    parts.py

I have a directory (a package) called machine

in it there is __init__.py and parts.py

at the same level as machine, there is a file named parts.py

in parts.py, the code looks like this:

#parts.py
class Parts(object):
    pass

in machine.parts the code looks like this

 #machine.parts
 from parts import Parts
 class MachineParts(Parts):
     pass

When I try to import machine.parts, I get an import error. I don't want to change my directory structure. How should I fix this and retain good PEP8 style?

You should make it a package by adding top-level __init__.py and giving some meaningful name to top-level directory:

mypackage
    __init__.py
    parts.py
    machine/
        __init__.py
        parts.py

Then, use absolute imports:

#machine.parts
from mypackage.parts import Parts
class MachineParts(Parts):
    pass

Since import supports relative imports, try:

from ..parts import Parts

Another option is to use an absolute import:

from appname.parts import Parts

As mentioned in How to import a Python class that is in a directory above?

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