Importing all functions from a package: "from .* import *"

Question:

Goal

I want to be able to import (on the __init__.py) all functions from every single file inside my package.

Usage

For example in this folder structure.

manage.py
- scripts/
   -- __init__.py
   -- tests.py
   -- deploy.py

I am currently doing the following:

manage.py:

from scripts import *

script/init.py:

from .tests import *
from .deploy import *

But, every time I add another file to the package I have to add an import line on script/__init__.py, which is kind of annoying.

Asked By: CESCO

||

Answers:

  1. importlib allows you to import any Python module from a string name. You can automate it with going through the list of files in the path.

  2. It’s more pythonic to use __all__. Check here for more details.

Answered By: Dhia

You can do it, manually, but you shouldn’t.

Why you really do not want to do this:

You’ll end up with a namespace where understanding what is what and from where it came from will be extremely hard, with difficulty increasing as the size of the overall project does. Appart from being completely unintuitive for Python, think of anybody else that might view your code or even worse, think about yourself re-reading it after 1 month and not remembering what’s going on. You don’t need that in your life.

In addition to that, any functions you expose to the importer that might overlap with other functions in other modules are going to get shaddowed by the most recent one imported. As an example, think of two scripts that contain the same function foo() and watch what happens.

>>> from scrpt1 import *
>>> foo()
Script 1
>>> from scrpt2 import *
>>> foo()
Script 2

Don’t need that in your life either. Especially when it is so easy to bypass by being explicit.


Here are some related lines from the text contained in import this:

Explicit is better than implicit.

Be explicit about the place where your functions are defined in. Don’t “spaghetti” your code. You’ll want to hit yourself in the future if you opt in for a mesh of all stuff in one place.

Special cases aren’t special enough to break the rules.

Really self explanatory.

Namespaces are one honking great idea — let’s do more of those!

“more of those!”, not less; don’t miss out on how wonderful namespaces are. Python is based on them; segregating your code in different namespaces is the foundation of organizing code.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.