importing multiple functions from a Python module
I am importing lots of functions from a module
Is it better to use
from my_module import function1, function2, function3, function4, function5, function6, function7
which is a little messy, but avoids flooding the current namespace with everything from that module or
from my_module import *
Which looks tidy but will fill the namespace with everything from that module.
Can't find anything in PEP8 about what the limit for how much you should import by name is. Which is better and why?
Solution 1:
If you really need that many functions, you are already polluting your namespace.
I would suggest:
import my_module
Or, if my_module has a long name use an alias:
import my_long_module as m
Solution 2:
If it's between one or the other, use
from my_module import function1, function2, function3, function4, function5, function6, function7
See "Explicit is better than implicit." in import this
.
If you just want a shorter name than my_module.function1
, there is always import my_module as mod
.
For the few functions you use many times (either type many times so you want a short name or in a loop so access speed is important), there is
func1 = my_module.function1
Solution 3:
With a little bit of management you can control what import * imports. Say your my_module has function1..function8 but you only want to make functions 1 through 6 available. In your my_module, reassign the __all__
attribute:
my_module.py:
__all__ = ['function1', 'function2', 'function3' ...]
def function1():
...
# etc...
Now if you use from my_module import *
, you'll only import those functions and variables you defined in the __all__
attribute from my_module.py.