Python Basics (12)--modules

Source: Internet
Author: User

This article address: http://www.cnblogs.com/archimedes/p/python-modules.html, reprint please indicate source address.

Module Introduction

If you exit the Python interpreter again, all definitions (variables and functions) you created previously are lost. Therefore, if you want to write a long-lasting program, it is best to use a text editor to write the program, the saved file input interpreter. We call it creating a script . The program gets longer, and you can separate it into several files for ease of maintenance. You may also want to use a common function in several programs, but you do not want to copy its definition into each program.

To meet these needs, Python provides a way to get the definition from a file and use it in an interactive instance of the script or interpreter. Such a file is called a module ; the definition in the module can be imported into another module or in the main module (the set of variables that can be called when the script executes is at the highest level and in calculator mode)

A module is a file that includes Python definitions and declarations. The file name is the module name plus the . py suffix. The module name of the module (as a string) can be obtained by a global variable __name__ . For example, you can use your favorite file editor to create a file called fibo.py in the current directory, with the following entries:

 #   Fibonacci numbers module  def  fib (n): #   write Fibonacci series up to n  A, b = 0, 1 while  b < N: print   b, A, b  = B, A+b  def  fib2 (n): #   return Fibonacci series up to n  result = [] A, b  = 0, 1 while  b < N:result.append (b) A, b  = B, A+b  return  result 

Now enter the Python interpreter and import the module with the following command:

>>> Import Fibo

Doing so does not directly fibo import the function in the current semantic table; it simply introduces the module name fibo . You can access this function by using the module name as follows:

>>> Fibo.fib (+)1 1 2 3 5 8 144 233 377 610 987>>> print ' \ n ', Fibo.fib2 (100
   
    ) [1, 1, 2, 3, 5, 8,, Fibo, +---
    ]>>>. 
    __name__ 
    ' 
    Fibo 
    '
   

If you want to call a function directly, you can usually assign it a local name:

>>> fib = fibo.fib>>> fib (1)1 2 3 5 8 13 21 34 55 89 144 233 377
In-depth modules

A module can contain execution statements as a function definition. These statements are typically used to initialize a module. They are only executed once when the module is first imported.

Corresponds to a global semantic table that defines all the functions in the module, each with its own private semantic table. Therefore, the module author can use some global variables in the module without causing an error because of a conflict with the user's global variables.

On the other hand, if you're sure you need this, you can get the global variables in the module just like the functions in the module, such as: modname.itemname .

modules can be imported (import) other modules. It is customary to put all import statements at the beginning of the module (or script, and so on), but this is not required. The module name is imported into the Global semantic table of this module.

Import A variant of the statement is imported directly from the imported module into the semantic table named in this module. For example:

 from Import fib, Fib2>>> fib (1)1 2 3 5 8 13 21 34 55 89 144 233 377

This does not import the module name from the local semantic table (as shown above, fibo not defined). This allows you to import all except the underscore ( _ ) begins with naming.

 from Import *>>> fib (1)1 2 3 5 8 13 21 34 55 89 144 233 377

This allows you to import all except the underscore ( _ ) begins with naming.

Module Search Path

When importing a module called spam , the interpreter searches the current directory for a file named spam.py and then searches in the directory list represented by the environment variable Pythonpath, followed by a list of paths in the environment variable path. If the PYTHONPATH is not set, or the file is not found, then search the installation directory .

In fact, the interpreter sys.path searches the module by the path directory specified by the variable, which, by default, contains the input script (or current directory), PYTHONPATH, and the installation directory. This allows the Python program (in this case, programs; I guess it should be "programer", programmer-Translator) Learn how to modify or replace a module search directory. It is important to note that because these directories contain scripts that run in the search path, these scripts should not have the same name as the standard modules, or Python will attempt to load these scripts as modules when importing the modules. This usually throws an error.

"Compiling" python files

For short programs that reference a large number of standard modules, there is an important way to improve startup speed, and if there is a file named Spam.pyc in the directory where spam.py is located , it is considered a pre-"compiled" version of the spam module. The modification time of this version of spam.py used to create SPAM.PYC is recorded in the spam.pyc file, and if the two do not match, the. pyc file is ignored.

Usually you do not need to do any work for creating SPAM.PYC files. Once spam.py compiles successfully, it attempts to compile the corresponding version of SPAM.PYC. If for any reason the write is unsuccessful, the returned SPAM.PYC file is considered invalid and subsequently ignored. the content of the Spam.pyc file is platform independent, so the Python module directory can be shared between machines of different architectures.

Some advanced tips:

  • When you invoke the Python interpreter with the- o parameter, the optimization code is generated and saved in the . pyo file. The optimizer does not have much help now; it simply removes the assertion (assert ) statement. With the- o parameter, all the code is optimized, the .pyc file is ignored, and the .py file is compiled to optimize the code.

  • Passing the two- o parameter to the Python interpreter (-oo) performs a fully optimized binary optimization compilation, which occasionally generates the wrong program. Now the optimizer simply removes the string from the binary code __doc__ and generates a more compact . pyo file. Because some programs rely on the availability of these variables, you should use this option only when you are sure of the error.

  • programs from. pyc files or . pyo files do not run faster than from. py files; . PYc or . pyo files are only faster when they are loaded.

  • When you run a script on the command line by the name of the script, the binary code that is created for the scripts is not written to the . PYc or . pyo file. Of course, the main code of the script is moved into a module, and then a small deconstruction script to import the module, you can increase the speed of the script startup. You can also specify a . pyc or. pyo file directly on the command line .

  • For the same module (referred to as routine spam.py), you can have only spam.pyc files (or spam.pyc, when using the- o parameter) without spam.py files. This allows you to package a Python code base that is more difficult to reverse engineer.

  • modules can be created for all modules in the specified directory  . pyc file (or create a. pyo file using the. pyo parameter).

Standard modules

Python comes with a library of standard modules and publishes separate documents, called the Python Library Reference Manual (hereafter referred to as the "Library Reference Manual"). There are modules built into the interpreter, which are not part of the language kernel, but are already built into the interpreter. This is both to improve efficiency and to provide interfaces for native access to operating systems such as system calls. Such a collection of modules is a configuration option that relies on the underlying platform. For example, theAmoeba module only provides support for amoeba native systems. There is a specific module worth noting:sys , this module is built into all python interpreters. Variables sys.ps1 and sys.ps2 defines the main prompt and the secondary support prompt string:

Import sys>>> sys.ps1' >>> sys.ps2'   ' C print ' yuck! ' yuck! C>

These two variables are only meaningful in the interpreter's interactive mode.

variables sys.path is a list of strings for the Interpreter module search path. It is initialized by the environment variable PYTHONPATH, and if no PYTHONPATH is set, it is initialized by the built-in default value. You can modify it with a standard string operation:

Import sys>>> sys.path.append ('/ufs/guido/lib/python')
Using the SYS module

Example 1: Using the SYS module

Import SYS Print ' The command line arguments is: '  for inch sys.argv:     Print I Print ' \n\nthe PYTHONPATH is ' ' \ n '

The results of the operation are as follows:

The command line arguments is:
f:/pycharmprojects/pytest/test.py


The PYTHONPATH is [' f:\\pycharmprojects\\pytest ', ' C:\\python27\\lib\\site-packages\\distribute-0.6.27-py2.7.egg ', ' C:\\python27\\lib\\site-packages\\wx-3.0-msw ', ' d:\\chardet-2.3.0 ', ' f:\\pycharmprojects\\pytest ', ' C:\\Windows\ \system32\\python27.zip ', ' c:\\python27\\dlls ', ' c:\\python27\\lib ', ' C:\\python27\\lib\\plat-win ', ' C:\\Python27\ \lib\\lib-tk ', ' c:\\python27 ', ' c:\\python27\\lib\\site-packages ', ' c:\\python27\\lib\\site-packages\\ Setuptools-0.6c11-py2.7.egg-info ']

dir ()Function

The built-in function dir () is used to find out which names a module defines. It returns a sorted list of strings:

The built-in function dir () is used to search for module definitions by module name, which returns a list of storage for a string type:

Import Fibo,sys Print dir (Fibo) Print ' \ n ', dir (SYS)

The results of the operation are as follows:

[' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' fib ', ' fib2 '] [' __displayhook__ ', ' __doc__ ', ' __egginsert ', ' __excepthook__ ', ' __name__ ', ' __package__ ', ' __plen ', ' __stderr__ ', ' __ Stdin__ ', ' __stdout__ ', ' _clear_type_cache ', ' _current_frames ', ' _getframe ', ' _mercurial ', ' api_version ', ' argv ', ' Builtin_module_names ', ' byteorder ', ' call_tracing ', ' callstats ', ' copyright ', ' displayhook ', ' dllhandle ', ' dont_write _bytecode ', ' exc_clear ', ' exc_info ', ' exc_type ', ' excepthook ', ' exec_prefix ', ' executable ', ' exit ', ' flags ', ' float_ Info ', ' float_repr_style ', ' getcheckinterval ', ' getdefaultencoding ', ' getfilesystemencoding ', ' getprofile ', ' Getrecursionlimit ', ' getrefcount ', ' getsizeof ', ' gettrace ', ' getwindowsversion ', ' hexversion ', ' long_info ', ' maxint ', ' MaxSize ', ' maxunicode ', ' meta_path ', ' modules ', ' path ', ' path_hooks ', ' path_importer_cache ', ' platform ', ' prefix ', ' Py3kwarning ', ' setcheckinterval ', ' setprofile ', ' setrecursionlimit ', ' settrace ', ' stderr ', ' stdin ', ' stdout ', ' Subversion ', ' Version ', ' Version_info ', ' warnoptions ', ' winver ' 

When no parameter is called, the dir () function returns the name of the current definition:

a=[1,2,3,4,5]import  Fibo,sysfibo=fibo.fibprint dir ()

The results of the operation are as follows:

 [ '  __builtins__  ,  " __doc__   ' ,  " __file__   ' ,  " __name__   ' ,  " __package__  , "  a  ,  '  fibo   ' ,  '  sys   ' ] 

The list lists the names of all types: variables, modules, functions, and so on:

dir () does not list built-in functions and variable names. If you want to list these things, they are defined in the standard module __builtin__ :

Import __builtin__>>> dir (__builtin__)

The results of the operation are as follows:

[' Arithmeticerror ', ' assertionerror ', ' attributeerror ', ' baseexception ', ' buffererror ', ' byteswarning ', ' Deprecationwarning ', ' eoferror ', ' ellipsis ', ' environmenterror ', ' Exception ', ' False ', ' floatingpointerror ', ' Futurewarning ', ' generatorexit ', ' IOError ', ' importerror ', ' importwarning ', ' indentationerror ', ' indexerror ', ' Keyerror ', ' keyboardinterrupt ', ' lookuperror ', ' memoryerror ', ' nameerror ', ' None ', ' notimplemented ', ' Notimplementederror ', ' oserror ', ' overflowerror ', ' pendingdeprecationwarning ', ' referenceerror ', ' RuntimeError ', ' Runtimewarning ', ' standarderror ', ' stopiteration ', ' syntaxerror ', ' syntaxwarning ', ' systemerror ', ' SystemExit ', ' Taberror ', ' True ', ' TypeError ', ' unboundlocalerror ', ' unicodedecodeerror ', ' unicodeencodeerror ', ' unicodeerror ', ' Unicodetranslateerror ', ' unicodewarning ', ' userwarning ', ' valueerror ', ' Warning ', ' windowserror ', ' zerodivisionerror ' ', ' __debug__ ', ' __doc__ ', ' __import__ ', ' __name__ ', ' __package__ ', ' abs ', ' all ', ' any ', ' Apply ', ' basestring ', ' Bin ', ' bool ', ' buffer ', ' bytearray ', ' bytes ', ' callable ', ' Chr ', ' classmethod ', ' cmp ', ' coerce ', ' compile ', ' complex ', ' copy Right ', ' credits ', ' delattr ', ' dict ', ' dir ', ' divmod ', ' Enumerate ', ' eval ', ' execfile ', ' exit ', ' file ', ' filter ', ' float ', ' Format ', ' Frozenset ', ' getattr ', ' globals ', ' hasattr ', ' hash ', ' help ', ' hex ', ' id ', ' input ', ' int ', ' intern ', ' Isinstanc ' E ', ' issubclass ', ' iter ', ' Len ', ' License ', ' list ', ' locals ', ' long ', ' map ', ' Max ', ' Memoryview ', ' min ', ' Next ', ' object ', ' Oct ', ' Open ', ' ord ', ' pow ', ' print ', ' property ', ' Quit ', ' range ', ' raw_input ', ' reduce ', ' reload ', ' repr ', ' reversed ', ' Round ', ' Set ', ' setattr ', ' slice ', ' sorted ', ' staticmethod ', ' str ', ' Sum ', ' super ', ' tuple ', ' type ', ' unichr ', ' Unicode ', ' VARs ', ' xrange ', ' Zip '

Package Packages

A package is typically a structured module namespace that uses the DOT module name. For example, a module named a.b represents a sub-module named "a" in a package named "B". Just as using modules to save different module architectures avoids collisions between global variables, using the DOT module name to save different class library architectures such as NumPy or Python Imaging libraries avoids naming conflicts between modules.

Suppose you now want to design a module set (a "package") to handle sound files and sound data uniformly. There are several different sound formats (typically identified by their extensions, for example:. wav, . AIFF, . au)), so, in order to convert between different types of file formats, you need to maintain a growing collection of packages. You may also want to do a lot of different things about sound data (such as mixing, adding echoes, applying the balance function, creating a man-made effect), so you have to add an infinite stream module to perform these operations. Your package might look like this (grouped by a hierarchical file system):

sound/                          top-level package      __init__.py Initialize The sound package      formats/                  subpackage for file Format Conversions              __init__.py              wavread.py              wavwrite.py              aiffread.py              aiffwrite.py              auread.py              auwrite.py ...      effects/                  subpackage for sound effects              __init__.py              echo.py              surround.py              reverse.py              ...      filters/                  subpackage for Filters              __init__.py              equalizer.py vocoder.py karaoke.py              ...

When you import a module, Python sys.path searches through the list of directories in the directory to search for subdirectories that hold the package.

There must be a __init__.py file in order for Python to view the directory as a package, to prevent some directories from accidentally overwriting the correct module in a subsequent module search path by using a generic name such as "string". In the simplest case,__init__.py can be just an empty file, but it may also contain the initialization code of the package, or set the __all__ variable, which is described later. Package users can import legitimate modules from a package, for example:

Import Sound.Effects.echo

This will import the Sound.Effects.echo Sub-module. It must be referenced by a full name.

Sound.Effects.echo.echofilter (input, output, delay=0.7, atten=4)

There is an alternative way to import a package:

 from Import Echo

This loads the echo submodule and makes it available without the package prefix, so it can be called as follows:

Echo.echofilter (input, output, delay=0.7, atten=4)

There is another variant for directly importing functions or variables:

 from Import Echofilter

so it's loaded again. Echo Sub-module, but you can call it directly Echofilter () function:

Echofilter (input, output, delay=0.7, atten=4)

It is important to note that from package import item when you import a package using the, this subkey (item) can be either a submodule (or a child package) in the package, or it can be another named, like a function, class, or variable defined in the package. importThe statement first checks whether the package has this subkey, and if not, it assumes that it is a module and tries to load it. If it is not found, a importerror exception is thrown.

instead, use a similar import item.subitem.subsubitem in such a syntax, these subkeys must be a package, and the last subkey can be a package or module, but not a class, function, or variable defined in the preceding subkey.

You may also be interested in:

Python Basics (11)-Object-oriented 1

Python Basics (10)--Digital

Python Basics (9)--Regular expressions

Python Basics (8)--File

Python Basics (7)--functions

Python Basics (6)-conditions, loops

Python Basics (5)--Dictionary

Python Basics (4)--string

Python Basics (3)--lists and tuples

Python Basics (2)--Object type

Python Basics (1)--python programming habits and features

Python Basics (12)--modules

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.