简体   繁体   中英

Python packages and import - no module named xy

I'm trying to structure my project like this

app/
__init__.py
web/
    __init__.py
    web.py
database/
    __init__.py
    db.py

I just want to import several classes from db.py to web.py but just a ImportError: No module named is thrown. What I tried so far

web.py

from __future__ import absolute_import
    from database.db import ClassA
OR

from __future__ import absolute_import
from app.database.db import ClassA

OR

from __future__ import absolute_import
import database import ClassA

What do I missing?

// edit:

db/__init __.py
from db import ClassA

All other __init__.py are empty. I guess I'm doing something wrong on this.

It should be

from ..database import db

You can also check the importings by running the web.py from the root of your project

python -m app.web.web

Assuming:

C:\pytest\
   test.py
   \database\
       db.py
       __init__.py
   \subfolder\
       __init__.py
       coolios.py

where __init__.py contains:

from db import *

and the second __init__.py contains:

from coolios import *

and db.py contains:

class WHAM():
    def __init__(self):
        print 'You import me!'

and coolios.py contains:

from database import *

class ganster():
    def __init__(self):
        WHAM()

and test.py contains:

from subfolder import ganster
ganster()

It should work.

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