1

As far as I understand, in Python there are 3 ways to import:

  1. from name_module import name_class
  2. import name_module
  3. from name_module import *

In all other ways, there is no point, as if this class is already in our module. But for some reason they do not recommend using the third way, explaining this by the fact that there is a possibility of a name conflict between the names of the imported module's class and the module in which we are located.

  1. Why does this not happen when we import the 2nd way. After all, there and there is the import of the entire file and the creation of the same variables in our namespace or not?
  2. What is better to use in what case?
khelwood
  • 55,782
  • 14
  • 81
  • 108
helsereet
  • 111
  • 1
  • 5

2 Answers2

1
  1. No. Python is not C or C++ where the compiler essentially copy-pastes included files to the top of the including code. import 'name_module' loads/adds a reference to name_module to the accessible namespace, and classes/methods/variables defined in it are accessed by name_module.name.

  2. Choose what works best for you except for the "star import". Never choose the "star import". Why is "import *" bad?

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0
  1. Becuase you have to use the module name to call the module functions when using this import method.

  2. Depends on what you mean with "best". import X is the safest. If you think that import aterriblyandunnecessarilylongpackagename makes your code inconvinient, use import aterriblyandunnecessarilylongpackagename as x. As soon as you use from there's a risk, and especially if you use *

Consider the following code. Assume that functions A,B and C exists in both X and Y.

from X import *
from Y import A
B
A

This code will always work as intended, but now assume that both X and Y has functions A, B and C, but X also has the function D:

from X import *
from Y import *
D
A

Now D will be called from X and A from Y. But what if a software upgrade adds a function called D to the package Y? Then the code will execute differently.

Never use from X import *

klutt
  • 30,332
  • 17
  • 55
  • 95