How to accomplish relative import in python

前端 未结 6 1259
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 10:38
stuff/
    __init__.py
    mylib.py
    Foo/
        __init__.py
        main.py
        foo/
            __init__.py
            script.py

s

6条回答
  •  囚心锁ツ
    2020-12-01 11:22

    After fiddling with it a bit more, I realized how to set it up, and for the sake of specificity I won't use foo bar names. My project directory is set up as...

    tools/
        core/
            object_editor/
                # files that need to use ntlib.py
                editor.py # see example at bottom
                __init__.py
            state_editor/
                # files that need to use ntlib.py
                __init__.py
            ntlib.py
            __init__.py # core is the top level package
        LICENSE
        state_editor.py # equivalent to main.py for the state editor
        object_editor.py # equivalent to main.py for the object editor
    

    A line in object_editor.py looks like...

    from core.object_editor import editor
    

    A line in editor.py looks like...

    from .. import ntlib
    

    or alternatively

    from core import ntlib
    

    The key is that in the example I gave in the question, the "main" script was being run from within the package. Once I moved it out, created a specific package (core), and moved the library I wanted the editors to share (ntlib) into that package, everything was hunky-dory.

提交回复
热议问题