Error importing package in Python 3.5

I have the following folder structure:

/main
    main.py
    /io
        __init__.py
        foo.py

In Python 2.7, I would write the main.pyfollowing:

import io.foo

or

from io.foo import *

wheareas in Python 3.5 I get an import error:

Traceback (most recent call last):
  File "./main.py", line 6, in <module>
    import io.foo
ImportError: No module named 'io.foo'; 'io' is not a package

I have not found any help yet.

+4
source share
2 answers

iois a built-in module . Do not call your local packages the same as the built-in module.

+4
source

While @ErikCederstrand's answer is correct and probably sufficient for you, I was curious why it failed, so I started digging through the cpython source. So, for any future visitors, here is what I found.

, , : https://github.com/python/cpython/blob/3.4/Lib/importlib/_bootstrap.py#L2207

2209 , :

parent = name.rpartition('.')[0]  #  Value of 'io'

io, . , if false, , "io":

if name in sys.modules:
    return sys.modules[name]
parent_module = sys.modules[parent]

, , (io ) __path__. , , , , , :

try:
    path = parent_module.__path__
except AttributeError:
    msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
    raise ImportError(msg, name=name)

, , , , parent_module.__ path__ , , .

, TL;DR: , , , , , , io.

EDIT: , __path__ , init_module_attrs:

 if _override or getattr(module, '__path__', None) is None:
     if spec.submodule_search_locations is not None:
         try:
             module.__path__ = spec.submodule_search_locations
         except AttributeError:
             pass
+2

Source: https://habr.com/ru/post/1695869/


All Articles