3. Packages and libraries in Python

Source: Internet
Author: User
Tags integer division pow sin

3.1 Concepts of modules and packages when the code is more and more, when all the code is concentrated in a file, it is difficult to maintain the code is separated into different py file, easy to maintain, the same name of the variables and functions do not affect each other as
 
   
  
  1. x = 5
  2. def F1 ():
  3. Pass
 
   
  
  1. #b. py
  2. x = ' str '
  3. def F1 (iterable):
  4. Pass
a.py and b.py variables and functions do not affect each other will a.py called Module A, b.py is called Module B, the name of the module is the name of the. py file introduced third-party modules #test.pyimport Mathprint Math.pow (2,10) When two different people write the module name conflict, the same name of the module into a different package can avoid this conflict such as P1.util and P2.util is two different module calls #test.py itself module name Import p1.util reference P1.util module pri NT P1.UTIL.F (2,10) calls the F function of the P1.util module in the file system, the package is the folder, the module is a. py file, similar to the domain name, the package can have a multilevel how to distinguish between a package and a normal directory, in Python, the package must have a __init__. PY files, each layer of the package must have such a file, even if it is an empty folder, only then Python will use this directory as a package to handle the 3.2 Python import module

To use a module, we must first import the module. Python imports a module using the import statement. For example, import the module that comes with the system, math:

Import Math

You can think of math as a variable that points to the imported module, where we can access all the exposed functions, variables, and classes defined in the Math module:

>>> Math.pow (2, 0.5) # POW is a function 1.4142135623730951>>> Math.PI # PI is a variable 3.141592653589793

If we only want to import some of the functions of the math module used, instead of all the functions, you can use the following statement:

From math import pow, sin, log

In this way, the 3 functions of pow, sin, and log can be referenced directly, but other functions of math are not imported:

>>> Pow (2, ten) 1024.0>>> sin (3.14) 0.0015926529164868282

What if I encounter a name conflict? For example, the Math module has a log function, logging module also has a log function, if used simultaneously, how to resolve the name conflict?

If you import the module name using import, there is no conflict because the function name must be referenced through the module name:

Import Math, Loggingprint math.log   # called the log function of math logging.log (' something ')   # called the Logging log function

If you use From...import to import the log function, it is bound to cause conflicts. At this point, you can give the function an "alias" to avoid the conflict:

From math import logfrom logging import log as Logger   # logging log now becomes Loggerprint log (   s) # called the Loglogger of math ( ' Import from logging ')   # call is logging log
3.3 Dynamic Import module in Python

If the imported module does not exist, the Python interpreter will report a importerror error:

>>> Import Somethingtraceback (most recent):  File ' <stdin> ', line 1, in <module>import Error:no module named something

Sometimes, two different modules provide the same functionality, such as Stringio and Cstringio, which provide Stringio.

This is because Python is a dynamic language that interprets execution, so Python code runs slowly.

If you want to improve the speed of Python code, the simplest way is to rewrite some key functions in C, which can greatly improve the execution speed.

The same functionality, Stringio is written in pure Python code, while the Cstringio part of the function is written in C, so Cstringio runs faster.

With Importerror errors, we often import modules dynamically in Python:

Try: From    Cstringio import stringioexcept importerror: from    stringio import Stringio

The above code attempts to import from Cstringio first, and if it fails (for example, Cstringio is not installed), try importing from Stringio. This way, if the Cstringio module is present, we will get a faster run, and if Cstringio does not exist, the code will run slower, but it will not affect the normal execution of the code.

The action of the try is to catch the error and execute the except statement when the specified error is caught.

Task

Using import ... as ..., you can also dynamically import modules of different names.

The Python 2.6/2.7 provides a JSON module, but Python 2.5 and earlier do not have JSON modules, but you can install a Simplejson module that provides the same function signatures and functions as the two modules.

Try to write the code to import the JSON module, which will work correctly in Python 2.5/2.6/2.7.

 
   
  
  1. Try :
  2. Import JSON
  3. Exceptimporterror:
  4. Import Simplejson
  5. Print JSON . dumps ({' python ':2.7})
3.4 Python's use __future__

New versions of Python introduce new features, but in fact these features already exist in the previous version. To "try out" a new feature, you can do so by importing some of the features of the __future__ module.

For example, the integer division operation of Python 2.7 is still an integer:

>>> 10/33

However, Python 3.x has improved the division of integers, "/" in addition to the floating-point number, "//" is still an integer:

>>> 10/33.3333333333333335>>> 10//33

To introduce the 3.x division rule in Python 2.7, import the __FUTURE__ division:

>>> from __future__ import division>>> print 10/33.3333333333333335

When an attribute of the new version is incompatible with the old version, the feature will be added to the __future__ in the old version so that the old code can test the new feature in the old version.

Task

In Python 3.x, string unification is Unicode, no prefix u is required, and str stored in bytes must be prefixed with B. Use __future__ 's unicode_literals to write Unicode strings in Python 2.7.

 
   
  
  1. #py2.7
  2. from __future__ import unicode_literals
  3. s = ' am I an Unicode? '
  4. print isinstance ( Span class= "PLN" >s Unicode )
3.5 Installing a third-party module Python provides two module management tools 1.EASY_INSTALL2.PIP (recommended, already built into python2.7.9 later versions) to download the latest version of Python https://www.python.org/ Ftp/python/2.7.13/python-2.7.13.msi setting Python's installation directory to the environment variable in the system during the installation process in CMD to open Python and install with PIP third-party modules can use PIP- H to get the use of the PIP command if you use the PIP tool to install the web.py library, you can find information about Python's open source third-party packages on the website Https://pypi.python.org/pypi


Null

3. Packages and libraries 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.