I am very new to python, I have a simple question.
For example
If I do
import A
then I can use A.b()
.
I am wondering, how to omit A
in A.b()
?
If you want to use b
from module A
:
from A import b
If you want to rename it:
from A import b as my_b
If you need several objects:
from A import b, c, d
If you need everything:
from A import *
About the import *
option, please do read this post.
It's rather short, but tl;dr: do not import everything from a module by from A import *
.
If you really need everything from the module, or a very big part of its content, prefer the normal import, possibly with renaming:
import numpy as np
import tkinter as tk
This question has already been answered, but one thing to note when using imports is that
from module import foo
and
import module
Are absolutely the same, as far as memory and performance is concerned. In either case, the module
is compiled and loaded into sys.modules
. The only difference is what is brought into your namespace. In the first case, it is foo
. In the second case, it is module
.
Since the other answers do not explain why using from module import *
is bad, this is the reason: *
will import everything into your namespace for direct use. This is not a good idea unless you know what you are doing. Name clashes are definitely possible, especially when importing multiple large modules.
This may be a matter of opinion, but I believe import module
followed by module.foo()
is safer and gives the reader a better idea about that method/attribute, where it came from, and what it is doing. Readability matters!