开发者

Importing modules from more advanced layout

Say this is my package layout

Package
    :: core
        :: hash
            :: hashgen.py
            :: validate.py
        :: common
            :: classes.py
    :: tools
        :: database_validate.py
    :: bot.py
    :: config.py

So if I wanted to import database_validate from tools in bot.py I'd do:

from tools import database_validate

But for core/hash/hashgen, how would I import that? Because it's slightly longer. I know I can probably just put everything in one file, but I'm curious of how to make it import from a longer folder layo开发者_如何学运维ut.


When building a package - don't forget the __init__.py. This needs to be in every tree you wish to import from. In your example it should look like this..

Package
    __init__.py
    :: core
        __init__.py
        :: hash
            __init__.py
            :: hashgen.py
            :: validate.py
        :: common
            __init__.py
            :: classes.py
    :: tools
        __init__.py 
       :: database_validate.py
    :: bot.py
    :: config.py

Once this is done then you can as phihag suggested

from package.core.hash.hashgen import *

Although I don't recommend using * per se used here for simplicity.

Check out this - Written by the man himself!


import core.hash.hashgen

Alternatively, for shorter, but potentially confusing code:

from core.hash import hashgen
# Don't forget hashgen now refers to a foreign module


from package.core.hash import hashgen

Your code should be in PYTHONPATH and you should have __init__.py files

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜