In Python, I'm not really clear on the difference between the following two lines of code:
import X
or
from X import *
Don't they both just import everything from the module X? What's the difference?
The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.
from X import * Creates a label for every member attribute of the X module, directly in the local namespace. Both operations add X to sys. modules , true, but the effect on the local namespace is the difference.
In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.
The only difference is convenience and nothing else. Import aliases/unrolling is just namespace thing. There's no difference in performance or footprint.
After import x
, you can refer to things in x
like x.something
. After from x import *
, you can refer to things in x
directly just as something
. Because the second form imports the names directly into the local namespace, it creates the potential for conflicts if you import things from many modules. Therefore, the from x import *
is discouraged.
You can also do from x import something
, which imports just the something
into the local namespace, not everything in x
. This is better because if you list the names you import, you know exactly what you are importing and it's easier to avoid name conflicts.
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