By Gloria Macia via Discussions on Python.org at 26Apr2022 14:15:
Trying to understand the following which is always giving me trouble -
Let’s say, I have a minimalistic python package that looks as follows:
maciamug@maciamug-PNMD6V mygalaxy % tree .
.
├── README.md
├── poetry.lock
├── pyproject.toml
├── src
│ └── mygalaxy
│ ├── __init__.py
│ ├── calc.py
│ └── planet.py
planet.py
uses calc.py
module, I am importing it as follows:
from mygalaxy.calc import planet_mass, planet_vol
This works just fine (trial and error). What I wonder is, why was the following ways not working:
That’s a normal “absolute” import, where the module name has a path from
the top of the tree. It presumes that “src” is in your syspath
list.
from calc import planet_mass, planet_vol
This is an absolute import, and the path is wrong (“calc” is not at the
top of the tree).
or else
from .calc import planet_mass, planet_vol
I’d expect this to work. Can you shows the full error traceback? Also
your sys.path
(inside Python: import sys; print(sys.path)
and/or
$PYTHONPATH
environment variable.
It may matter how you invoked things. Are you:
- invoking something else which imports from
mygalaxy
etc, and finds
it with sys.path
- invoking
planet.py
directly? (in which case I would not expect from mygalaxy.calc
to work)
Can you show the invocation command (how you start Python to test
these)?
My personal habit would be to either (a) install the mygalaxy
package
using pip
or (b) add /path/to/src
to my $PYTHONPATH
environment
variable.
I’d hope to use this form:
from .calc import planet_mass, planet_vol
because planet.py
knows that calc.py
is part of its own package, and
this avoids needing to know the absolute name of the package.
If planet.py
was found by an import, then it knows it is in a package.
If you invoke planet.py
directly, I believe it does not consider it
part of a package, and therefore the relative import path .calc
would
not work.
So a script foo.py
which goes:
from mygalaxy.planet import something
would let planet.py
get to .cacl
.
Cheers,
Cameron Simpson cs@cskk.id.au