[2-1] Advanced Python module | import module / import module dynamic / use __future__ / Scoping

1, import module

To use a module, we must first import the module. Python import statement using a module. For example, a module built into the system math:

import math

You can think math is a pointer to the variable module has been imported by the variables, we can access all public functions, variables and class math module defined:

>>> math.pow(2, 0.5) # pow是函数
1.4142135623730951

>>> math.pi # pi是变量
3.141592653589793

If we only want to import math module used in a number of functions, not all the functions, you can use the following statement:

from math import pow, sin, log

Thus, direct reference pow, sin, log three functions, but other functions are not introduced come math:

>>> pow(2, 10)
1024.0
>>> sin(3.14)
0.0015926529164868282

If you encounter a name conflict how to do? For example, math module has a log function, logging module also has a log function, if used at the same time, how to resolve name conflicts?

If you use import to import the module name, because the name of the function must be referenced by the module name, so there is no conflict:

import math, logging
print math.log(10)   # 调用的是math的log函数
logging.log(10, 'something')   # 调用的是logging的log函数

If you use the from...importimport log function, it is bound to cause conflict. In this case, since a "Alias" to the function to avoid conflicts:

from math import log
from logging import log as logger   # logging的log现在变成了logger
print log(10)   # 调用的是math的log
logger(10, 'import from logging')   # 调用的是logging的log

task:

Python's os.path module provides isdir () and isfile () function, import the module, and call the function to determine whether the specified directory and file exists.

note:

  1. As the operating environment is the platform server, so the test is also a server folders and files, there is / data / webroot / resource / python and /data/webroot/resource/python/test.txt file folders on the server, you can under the test.

  2. Of course, you can test whether there is a corresponding folders and files on this machine.

import os
print os.path.isdir(r'C:\Windows')
print os.path.isfile(r'C:\Windows\notepad.exe')

CODE:

import os
print os.path.isdir(r'/data/webroot/resource/python')
print os.path.isfile(r'/data/webroot/resource/python/test.txt')

2, the dynamic import module

If you import the module does not exist, Python interpreter will report ImportError error:

>>> import something
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named something

Sometimes, two different module provides the same functionality, such as StringIO and cStringIO StringIO provides this function.

This is because Python is a dynamic language, interpreted, therefore Python code runs slow.

If you want to increase the operating speed of Python code, the easiest way is to rewrite some of the key functions in C language, so that we can greatly improve the speed of execution.

The same function, StringIO is written in pure Python code, and cStringIO part of the function is written in C, so cStringIO run faster.

Use ImportError wrong, we often Dynamically importing modules in Python:

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

The code introduced from cStringIO first try, if it fails (such cStringIO not installed), and then try to import from StringIO. Thus, if cStringIO module is present, then we will get faster speed, if cStringIO does not exist, at most, the code will run slower, but it will not affect the normal execution of the code.

Try to capture action is wrong, and execute the statement except when capturing the specified error.

task:

Use import ... as ...may also be introduced into the dynamic modules of different names.

Python 2.6 / 2.7 provides a json module, but Python 2.5 and earlier versions do not json module, but you can install a simplejson module, function signature and functions of these two modules provide exactly the same.

Write the code into json module can be operable at Python 2.5 / 2.6 / 2.7.

CODE:

try:
    import json
except ImportError:
    import simplejson as json
print json.dumps({'python':2.7})


3, using __future__

The new version of Python will introduce new features, but in fact these functions on an older version already exists. To "try" some new features, can be achieved by importing certain functions __future__ module.

For example, Python integer division integer result is still 2.7:

>>> 10 / 3
3

However, Python 3.x has improved integer division operation, "/" will be in addition to float, "//" In addition it still is an integer:

>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3

3.x division rule to be introduced in Python 2.7, introducing the __future__ division:

>>> from __future__ import division
>>> print 10 / 3
3.3333333333333335

When a new version of a feature is not compatible with older versions, this feature will be added in the old version to __future__ so old code to test the new features in the old version.

task:

In Python 3.x, the Unicode string is uniform, no need to add a prefix u, and stored in bytes must str prefixed b. Please use __future__ of unicode_literals write unicode string in Python 2.7.

CODE:

from __future__ import unicode_literals

s = 'am I an unicode?'
print isinstance(s, unicode)

4. Scope

In a module, we might define a lot of functions and variables, but some functions and variables we want to give to others to use, some functions and variables we want to use only inside the module.
In Python, it is achieved by _ prefix.

Normal function and variable names are public (public), it may be directly referenced, for example: abc, x123, PI and the like;

Similar __xxx__ such variables are special variables that can be directly referenced, but there are special purposes, such as the above __author __, __ name__ is a special variable, hello module definition documentation comments can also use special variables __doc__ visit, we own variable generally do not use this variable name;

Similar _xxx __xxx and such a function or variable is non-public (Private), should not be a direct reference, such _abc, __ abc the like;

The reason why we say, private functions and variables "should not" be referenced directly, rather than "can not" is a direct reference, because Python is not a way to completely restrict access to private functions or variables, however, not from the programming practice You should refer to private functions or variables.

private function or variable should not be cited by others, that they have what use is it? See examples:

def _private_1(name):
    return 'Hello, %s' % name

def _private_2(name):
    return 'Hi, %s' % name

def greeting(name):
    if len(name) > 3:
        return _private_1(name)
    else:
        return _private_2(name)

Our public greeting in the module () function, and the internal logic by hiding the private function, so call the greeting () function do not care about the details of the internal private function, which is a very useful code package and abstract way, which is:

Function does not require an external reference in its entirety defined as private, only you need to reference external function was defined as public.

Published 20 original articles · won praise 0 · Views 394

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/104493181