Differences between modules (module) and Packages (package) in Python

Source: Internet
Author: User
Tags first string

Most of the content of this article is reproduced to: official website of Liao Xuefeng

1. Modules (module)

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.

The use of modules also avoids 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.

You may also think, what if different people write 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, for example mycompany , in the following directory to store

__init__ . py├─abc.py└─xyz.py

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 abc.py module becomes mycompany.abc , similarly, xyz.py the module name becomes mycompany.xyz .

Please note that each package directory will have a __init__.py file that must exist, otherwise Python will use this directory as a normal directory, not 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 MyCompany.

Similarly, there can be multi-level catalogs, which form a multi-level package structure. For example, the following directory structure:

mycompany├─web│   __init__ . py│  ├─utils.py│  __init__. py├─abc.py└─xyz.py

www.pythe module name of the file ismycompany.web.www

NOTES: When you create a module yourself, you should be careful about naming it and not conflict with the module name that comes with Python. For example, the system comes with the SYS module, its own module is not named sys.py, otherwise it will not be able to import the system's own SYS module.

2. Using the module

Python itself has many very useful modules that can be used immediately as soon as the installation is complete.

Our built-in sys modules, for example, write a hello module:

#!/usr/bin/env Python3#-*-coding:utf-8-*-'a test module'__author__='Michael Liao'ImportSYSdefTest (): args= SYS.ARGV#the argv parameter stores all parameters of the command line with a list    ifLen (args) ==1:#When the list length is 1 o'clock and there is only one argument        Print('Hello, world!.')    elifLen (args) ==2:#When the command line has two parameters        Print('Hello,%s!.'% args[1])    Else:        Print('Too many arguments!')if __name__=='__main__': Test ()

Lines 1th and 2nd are standard comments, and line 1th comments allow the hello.py file to run directly on Unix/linux/mac, and the 2nd line comment indicates that the. py file itself uses standard UTF-8 encoding;

Line 4th is a string representing the document comment of the module, and the first string of any module code is treated as a document comment of the module;

The 6th line uses __author__ variables to write the author in, so that when you open the source code, others will be able to admire your name;

The above is the Python module standard file template, of course, you can also delete all do not write, but, according to the standard is certainly correct.

The real Code section starts at the back.

You may have noticed that the first step in using the sys module is to import the module:

Import sys

After importing the sys module, we have the variable sys pointing to the module, and with the SYS variable, we can access all the functions of the SYS module.

sysThe module has a argv variable that list stores all the parameters of the command line. argvthere is at least one element, because the first parameter is always the name of the. py file, for example:

python3 hello.pythe operation obtained sys.argv is [‘hello.py‘] , note here python3 is not considered as parameters;

python3 hello.py Michaelthe operation obtained sys.argv is [‘hello.py‘, ‘Michael] .

Finally, notice the two lines of code:

if __name__= ='__main__':    test ()

When we run the module file at the command line hello , the Python interpreter places a special variable __name__ __main__ , and if the module is imported elsewhere, the hello if judgment will fail, so this if Testing allows a module to execute some extra code when it runs through the command line, most commonly by running tests.

We can run with the command line to hello.py see the effect:

$ python3 Hello.pyhello, world!$ python hello.py Michaelhello, michael!

If you start the Python interactive environment, then import the hello module:

Import Hello>>>

When importing, there is no print Hello, word! , because no function is executed test() .

hello.test()to print out when it is called Hello, word! :

>>> hello.test () Hello, world!

Differences between modules (module) and Packages (package) in Python

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.