'Attempted relative import in non-package' although packages with __init__.py in one directory

前端 未结 1 933
梦谈多话
梦谈多话 2020-12-13 09:34

I have a module named extended.py which contains the following line:

from .basic import BasicModule

and the file basic.p

相关标签:
1条回答
  • 2020-12-13 09:39

    Relative imports only work for packages, but when you importing in extended.py you are running a top-level module instead.

    The current directory may hold a __init__.py file but that doesn't make exended.py part of a package yet.

    For something to be considered a package, you need to import the directory name instead. The following would work:

    main.py
    
    packagename\
        __init__.py
        basic.py
        extended.py
    

    then in main.py put:

    import packagename.extended
    

    and only then is extended part of a package and do relative imports work.

    The relative import now has something to be relative to, the packagename parent.

    0 讨论(0)
提交回复
热议问题