Python issues with difference between import module and module import

I am having a problem with the difference between import moduleand from module import name1, name2 ...in Python. I am new (last week) to Python using Python 3.6 on Windows-64.

The Python Tutorial briefly discusses these two approaches import. It is argued that it is from module import *not recommended because of the danger of contamination of the current namespace. However, there is no indication that between import moduleand from module import name1, name2..there is any significant difference in the work with implication, that this is a matter of preference or convenience.

However, in practice there is a big difference. Consider this module called ModuleA, which defines a global variable and function:

# ModuleA
iGlobalA = 0

def fA():
    iGlobalA += 1
    print( "MA: iGlobalA=", iGlobalA )

print( "Module A Initialised, iGlobalA=", iGlobalA )

import ModuleA ModuleA. , :

import ModuleA as MA

def fX():
    print( "MX: Before, ModuleA.iGlobalA=", MA.iGlobalA )
    MA.fA()
    print( "MX: After 1, ModuleA.iGlobalA=", MA.iGlobalA )
    MA.fA()
    print( "MX: After 2, ModuleA.iGlobalA=", MA.iGlobalA )

fX()

:

MA: Initialised, iGlobalA= 100
MX: Before, ModuleA.iGlobalA= 100
MA: iGlobalA incremented to 101
MX: After 1, ModuleA.iGlobalA= 101
MA: iGlobalA incremented to 102
MX: After 2, ModuleA.iGlobalA= 102

. ModuleY, from ModuleA import fA, iGlobalA, ModuleA :

# ModuleY
from ModuleA import fA, iGlobalA   

def fY():
    print( "MY: Before, ModuleA.iGlobalA=", iGlobalA )
    fA()
    print( "MY: After 1, ModuleA.iGlobalA=", iGlobalA )
    fA()
    print( "MY: After 2, ModuleA.iGlobalA=", iGlobalA )

fY()

:

MA: Initialised, iGlobalA= 100
MY: Before, ModuleA.iGlobalA= 100
MA: iGlobalA incremented to 101
MY: After 1, ModuleA.iGlobalA= 100
MA: iGlobalA incremented to 102
MY: After 2, ModuleA.iGlobalA= 100

iGlobalA ModuleA ModuleA ModuleA.iGlobalA. , fA ModuleA, , - - ModuleA, fA() , , .

, . , -, , , .

- @abdullah-ahmed-ghaznavi .

  • - ?
  • ?
  • , ?
+4
1

iGlobalA ModuleA

. from ModuleA import iGlobalA ModuleA.iGlobalA ModuleY.iGlobalA - , id(iGlobalA) . , () , - ( ModuleA, ModuleY), , fA() iGlobalA - ModuleA.iGlobalA - , ModuleA ( ).

, ModuleY ModuleA.iGlobalA, , , ( ModuleA) fA(), ModuleY, .

, , , (.. , dict ..), :

# ModuleA
iGlobalA = []

def fA():
    iGlobalA.append(1)
    print( "MA: iGlobalA=", iGlobalA )

print( "Module A Initialised, iGlobalA=", iGlobalA )

Python- , Python ( "" " " ).

, .

, . , , cf https://docs.python.org/3/reference/simple_stmts.html#import https://docs.python.org/3/reference/import.html, , " " " , ".

, -, , , .

, lib ( , ) ( ), , , ( ) API lib.

- ?

, , , , , .

? , ?

. , .

+1

Source: https://habr.com/ru/post/1695346/


All Articles