Howto import modules with dependencies in the same absolute/relative path with imp?

前端 未结 2 984
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 15:31

Is there a way to import modules with dependencies within the same directory using an absolute/relative path with \"imp\" ?

Here follows the directory structure:

相关标签:
2条回答
  • 2021-01-11 16:23

    IMO this is not feasible with load_source which doesn't do necessary things so that import in your 'dependant.py' file consider its parent directory.

    You should either do what have been suggested (__init__.py in the directory and absolute import in the module), or use lower-level find_module / load_module functions which allows this kind of things (see find_module 'path' argument)

    0 讨论(0)
  • 2021-01-11 16:23

    You need to have __init__.py in importFrom directory.

    In [5]: ls importFrom/
    dependance.py  dependant.pyc  dependence.pyc  __init__.pyc
    dependant.py   dependence.py  __init__.py
    
    In [6]: from importFrom import dependant
    
    In [7]: dependant.dependence
    Out[7]: <module 'importFrom.dependence' from    'importFrom/dependence.py'>
    

    Instead of importing dependant in test, I have used Python interpreter to show the output. In dependant.py, dependance is imported.

    0 讨论(0)
提交回复
热议问题