Python learning day 4 - module import

1. Namespace

The name of the module plus the name of the file is the namespace.
How does python distinguish between an ordinary folder and a package?
There is a specific file under a folder__ init__.py. At this time, this folder is a package. (two underscores before and after). Among them, the file itself is also a module. The name of this module is the name of its immediate folder.
 

2. Introduction of modules:

First:

 
 
We cannot directly import the variables under the module.
Modify the name of the imported module:
import t.c7 as m 
print(m.a)

Second:

from t.c7 import a 
print(a) //perhaps # from t import c7 #print(c7.a)
Introduce all variables:
from t.c7 import * 
print(a) 
print(c) 
print(d)
The variables in t.c7 are defined as:
a = 2
c = 3
d = 4
In t.c7, you can specify to export variables or functions through the * sign, and export variables A and C with the following values:
  t.c7.py:
__all__ = ['a', 'c']   
  
a = 2     
c = 3     
d = 4
At this point, execute C8 Py file:
from t.c7 import *

print(a)
print(c)
print(d) 
//2
//3
//Traceback (most recent call last):
//  File ".\c8.py", line 9, in <module>
//    print(d)
//NameError: name 'd' is not defined
Among them__ all__ Built in variables called modules.

Third:

from c9 import a,b,c

'''
    from c9 import a
    from c9 import b
    from c9 import c
'''
python suggests that the number of characters in a line should not exceed 80
At this time, it involves line feed without changing the original meaning of the code:
from c9 import a,b,\
c  
The above example is not recommended and appears very abrupt, so it is recommended to use parentheses:
from c9 import (a,b,
c)
 

3.__ init__. Function of Py file:

 

Single import:

 
When importing a package, the file will be executed automatically.
c11 file:
import t
At this point, execute C11 py:
#This is __init__.py file t Medium__init__.py Automatic file execution.
Of course, only the c7 file in t is referenced__ init__.py can still be executed.
In__ init__. Write in py file:
__all__ = ['c7']
Add c8.0 in the t folder Py file, C8 Write in py file:
e = 2 
f = 3  
g = 4
Write in c11 file and run c11
from t import * 
print(c7.a) 
#2 
print(c8.e) 
#error:  NameError: name 'c8' is not defined
 

Batch import:

About project Catalog:
Under t folder__ init__. Batch import module in py:
import sys
import datetime 
import io
Reference under c13 file:
import t
print(t.sys.path)
#['F:\\pythonlearn\\my-pythonFirst\\six', 'E:\\py3\\python38.zip', 'E:\\py3\\DLLs', 'E:\\py3\\lib', 'E:\\py3', 'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python38\\site-packages', 'E:\\py3\\lib\\site-packages']

Packages and modules:

    1. Packages and modules will not be imported repeatedly:
    2. Avoid circular import
 
What is circular import?
For example, create a new p folder. Under the P folder, there are p1 and p2 files:
In p1:
from p2 import p2 
p1 = 2 
print(p2)
In p2:
from p1 import p1 
p2 = 2
An error will be reported when p1 is executed.
Traceback (most recent call last):
  File ".\p1.py", line 1, in <module>
    from p2 import p2
  File "F:\pythonlearn\my-pythonFirst\six\p\p2.py", line 1, in <module>
    from p1 import p1
  File "F:\pythonlearn\my-pythonFirst\six\p\p1.py", line 1, in <module>
    from p2 import p2
ImportError: cannot import name 'p2' from partially initialized module 'p2' (most likely due to a circular import) (F:\pythonlearn\my-pythonFirst\six\p\p2.py)
 
While importing, the code of the imported module will be executed.
 

Built in variables of the module:

a = 2
c = 3

infos = dir();
print(infos)
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'c']
Print the specific information in the built-in variable: look at the structure first
  1. In C9 Py:
'''

    This is a c9 doc

'''


print("name:"+__name__)
print("package:"+__package__)
print("doc:"+__doc__)
print("file:"+__file__)
  2. Introduce in c15:
import t.t1.c9
Print results at this time:
name:t.t1.c9
package:t.t1
doc:

    This is a c9 doc

 

If c9 there is no wrong side in the report:
TypeError: can only concatenate str (not "NoneType") to str
 

The difference between the entry file and the built-in variables of the ordinary module:

 
Modify C15 py
import t.t1.c9

print("name:"+__name__)
print("package:"+__package__)
print("doc:"+__doc__)
print("file:"+__file__)
Print results:
name:t.t1.c9
package:t.t1
doc:

    This is a c9 doc


file:F:\pythonlearn\my-pythonFirst\six\t\t1\c9.py
name:__main__
Traceback (most recent call last):
  File ".\c15.py", line 9, in <module>
    print("package:"+__package__)
TypeError: can only concatenate str (not "NoneType") to str
Continue to modify:
'''
describe
'''
import t.t1.c9

print('~~~~~~~~~~~~~~~~~~~~c15~~~~~~~~~~~~~~~~~~~~~~~~~')
print("name:" + __name__)
print("package:" + (__package__ or 'The current module does not belong to any package'))
print("doc:" + __doc__)
print("file:" + __file__)
Print results:
name:t.t1.c9
package:t.t1
doc:

    This is a c9 doc


file:F:\pythonlearn\my-pythonFirst\six\t\t1\c9.py
~~~~~~~~~~~~~~~~~~~~c15~~~~~~~~~~~~~~~~~~~~~~~~~
name:__main__
package:The current module does not belong to any package
doc:
describe

file:.\c15.py

 

Conclusion: because it is running C15 Py file, so it is an entry file, so it does not belong to any package. c9 is introduced from T1 under t, so c9 belongs to t.t1 package.
In addition, the file result is related to the root runtime environment:
 
Supplement to dir() function:
 
When the function has no parameters, it returns the list of variables, methods and defined types in the current range; With parameters, the list of properties and methods of the parameters is returned. If the parameter contains a method__ dir__ (), the method will be called. If the parameter does not contain__ dir__ (), this method will collect parameter information to the greatest extent.
 
Interpretation of a sentence of code:
if __name__ == "__main__":    
     pass
Make a script both importable and executable can be used to summarize:
Let your script not only provide a script for other programs to call, but also act as an executable file.
 
When a module is in two different situations, the logic of the code is different in these two situations. This program is needed at this time.
For example, in C17 Write in py:
if __name__ == "__main__":
    print('This is app')

print('This is a module')
At this time, if you execute the file directly, you can get:
  
  This is app
  This is a module
If called:
This is a module
This is because, as an entry file, its built-in variables__ name__ The value of is__ main__
We can also call the file as a module through the command:
python -m six.c17
At this time, c17 is the py file under the six folder, and the command line is carried out under the same level directory of the six (to be called a module, it must be a file under a package, otherwise an error will be reported):
PS F:\pythonlearn\my-pythonFirst> python -m six.c17 
This is app
This is a module
For the above codes, please note:
① if not under six__ init__.py, c17 this file cannot be found
② if it is executed under the six Directory:
PS F:\pythonlearn\my-pythonFirst\six> python -m c17
This is app
This is a module

//-m If it is a file, an error will be reported
PS F:\pythonlearn\my-pythonFirst\six> python -m .\c17.py
E:\py3\python.exe: Relative module names not supported
Execute the command for c15 in the root directory: (python -m six.c15)
'''
describe
'''
import t.t1.c9

print('~~~~~~~~~~~~~~~~~~~~c15~~~~~~~~~~~~~~~~~~~~~~~~~')
print("name:" + __name__)
print("package:" + (__package__ or 'The current module does not belong to any package'))
print("doc:" + __doc__)
print("file:" + __file__)
An error will be reported. The error content is that the file t cannot be found. In this case, it is necessary to add six before the file t
'''
describe
'''
import six.t.t1.c9

print('~~~~~~~~~~~~~~~~~~~~c15~~~~~~~~~~~~~~~~~~~~~~~~~')
print("name:" + __name__)
print("package:" + (__package__ or 'The current module does not belong to any package'))
print("doc:" + __doc__)
print("file:" + __file__)
The printed name and package are:
name:six.t.t1.c9 
package:six.t.t1
Relative Import and absolute import are involved here. At this point, - m is followed by the namespace.
 

Relative Import and absolute import:

 

Absolute import:

  1. The location of the entry file determines__ package__.
m2 file:
print(__package__);
Execute main py
Module2.Module4
Set main Py to Module2, and modify the import in main to module4 M2, execute main py
Module4
The description entry file determines this namespace.
Absolute path: start from the top package and look down.

Relative path:

One point represents the current directory, two points represent the upper level directory, three points represent the upper level directory, and N points represent the upper n-1 level directory
However, import cannot use relative paths, but can use from. The main reference cannot use a relative path because, as an entry file, after being executed by python, its name refers to__ main__. And__ main__ It does not exist, so the relative path cannot be used in the entry file. However, you can use - m to make the entry file as a module.
 
Files in the package cannot use relative paths to reference top-level files. As shown below:
The reason is that the top-level package of m5 is Module2, Mian Py is an entry file, which is not available in the same level directory__ main__ This bag is.
 

Tags: Python

Posted by lizlazloz on Wed, 04 May 2022 23:08:16 +0300