Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python module

Python module

A Python module (Module) is a Python file ending in .py that contains Python object definitions and Python statements.

Modules allow you to logically organize your Python code segments.

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

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

Example

The following is a simple module, support.py:

The 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 it. The syntax is as follows:


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

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

模块名.函数名

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

The search path is a list of all directories that an interpreter searches first. To import the module support.py, you need to put the command at the top of the script:

Code in the test.py file:

#!/usr/bin/python

-- coding: UTF-8 --

Import the module

import

support

Now the functions contained in the module can be called

support

.

print_func

(

"

Runoob

"

)

The example above produces the following output:


Hello : Runoob

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.


The 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 declaration does not import the entire fib module into the current namespace; it only imports the single fibonacci function from fib into the global symbol table of the module executing the declaration.


The from...import* statement

It is also possible to import all the contents of a module into the current namespace, simply by using the following declaration:


from modname import *

This provides a simple way to import all items from a module. However, this kind of 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 order in which the Python interpreter searches for its location is:

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


The PYTHONPATH variable

As an environment variable, PYTHONPATH consists of many directories stored 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 Scopes

Variables are names (identifiers) that have matching objects. A namespace is a dictionary containing variable names (keys) and their corresponding objects (values).

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

Every function has its own namespace. The scope rules for class methods are the same as those for ordinary functions.

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

Therefore, to assign a value to a global variable inside a function, you must use the global statement.

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

For example, we define a variable Money in the global namespace. If we then assign a value to Money inside a function, Python assumes Money is a local variable. However, we have not declared a local variable Money before accessing it, so an UnboundLocalError will occur. Uncommenting the global statement will solve this problem.


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
Money = 2000
def AddMoney():
   # Uncomment the following to modify the code:
   # global Money
   Money = Money + 1
 
print Money
AddMoney()
print Money

The dir() function

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

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


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# Import built-in math module
import math
 
content = dir(math)
 
print content;

The example above produces the following output:


['__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__ refers to the name of the module, and __file__ refers to the filename from which the module was imported.


The 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 accessible within that function.

If globals() is called inside a function, it returns all the global names accessible within that function.

Both functions return a dictionary. Therefore, the names can be extracted with the keys() function.


The reload() function

When a module is imported into a script, the code at the top level 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 re-imports a previously imported module. The syntax is as follows:


reload(module_name)

Here, module_name should be the name of the module directly, not in the form of 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, subpackages under subpackages, and so on.

Simply put, a package is a folder, but the folder must contain a init.py file, whose contents may be empty.init.py It is used to mark the current folder as a package.

Consider a package in the package_runoob directory with files **runoob1.py, runoob2.py,init.py ** files; test.py is the code that tests calling the package. The directory structure is as follows:


test.py
package_runoob
|-- __init__.py
|-- runoob1.py
|-- runoob2.py

The source code is as follows:

package_runoob/runoob1.py

#!/usr/bin/python

-- coding: UTF-8 --

def

runoob1

(

)

:

print

"

I'm in runoob1

"

package_runoob/runoob2.py

#!/usr/bin/python

-- coding: UTF-8 --

def

runoob2

(

)

:

print

"

I'm in runoob2

"

Now, in the package_runoob directory, creating init.py:

package_runoob/init.py

#!/usr/bin/python

-- coding: UTF-8 --

if

name

==

'

main

'

:

print

'

run as the main program

'

else

:

print

'

package_runoob initialization

'

Then we package_runoob create test.py in the same directory to call package_runoob package

test.py

#!/usr/bin/python

-- coding: UTF-8 --

import the Phone package

from

package_runoob

.

runoob1

import

runoob1

from

package_runoob

.

runoob2

import

runoob2

runoob1

(

)

runoob2

(

)

The example above produces the following output:


package_runoob 初始化
I'm in runoob1
I'm in runoob2

As above, for the sake of example, we have 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.