Import a module from a directory (package) one level up

前端 未结 4 979
抹茶落季
抹茶落季 2021-01-04 08:35

What is the right way in Python to import a module from a directory one level up? The directory is a Python package with all these modules and I have a sub directory with co

4条回答
  •  死守一世寂寞
    2021-01-04 09:04

    Instead of using upper imports, have an entry point that you can call from the upper most level and have your imports relative to that entry point in your recipe.py file.

    Ex:

    pkg1/
       __init__.py  
       main.py
       fruit.py  
       +sub_pkg
          __init__.py
          recipe.py
    

    Where main.py contains:

    #!/usr/bin/env python3
    
    import subpkg.recipe as recipe
    import fruit
    
    if __package__ is None and __name__ == "__main__":
        __package__ = "main"
        print()
        # Call recipe.py or fruit.py methods from here
    

    And in recipe.py:

    import fruit
    # do stuff with fruit module, which is properly imported now
    

    To run, call python3 main.py

提交回复
热议问题