0

Under the same directory, I have a main.py and a module.py. I want to call module.py from main.py using the handle mod. Normally, what I'd just write in main.py:

import module as mod

However, I found out by dumb trial and error that the above does not work when I'm in a Docker container. In such cases, I'd need to write

from . import module as mod

which in turn wouldn't work in a "normal" environment, i.e., on my local machine.

I have a vague suspicion that this has something to do with pathnames, but it's not clear to me why things work this way. Ideally, I would have liked the Python code to work the exact same way regardless of whether it's run from within a container or not.

Tfovid
  • 761
  • 2
  • 8
  • 24
  • 2
    The first is an absolute import; the second is a relative import. Docker isn't really relevant; the question is how and where is `module` installed, and where is the script that uses it installed? – chepner Jul 21 '21 at 19:06
  • Does https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time help? Or any of the other results for `relative import [python]`? – Karl Knechtel Jul 21 '21 at 19:18

2 Answers2

1

Let's ignore the as, as that is only relevant for determining the variable the module will be bound to.

import module is an absolute import. module must be found in a directory that is listed in sys.path. This will work if module is in the current working directory when execute main.py, but in general that won't be the case.

from . import module is a relative import. module must be found in the current package, which is (most likely) whatever directory contains the module that's trying to import module. This works when the code trying to import module.py is in the same directory as module.py, regardless of where that is compared to the current working directory.

So the question is, how are you installing your code in your Docker image?

chepner
  • 497,756
  • 71
  • 530
  • 681
0

import module as mod: This imports the module called "module" as "mod", which could also be from the site-packages directory, this syntax can be used in every Python script.

from . import module as mod: This imports the module called "module" as "mod", but it has to be in the exact same directory as the script which is importing it, this syntax can only be used in module scripts, not in the main script.

AceKiron
  • 56
  • 11