1

Apologies if that titles a little confusing.

Basically, if I have a submodule that refers any other package (without the full module reference, i.e import foo.bar rather than import project.foo.bar) and produce a package graph using pyreverse, then pyreverse doesn't show that the submodule is using foo.bar.

For example, if I have the following package structure

parent/
--__init__.py
--parent_example.py
--sub/
----__init__.py
----sub_example.py

Where the file sub_example.py contains from parent_example import foo

it produces the following diagram when ran with the command pyreverse parent -o png

enter image description here

However if you import using an absolute path from parent.parent_example import foo and run the same command, it outputs what you would expect

enter image description here

So my question is as follows - if I am importing a module form another package, should I be using an absolute path like in example two (from the root of what is assumed to be the most top level package - in the example case, the parent package), or should I be importing like I am in the first example?

I understand that this might be seen as asking for opinions - I'd like to clarify that I'm looking for the python recommended way (most standard practice, or PEP if it exists) to handle imports

Cheers

Liam Kelly
  • 231
  • 3
  • 15
  • I think you are thinking too much as objects (so parent, children). See modules as unrelated. Naming is just convenience. Use `import parent` in `parent.sub`. Every children should know the name of the parent. – Giacomo Catenazzi Mar 14 '18 at 13:41

1 Answers1

1

"Where the file sub_example.py contains from parent_example import foo"

Above should not even work with the module locations shown.

"However if you import using an absolute path from parent.parent_example import foo"

That is a relative import, that specifies a full absolute path inside the package (that is path from the root of the package). Everything ok with that form.

The first form should read

from ..parent_example import foo

All those files belong (are inside) parent package. And so you can specify the imports with relative imports, from <put.your.path> import some_bar or from <.your.path> import some_bar or from <..your.path> import some_bar, and so on... in any of the modules inside parent.

Whether you use always the full relative path or always partial relative paths is a matter of personal choice.

Usually it makes sense to omit the name of the parent package as it isn't needed and so you can change its name without touching the code inside.

This might be useful to you

progmatico
  • 4,714
  • 1
  • 16
  • 27