2

Please guide me on the pythonic way for a minor code-standards question. Searching SO re imports gets me many discussions comparing import foo vs from foo import bar which is not my concern here. Still I apologize if I am creating a dupe Q.

My team sometimes puts up code for review with import statements like below and I'm struggling to give advice:

Module our_a.py has a classic import statement, this is fine:

from famous_package import some_function
# .. call the famous package's some_function()

Module our_b.py imports the same symbol, but from our_a not from famous_package:

from our_a import some_function
# .. call the famous package's some_function()

Is there a name for this practice? Indirect import? Re-import?? Anyhow it works fine, and flake8 does not complain about import statements in module our_b. Is there any benefit here? My instinct says, our_b should just import some_function from famous_package directly. Thanks in adv for your insights.

chrisinmtown
  • 3,571
  • 3
  • 34
  • 43
  • 1
    I'd agree with your statement/instinct, it creates tighter coupling and an uneeded dependency between the 2 modules. I'd guess it makes sense in some way if they rely on each other heavily, but then I'd probably argue combining them (unless one module was used as some type of utility elsewhere)...this seems off to me and personally I'd argue against it because it makes the code slightly harder to read – ViaTech Apr 19 '23 at 12:47
  • 1
    The term I've always used for this is "transitive imports", and yes it's bad practice. If you *want* to re-export one of your imports from a module you write, you can write an explicit `__all__` that includes it. I believe mypy has a setting that disables transitive imports unless explicitly requested with `__all__` as well. – Silvio Mayolo Apr 19 '23 at 16:55
  • Thanks @SilvioMayolo if you post as an answer I will accept. Maybe please clarify your advice about using `__all__` bcos it's not necessary to include a symbol there for it to be seen elsewhere, I think changing that is a way to *restrict* visible symbols. – chrisinmtown Apr 20 '23 at 10:12

0 Answers0