python – Importing all functions from a package: from .* import *

python – Importing all functions from a package: from .* import *

You can do it, manually, but you shouldnt.

Why you really do not want to do this:

Youll 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 whats going on. You dont 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

Dont 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. Dont spaghetti your code. Youll want to hit yourself in the future if you opt in for a mesh of all stuff in one place.

Special cases arent special enough to break the rules.

Really self explanatory.

Namespaces are one honking great idea — lets do more of those!

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

  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. Its more pythonic to use __all__. Check here for more details.

python – Importing all functions from a package: from .* import *

Leave a Reply

Your email address will not be published.