Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 682
Jim Jeffries Avatar asked Jul 20 '11 12:07

Jim Jeffries


People also ask

How do I import multiple functions from a Python module?

Import multiple modulesYou can write multiple modules separated by commas after the import statement, but this is not recommended in PEP8. Imports should usually be on separate lines. If you use from to import functions, variables, classes, etc., as explained next, you can separate them with a comma.

How do you import all functions in Python?

We can use import * if we want to import everything from a file in our code. We have a file named functions.py that contains two functions square() and cube() . We can write from functions import * to import both functions in our code. We can then use both square() and cube() functions in our code.

Can you import functions in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

How do I import a function from a module?

To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.


2 Answers

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 
like image 97
Kugel Avatar answered Nov 02 '22 10:11

Kugel


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 
like image 26
agf Avatar answered Nov 02 '22 09:11

agf