Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "import X" and "from X import *"? [duplicate]

Tags:

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?

like image 456
temporary_user_name Avatar asked Sep 04 '12 20:09

temporary_user_name


People also ask

What is the difference between import X and from X import *?

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.

What does from X import * mean in Python?

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.

What is import * in Python?

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.

What is the difference between from math import * and import math?

The only difference is convenience and nothing else. Import aliases/unrolling is just namespace thing. There's no difference in performance or footprint.


1 Answers

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.

like image 164
BrenBarn Avatar answered Oct 14 '22 08:10

BrenBarn