Python module import implements the functionality you need

Source: Internet
Author: User
Modules allow you to logically organize your Python code snippets.

Assigning the relevant code to a module will make your code better and easier to understand.

The module is also a Python object, with a random name attribute used to bind or reference.

Simply put, the module is a file that holds the Python code. Modules can define functions, classes, and variables. The module can also contain executable code.

Example

A python code in a module called Aname can usually be found in a file called aname.py. The following example is a simple module support.py.

def print_func (PAR):

Print "Hello:", par

Import statement

To use a Python source file, simply execute the import statement in another source file with the following syntax:

Import module1[, module2[,... Modulen]

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

A search path is a list of all directories that an interpreter will search first. To import the module hello.py, you need to place the command at the top of the script:

#!/usr/bin/python

# import Module

Import support

# Now you can invoke the functions contained in the module.

Support.print_func ("Zara")

The result of the above example output:

Hello:zara.

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

From...import statements

The FROM statement of Python lets you import a specified section from the module into the current namespace. The syntax is as follows:

>>>from modname Import name1[, name2[, ... Namen]

For example, to import the Fibonacci function of a module FIB, use the following statement:

>>>from fib Import Fibonacci

This declaration does not import the entire FIB module into the current namespace, it only introduces the Fibonacci individual in the FIB to the global symbol table of the module that executes the declaration.

From...import * Statement

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

>>>from Mod_name Import *

This provides an easy way to import all the items in a module. However, such statements should not be used too much.

Positioning module

When you import a module, the Python parser's search order for the module location is:

    • Current directory

    • If it is not in the current directory, Python searches for each directory under the shell variable Pythonpath

    • If none are found, Python looks at the default path. Under UNIX, the default path is typically/usr/local/lib/python/

The module search path is stored in the Sys.path variable of the system module. The variable contains the current directory, Pythonpath, and the default directory determined by the installation process.

Pythonpath variable

As an environment variable, Pythonpath consists of many directories that are installed in a single list. The syntax of the Pythonpath is the same as the shell variable path.

In Windows systems, the typical pythonpath are as follows:

Set Pythonpath=c:\python20\lib;

In Unix systems, the typical pythonpath are as follows:

Set Pythonpath=/usr/local/lib/python

Namespaces and Scopes

A variable is a name (identifier) that has a matching object. A namespace is a dictionary that contains the variable names (keys) and their respective objects (values).

A Python expression can access variables in the local namespace and in 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 of a method of a class are the same as the usual functions.

Python intelligently guesses whether a variable is local or global, and assumes that any variable that is assigned within the function is local.

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

The expression for global varname tells Python that VarName is a global variable so that Python does not look for the variable in the local namespace.

For example, we define a variable money in the global namespace. We then assign a value to the variable money within the function, and then Python assumes that money is a local variable. However, we did not declare a local variable money before the visit, and the result is a unboundlocalerror error. Canceling the comment on the global statement will solve this problem.

>>>#!/usr/bin/python

>>>money = 2000

>>>def Addmoney ():

# to correct the code, uncomment the following:

# Global Money

Money = money + 1

>>>print Money

>>>addmoney ()

>>>print Money

Dir () function

The Dir () function is a well-ordered list of strings, and the content is a name 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

>>># importing the built-in math module

>>>import Math

>>>content = Dir (math)

>>>print content;

The result of the above example 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 points to the name of the module, 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 the function, all the names that can be accessed in the function are returned.

If Globals () is called inside the function, all the global names that can be accessed in the function are returned.

The return type of two functions is a dictionary. So names can be extracted with the keys () function.

Reload () function

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

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

>>>reload (module_name)

Here, module_name to directly put the module's name, not a string form. For example, to reload the Hello module, as follows:

>>>reload (Hello)

Packages in Python

A package is a hierarchical file directory structure that defines a Python application environment consisting of a module and a sub-package, and a sub-package under a sub-package.

Consider a pots.py file in the phone directory. This file has the following source code:

>>>#!/usr/bin/python

>>>def Pots ():

Print "I ' m Pots Phone"

In the same way, we have two other files that hold different functions:

    • phone/isdn.py contains function Isdn ()

    • phone/g3.py contains function G3 ()

Now, create the file init.py in the phone directory:

    • phone/init.py

When you import the phone, in order to be able to use all the functions, you need to use explicit import statements in init.py, as follows:

>>>from Pots Import Pots

>>>from ISDN Import ISDN

>>>from G3 Import G3

When you add the code to init.py, the classes are all available when you import the phone package.

>>>#!/usr/bin/python

>>># now import your Phone package.

>>>import Phone

>>>phone.pots ()

>>>PHONE.ISDN ()

>>>PHONE.G3 ()

The result of the above example output:

I ' m Pots Phone

I ' m 3G Phone

I ' m ISDN Phone

As above, for example, we only put a function in each file, but in fact you can put a lot of functions. You can also define Python classes in these files, and then build a package for those classes.

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.