The concept of Python modules and packages

Source: Internet
Author: User

Modules & Packages (* * * * * *) module (modue) Concept:

In the development of computer programs, as the program code more and more, in a file code will be more and more long, more and more difficult to maintain.

In order to write maintainable code, we grouped many functions into separate files so that each file contained relatively few code, and many programming languages used this way of organizing code. In Python, a. py file is called a module.

What are the benefits of using modules?

The greatest benefit is that the maintainability of the code is greatly improved.

Second, writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python built-in modules and modules from third parties.

Therefore, there are three types of modules:

    • Python Standard library
    • Third-party modules
    • Application Custom Modules

In addition, the use of modules can also avoid conflicting function names and variable names. Functions and variables of the same name can exist in different modules individually, so we do not have to think about names that conflict with other modules when we write our own modules. But also be aware that try not to conflict with the built-in function name.

Module Import method

1 Import Statement

1 importmodule1[, module2[,... moduleN]

When we use the import statement, how does the Python interpreter find the corresponding file? The answer is that the interpreter has its own search path, which exists in the Sys.path.

12 [‘‘, ‘/usr/lib/python3.4‘, ‘/usr/lib/python3.4/plat-x86_64-linux-gnu‘,‘/usr/lib/python3.4/lib-dynload‘‘/usr/local/lib/python3.4/dist-packages‘‘/usr/lib/python3/dist-packages‘]  

So if, like me, there are files in the current directory with the same name as the module to be introduced, the module to be introduced will be screened out.

2 From...import Statements

1 frommodname importname1[, name2[, ... nameN]]

This declaration does not import the entire ModuleName module into the current namespace, but only introduces the name1 or name2 individual inside it into the global symbol table of the module that executes the declaration.

3 from...import* Statements

1 frommodname import*

This provides an easy way to import all the items in a module. However, such statements should not be used too much. In most cases, Python programmers do not use this approach, because the naming of other sources introduced may well overwrite existing definitions.

4 Operational nature

12 #1 import test#2 from test import add  

Whether 1 or 2, first find test.py through Sys.path, then execute the test script (all execution), the difference is that 1 will load the variable name of test into the namespace, and 2 will only load the add variable name in.

Packages (Package)

What if a different person writes the same module name? To avoid module name collisions, Python introduces a way to organize modules by directory, called packages.

For example, a abc.py file is a named abc module, and a xyz.py file is a named xyz module.

Now, assuming that our abc and xyz these two module names conflict with the other modules, we can organize the modules through the package to avoid conflicts. Method is to select a top-level package name:

Once the package is introduced, all modules will not conflict with others as long as the package name in the top layer does not conflict with others. Now, the name of the view.py module becomes HELLO_DJANGO.APP01 .views , similarly, the Manage .py module name is Hello_django.manage.

Please note that each package directory will have a __init__.py file that must exist, otherwise Python will treat the directory as a normal directory (folder) instead of a package. __init__.pyit can be an empty file, or it can have Python code, because __init__.py it is a module, and its module name is the name of the corresponding package.

The calling package is the __init__.py file under the Execute Package

Note Point (important)

1--------------

In the Nod1 import Hello is not found, there are students said can find Ah, that is because your pycharm for you to add MyApp this layer of path into the sys.path inside, so you can find, however, once the program runs at the command line, the error. A classmate asked what to do? Simple Ah, you add this path to not just OK:

12345 importsys,osBASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(BASE_DIR)importhellohello.hello1()

2--------------

12 if__name__==‘__main__‘:    print(‘ok‘)

"Make a. py both importable and executable"

If we are directly executing a. py file, the file then "__name__ = = ' __main__ '" is true, but if we import the file through import from another. py file, then __name__ The value is the name of our py file, not the __main__.

This feature also has a use: When debugging code, in "if __name__ = = ' __main__ '" to add some of our debugging code, we can let the external module calls do not execute our debugging code, but if we want to troubleshoot the problem, directly execute the module file, Debug your code to work! S

3

123456789101112131415 ##-------------cal.pydefadd(x,y):    returnx+y##-------------main.pyimport cal      #from module import caldefmain():    cal.add(1,2)    ##--------------bin.pyfrommodule import mainmain.main()
Note

The concept of Python modules and packages

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.