How to do relative imports in Python?

前端 未结 15 2811
情深已故
情深已故 2020-11-21 04:47

Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I\'

15条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 05:32

    This is unfortunately a sys.path hack, but it works quite well.

    I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.

    what I wanted to do was the following (the module I was working from was module3):

    mymodule\
       __init__.py
       mymodule1\
          __init__.py
          mymodule1_1
       mymodule2\
          __init__.py
          mymodule2_1
    
    
    import mymodule.mymodule1.mymodule1_1  
    

    Note that I have already installed mymodule, but in my installation I do not have "mymodule1"

    and I would get an ImportError because it was trying to import from my installed modules.

    I tried to do a sys.path.append, and that didn't work. What did work was a sys.path.insert

    if __name__ == '__main__':
        sys.path.insert(0, '../..')
    

    So kind of a hack, but got it all to work! So keep in mind, if you want your decision to override other paths then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)

提交回复
热议问题