Relative import of package __init__.py

早过忘川 提交于 2019-12-05 01:22:13

There's nothing special about the dunders (they're just discouraged when writing your own module/function names); you should just be able to do

from .__init__ import my_function as local_name
  • python2 and python3 (uses the discouraged __import__):

    • from 1st level module (pkg.foo, pgk.bar, ...):

      local_name = __import__("", globals(), locals(), [], 1)
      
    • from module in subpackage (pkg.subpkg.foo, ...):

      local_name = __import__("", globals(), locals(), [], 2)
      
  • python3 only*:

    • From pkg.foo or pkg.bar:

      import importlib
      local_name = importlib.import_module("..", __name__)
      
    • From pkg.subpkg.baz:

      import importlib
      local_name = importlib.import_module("...", __name__)
      

*import_module on python2 tries load pkg. in this case, unfortunately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!