importing multiple functions from a Python module

PythonCoding StyleImport

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 - Python

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 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJim JeffriesView Question on Stackoverflow
Solution 1 - PythonKugelView Answer on Stackoverflow
Solution 2 - PythonagfView Answer on Stackoverflow
Solution 3 - PythonManny DView Answer on Stackoverflow