How to do relative imports in Python?

前端 未结 15 3188
情深已故
情深已故 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:44

    On top of what John B said, it seems like setting the __package__ variable should help, instead of changing __main__ which could screw up other things. But as far as I could test, it doesn't completely work as it should.

    I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in sys.path, as far as I could understand.

    I should also mention that I did not find how to format the string that should go into those variables. Is it "package_head.subfolder.module_name" or what?

提交回复
热议问题