Python Modules

A Python module is a Python file ending with .py, which contains Python object definitions and Python statements.

Modules allow you to logically organize your Python code sections.

Assigning related code to a module makes your code more usable and easier to understand.

Modules can define functions, classes, and variables, and can also contain executable code.

Example

The following is a simple module support.py:

support.py module:

def print_func( par ): print "Hello : ", par return

import statement

Importing modules

Once a module is defined, we can use the import statement to import the module. The syntax is as follows:

import module1[, module2[,... moduleN]]

For example, to reference the math module, you can use the following at the very beginning of the file:import mathto import it. When calling functions in the math module, you must reference it like this:

Module name.function name

When the interpreter encounters an import statement, the module will be imported if it is in the current search path.

The search path is a list of all directories that the interpreter will search in order. If you want to import the module support.py, you need to put the command at the top of the script:

test.py file code:

#!/usr/bin/python # -*- coding: UTF-8 -*- # import module import support # Now you can call the functions included in the module support.print_func("Example")

The output of the above example is:

Hello : Example

A module is imported only once, no matter how many times you execute import. This prevents the imported module from being executed over and over again.



from…import statement

Python's from statement lets you import a specific part from a module into the current namespace. The syntax is as follows:

from modname import name1[, name2[, ... nameN]]

For example, to import the fibonacci function from the fib module, use the following statement:

from fib import fibonacci

This statement does not import the entire fib module into the current namespace; it only imports the fibonacci function from fib into the global symbol table of the module executing this statement.



from…import * statement

It is also possible to import all the contents of a module into the current namespace. Simply use the following declaration:

from modname import *

This provides a simple way to import all items from a module. However, this declaration should not be overused.

For example, if we want to import everything from the math module at once, the statement is as follows:

from math import *

Search path

When you import a module, the Python interpreter searches for the module's location in the following order:

  • 1. Current directory
  • 2. If it is not in the current directory, Python searches each directory listed in the shell variable PYTHONPATH.
  • 3. If it cannot be found anywhere, Python checks the default path. Under UNIX, the default path is generally /usr/local/lib/python/.

The module search path is stored in the sys.path variable of the system module. This variable contains the current directory, PYTHONPATH, and the default directories determined by the installation process.



PYTHONPATH variable

As an environment variable, PYTHONPATH consists of many directories contained in a list. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

On Windows systems, a typical PYTHONPATH is as follows:

set PYTHONPATH=c:\python27\lib;

On UNIX systems, a typical PYTHONPATH is as follows:

set PYTHONPATH=/usr/local/lib/python


Namespaces and scope

A variable is a name (identifier) that owns a matching object. A namespace is a dictionary containing variable names (keys) and their corresponding objects (values).

A Python expression can access variables in both the local namespace and the global namespace. If a local variable and a global variable have the same name, the local variable overrides the global variable.

Each function has its own namespace. The scope rules for class methods are the same as for regular functions.

Python intelligently guesses whether a variable is local or global; it assumes that any variable assigned a value within a function is local.

Therefore, if you want to assign a value to a global variable within a function, you must use the global statement.

The expression global VarName tells Python that VarName is a global variable, so Python will not search for this variable in the local namespace.

For example, we define a variable Money in the global namespace. Then we assign a value to Money inside a function, and Python assumes that Money is a local variable. However, since we did not declare a local variable Money before accessing it, an UnboundLocalError will occur. Removing the comment symbol before the global statement can solve this problem.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
Money = 2000
def AddMoney():
   # 想改正代码就取消以下注释:
   # global Money
   Money = Money + 1
 
print Money
AddMoney()
print Money


dir() function

The dir() function returns a sorted list of strings containing the names defined in a module.

The returned list contains all modules, variables, and functions defined in a module. Here is a simple example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 导入内置math模块
import math
 
content = dir(math)
 
print content;

The output of the above example is:

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ points to the module's name, and __file__ points to the import file name of the module.



globals() and locals() functions

Depending on where they are called, the globals() and locals() functions can be used to return names in the global and local namespaces.

If locals() is called inside a function, it returns all the names that can be accessed in that function.

If globals() is called inside a function, it returns all the global names that can be accessed in that function.

The return type of both functions is a dictionary. Therefore, the names can be extracted using the keys() function.



reload() function

When a module is imported into a script, the code in the top-level part of the module is executed only once.

Therefore, if you want to re-execute the top-level code in a module, you can use the reload() function. This function will re-import a previously imported module. The syntax is as follows:

reload(module_name)

Here, module_name should be the module's name directly, not a string. For example, to reload the hello module:

reload(hello)


Packages in Python

A package is a hierarchical file directory structure that defines a Python application environment composed of modules, subpackages, and subpackages within subpackages, and so on.

Simply put, a package is a folder, but the folder must contain an __init__.py file, and the content of that file can be empty.__init__.pyIt is used to identify that the current folder is a package.

Consider apackage_exampleunder the directoryexample1.py、example2.py、__init__.py file, test.py is the code for testing the package call, the directory structure is as follows:

test.py
package_example
|-- __init__.py
|-- example1.py
|-- example2.py
The source code is as follows:

package_example/example1.py

#!/usr/bin/python # -*- coding: UTF-8 -*- def example1(): print "I'm in example1"

package_example/example2.py

#!/usr/bin/python # -*- coding: UTF-8 -*- def example2(): print "I'm in example2"

Now, inpackage_examplecreate under the directory__init__.py:

package_example/__init__.py

#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': print 'run as the main program' else: print 'package_example initialization'

Then wepackage_example in the same-level directorycreate test.py below to callpackage_examplePackage

test.py

#!/usr/bin/python # -*- coding: UTF-8 -*- # import Phone package from package_example.example1 import example1 from package_example.example2 import example2 example1() example2()

The output of the above example is:

package_example 初始化
I'm in example1
I'm in example2

As above, for illustration, we placed only one function in each file, but in fact you can place many functions. You can also define Python classes in these files and then create a package for these classes.

Other extensions