Relative imports in Python 3

前端 未结 16 1083
误落风尘
误落风尘 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:14

    Put this inside your package's __init__.py file:

    # For relative imports to work in Python 3.6
    import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
    

    Assuming your package is like this:

    ├── project
    │   ├── package
    │   │   ├── __init__.py
    │   │   ├── module1.py
    │   │   └── module2.py
    │   └── setup.py
    

    Now use regular imports in you package, like:

    # in module2.py
    from module1 import class1
    

    This works in both python 2 and 3.

提交回复
热议问题