Home > Enterprise >  python relative import from same package fails
python relative import from same package fails

Time:06-19

I am working on a project involving the popular aiortc/aioquic github package. Located at src/aioquic/buffer.py there is an import statement:

from ._buffer import Buffer, BufferReadError, BufferWriteError  # noqa

This line is meant to import a C/stub module _buffer.c / _buffer.pyi . When used from the root directory to run examples found in the examples directory this import line will work, but when trying to run in a Docker container from the same directory this import fails and when importing from the /src directory the import fails. I have tried reading several other questions on python relative imports but none seem to make sense to me.

To reproduce the issue:

  1. open python in the src directory
  2. from aioquic import about (works)
  3. from aioquic import buffer (fail)
from aioquic import buffer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/aioquic/src/aioquic/buffer.py", line 1, in <module>
    from ._buffer import Buffer, BufferReadError, BufferWriteError  # noqa
ModuleNotFoundError: No module named 'aioquic._buffer'

I don't understand why the examples http3_client and http3_server work but when trying to import it directly it fails. I thought I understood roughly how to use python imports but apparently not. What would cause the same line to work when running from one directoy but fail when running from another directory? Is it something magical with the PYTHONPATH? I'm hoping someone smarter than I am can explain why this is failing. [EDIT and most importantly how to fix this so the import will work nomatter where the user runs python from. I have tried several different combinations but none seem to work.] Thanks in advance.

CodePudding user response:

I figured out what was wrong. The stub/C module had to be built into a .pyd file before it could imported. This was done by

pip install -e .

on the parent directory

CodePudding user response:

Is it something magical with the PYTHONPATH?

Yes.

Typically . dot (current working directory) will appear in that exported env var, so where you started matters.

Take care to ensure you're using the same env var setting, and the same pwd, during both the interactive and the Docker runs.

  • Related