What is "good practice" for importing modules? For example, if I had a module named 'module' and a function named 'func' which would be preferable?
1:
def do_things():
from module import func
func()
2:
from module import func
def do_things():
func()
3:
import module as mod
def do_things():
mod.func()
4:
def do_things():
import module as mod
mod.func()
I need to make sure my code is written well for this project. Also with importing classes from modules (such as "from bs4 import BeautifulSoup") is it fine to import them into the global namespace at the top of my program? If not, do the same rules as here apply?
From a performance point of view, import
and import from
are exactly the same . The interpreter will load the whole module into memory.
That leaves you with a choice: which way to do it. I'd go with the one that makes the code more readable and less ambiguous:
UPDATE: About local imports, please see this answer. Python will work with local or top-of-file imports. Local import can save you from circular dependency. A better design can also help you with that.
You must chose your own poison, it's all about trade-offs.
For me I prefer #3, my reasoning is:
from module import func
you can use any function in that module without explicitly importing it.from module import func1, func2, fun3
you can just do import module as mod
then mod.func1()
. For importing a single class, if that's the only thing you will do with that module I would find that ok, but my point 1 can apply here, if that module also has helper functions and/or other classes, it might be better to import the module then do module.Class()
.
When looking for best practices PEP8 is usually the first place to look. According to PEP8 it's #2: https://www.python.org/dev/peps/pep-0008/#imports
I also like #3, but only in certain cases:
import numpy as np
)import a_ridiculously_long_module_name as short_name
or import module.submodule.subsubmodule as short_name
)The danger of using aliases with unknown packages is that the abbreviation might make sense to you, but not to someone else. This could hinder code readability.
You can also combine aliases and absolute imports. So option 5 would be:
from module import function as func
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.