pepper
pepper

Reputation: 2197

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?

Upvotes: 0

Views: 61

Answers (2)

alexanderlukanin13
alexanderlukanin13

Reputation: 4725

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

Upvotes: 1

Sina Khelil
Sina Khelil

Reputation: 1991

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?

Upvotes: 0

Related Questions