Relative imports in Python 3

前端 未结 16 1305
误落风尘
误落风尘 2020-11-21 06:42

I want to import a function from another file in the same directory.

Sometimes it works for me with from .mymodule import myfunction but sometimes I get

16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:04

    To obviate this problem, I devised a solution with the repackage package, which has worked for me for some time. It adds the upper directory to the lib path:

    import repackage
    repackage.up()
    from mypackage.mymodule import myfunction
    

    Repackage can make relative imports that work in a wide range of cases, using an intelligent strategy (inspecting the call stack).

提交回复
热议问题