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?
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With