importing multiple functions from a Python module
Asked Answered
C

4

64

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?

Consistent answered 20/7, 2011 at 12:23 Comment(0)
C
66

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
Clausius answered 20/7, 2011 at 12:25 Comment(0)
F
48

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
Fusain answered 20/7, 2011 at 12:30 Comment(1)
Is there a tool to search through my_module and list all the functions used so you can autogenerate the line: from my_module import function1, function2, function3, function4, function5, function6, function7...Pore
W
17

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.

Whyalla answered 20/7, 2011 at 12:31 Comment(3)
What if the module is some inbuilt or 3rd party module which you cannot or don't want to edit?Jacklight
Then you probably couldn't/shouldn't do this. I assumed by the file name that it was something he's creating.Whyalla
@MannyD - that's correct, however in other places in my code I need to import function9..functionNConsistent
C
9

Not sure if this is new, but now you can do:

from my_module import (
     function1,
     function2, 
     function3, 
     function4
     )

At least this doesn't go off the page and is easier to read IMO.

Cotter answered 21/12, 2022 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.