2

module_a is the main module of the package whereas module_b is just another module in package

package
|-------- __init__.py
|-------- module_a.py 
+-------- module_b.py 

How does from .module_b import Test differ from a direct import like from module_b import Test

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • For one thing, the former will fail if you try to run `module_a` directly, rather than importing from `package`. – jonrsharpe Jun 27 '15 at 18:14
  • Perhaps if I had modules with names in the standard library I could differentiate between modules that I have created in the local package. – Malik Brahimi Jun 27 '15 at 18:16
  • It's not really clear what you're trying to achieve, and why. Should this be a package, or not? – jonrsharpe Jun 27 '15 at 18:20
  • The only difference for me is that `from .module_b import Test` raises an error. – timakro Jun 27 '15 at 18:22
  • If that's your question, see e.g. http://programmers.stackexchange.com/q/159503/110531, http://stackoverflow.com/q/14132789/3001761 – jonrsharpe Jun 27 '15 at 18:23
  • The first answer on the Programmers question highlights one reason - an explicit relative import makes it clearer that `module_b` is in the same package, not the standard library or some third-party package. – jonrsharpe Jun 27 '15 at 18:32
  • [*"With the shift to absolute imports, the question arose whether relative imports should be allowed at all. Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports."*](https://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports) – jonrsharpe Jun 27 '15 at 18:39

0 Answers0