Relative imports in Python 3

unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that? It’s quite common to have a layout like this… …with a mymodule.py like this… …a myothermodule.py like this… …and a main.py like this… …which works fine when you … Read more

Is “from matplotlib import pyplot as plt” == “import matplotlib.pyplot as plt”?

Even though they are equivalent, I think there is a pretty good argument that the second form import matplotlib.pyplot as plt is objectively more readable: It is generally customary to use import matplotlib.pyplot as plt and suggested in the matplotlib documentation (see http://matplotlib.org/users/pyplot_tutorial.html etc…) so this will be more familiar to most readers. import matplotlib.pyplot … Read more

Relative imports in Python 3

It’s quite common to have a layout like this… …with a mymodule.py like this… …a myothermodule.py like this… …and a main.py like this… …which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to the relative import… The way you’re supposed to run it is… …but it’s somewhat verbose, and doesn’t mix well with a shebang line like #!/usr/bin/env python3. The simplest … Read more

Relative imports in Python 3

unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that? It’s quite common to have a layout like this… …with a mymodule.py like this… …a myothermodule.py like this… …and a main.py like this… …which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to … Read more

Python: ‘ModuleNotFoundError’ when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules. Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. … When importing the package, Python searches through the directories on sys.path looking … Read more

Relative imports – ModuleNotFoundError: No module named x

TL;DR: You can’t do relative imports from the file you execute since __main__ module is not a part of a package. Absolute imports – import something available on sys.path Relative imports – import something relative to the current module, must be a part of a package If you’re running both variants in exactly the same way, one of them should work. Here is … Read more