How do I make these relative imports work in Python 3?

前端 未结 1 1969
渐次进展
渐次进展 2021-01-15 01:13

I have a directory structure that looks like this:

project/
        __init__.py
        foo/
            __init.py__
            first.py
            second.         


        
相关标签:
1条回答
  • 2021-01-15 01:46

    Edit: I did misunderstand the question: No __all__ is not restricted to just modules.

    One question is why you want to do a relative import. There is nothing wrong with doing from project.foo import *, here. Secondly, the __all__ restriction on foo won't prevent you from doing from project.foo.first import WonderfulThing, or just from .first import WonderfulThing, which still will be the best way.

    And if you really want to import a a lot of things, it's probably best to do from project import foo, and then use the things with foo.WonderfulThing instead for doing an import * and then using WonderfulThing directly.

    However to answer your direct question, to import from the __init__ file in second.py you do this:

    from . import WonderfulThing
    

    or

    from . import *
    
    0 讨论(0)
提交回复
热议问题