Relative imports in Python 3

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

    For PyCharm users:

    I also was getting ImportError: attempted relative import with no known parent package because I was adding the . notation to silence a PyCharm parsing error. PyCharm innaccurately reports not being able to find:

    lib.thing import function

    If you change it to:

    .lib.thing import function

    it silences the error but then you get the aforementioned ImportError: attempted relative import with no known parent package. Just ignore PyCharm's parser. It's wrong and the code runs fine despite what it says.

提交回复
热议问题