5-4 Modules and Packages

1. Module

The essence of a module is a py file. A module is a file containing python definitions and declarations. The file name is the module name plus the suffix of .py.

2, import statement

The imported module must satisfy two conditions 
1. The module name must satisfy the specification of the variable name
2. The location of the imported module must be in the search path where sys.path is located

Modules can contain executable statements and definitions of functions, the purpose of which is to initialize the module, they are only executed the first time the module name encounters an import statement (import statements can be used anywhere in the program, And the same module is imported many times. In order to prevent you from importing repeatedly, python's optimization method is: after the first import, the module name is loaded into the memory, and subsequent import statements are only for modules that have been loaded in large memory. The object adds a reference and does not re-execute the statement inside the module.

We can find the currently loaded modules from sys.modules. sys.modules is a dictionary that contains the mapping between module names and module objects. The dictionary determines whether to re-import when importing a module.

Each module is an independent namespace. For functions defined in this module, the namespace of this module is regarded as a global namespace, so that when we write our own modules, we don’t have to worry about defining global variables in our modules. When imported, it will conflict with the user's global variables.

  Three things are done when the module my_module is imported for the first time:

  1. Create a new namespace for the source file (my_module module). If the functions and methods defined in my_module use global, this namespace is accessed.

  2. Execute the code contained in the module in the newly created namespace, see initial import import my_module.

  3. Create a name (module) to refer to the namespace.

3. The as keyword aliases the module name .

  1 import my_module as sm
  2 print(sm.money)

Example usage one:

There are two sql modules mysql and oracle, according to the user's input, choose different sql functions.

#mysql.py
def sqlparse():
    print('from mysql sqlparse')
#oracle.py
def sqlparse():
    print('from oracle sqlparse')

#test.py
db_type=input('>>: ')
if db_type == 'mysql':
    import mysql as db
elif db_type == 'oracle':
    import oracle as db

db.sqlparse()

Example usage two: 

The way of aliasing imported modules is useful for writing extensible code. Suppose there are two modules xmlreader.py and csvreader.py, both of which define the function read_data(filename): used to read some data from a file , but in a different input format. Code can be written to selectively pick and choose read modules.

if file_format == 'xml':
     import xmlreader as reader
elif file_format == 'csv':
     import csvreader as reader
data=reader.read_date(filename)

You can also import multiple modules on one line: import sys,os,re

4, from ... import...

The imported name belongs directly to the global, but points to the memory space where the module's name resides.

Compared to import my_module, it will bring the namespace 'my_module' of the source file into the current namespace, which must be the way my_module.name is used.

The from statement is equivalent to import, and it will also create a new namespace, but the name in my_module is directly imported into the current namespace. In the current namespace, the name can be used directly.

So the search order of summary modules is: modules already loaded in memory -> built-in modules -> modules contained in the sys.path path.

4.1 Use modules as scripts:

We can view the module name through the module's global variable __name__:
run as a script:
__name__ is equal to '__main__'

Import as module:
__name__= module name

Role: used to control the .py file to execute different logic in different application scenarios
if __name__ == '__main__':

 5. Package

Packages are a way of organizing the python module namespace by using '.modulename'.

1. Whether it is the import form or the from...import form, if you encounter a dot in the import statement (not when using it), you must be alert at the first time: this is about the import syntax that is only available in packages.

2. The package is at the directory level (folder level), and the folder is used to form the py file (the essence of the package is a directory containing the __init__.py file)

3. When importing a file, the name in the generated namespace comes from the file, and the import package, the name of the generated namespace also comes from the file, that is, __init__.py under the package, the essence of the import package is to import the file

emphasize:

  1. In python3, even if there is no __init__.py file under the package, the import package will still not report an error, while in python2, the file must be under the package, otherwise the import package will report an error

  2. The purpose of creating a package is not to run, but to be imported and used. Remember, a package is just a form of a module, and a package is a module

 Precautions:


1. The import statement related to the package is also divided into import and from...import..., but no matter which one, no matter where it is, you must follow a principle when importing: all the points with dots when importing , the left side of the point must be a packet, otherwise it is illegal. Can have a series of points, such as item.subitem.subsubitem, but must follow this principle.

2. After importing, there is no such restriction in use. The left side of the dot can be packages, modules, functions, and classes (they can all call their own properties in the way of dots).

3. Compare the application scenarios of import item and from item import name:
if we want to use name directly, we must use the latter.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325320077&siteId=291194637