Home
Home Page
And again about functional programming on Python
Where the Python has come crawling?
Practical application OOP in PHP5
Functional programming in language Python
Approaches of language Python - an amusing example of optimization
Use ext/mysqli: Part I - the Review and the prepared expressions
How to receive the maximal result from registration in catalogues
XML-RPC In language Python
The API-specification of databases of language Python, version 2.0
Programming of the Web-client in language Python
Useful advice for job with XML
Future Web - behind semantics
Whether it is necessary to cancel spaces of names XML?
Use AJAX in ASP.NET
ASP .NET 2.0: Reference pages
Patterns of registration
What is ASP.NET. Installation and the test project.
Anatomy ASP.NET. ASP.NET in operation.
Server elements of management Continuation.
Links
 
topic



Where the Python has come crawling?

Introduction


On April, 17, 2001 has left Python 2.1. In spite of the fact that younger number{room} of the version has changed only on unit, the quantity{amount} of additions in language and libraries is comparable to that, that has been brought in 2.0 in comparison with 1.6 (however, a principal cause of that after version 1.6 has left 2.0, instead of 1.7, there was a necessity precisely to separate all subsequent versions, from the versions, leaving under aegis CNRI).


One of the largest changes concerns not the language, and process of his{its} development. Though (fortunately) Python has saved "dictatorial" model of development when the author of language has absolutely deciding{solving} word in acceptance or nonacceptance of any offers on expansion / change of language or libraries, the model of entering, discussions and acceptances of such offers has changed, becoming{beginning} ordered and formalized. She is based on PEP (Python Enhancement Proposals - offers on expansion Python). PEP - the document describing offered{suggested} new property of language (Standard Track PEP) or giving some essential information to community of users Python (Informational PEP). As an example of the last can serve PEP0001 - PEP Purpose and Guidelines, describing applicability and mechanism PEP. Kategorizovannyj the index of all PEP is on http://python.sourceforge.net/peps/. < =http%3A%2F%2Fpython.sourceforge.net%2Fpeps%2F.> Python 2.1 - the first version completely developed on the basis of model PEP.

Additions in language

Statically enclosed spaces of names (nested/lexical scopes)


This change concerns a way by which in Python names inside functions are resolved. Language Python has the block structure similar to languages algol`nogo of type (to which, with some clauses, concerns and C). Base unit (area) of the program are the module, definition of a class or function. Statically enclosed spaces of names define{determine} the order of search of the name met in the block, as consecutive search, since the nearest leksicheski the comprehensive block and in the direction of more and more external.


In Python 2.0 (and earlier) any name on which there was a link in function, was consistently searched in three spaces of names:


* In local (actually that function where the link has appeared), then if not it is found,

* In global (space of names of the module where function is determined), then

* In space of the built - in names (the module __ builtins __).


This rule of search sometimes name LGB (Local, Global, Builtin). Thus, for the enclosed functions (t.e, functions certain{determined} inside other functions), search of names was made in precisely the same way, i.e. if the name has not been found directly in space of names of the enclosed function, it at once started to be searched in global space, instead of in comprehensive function. It differed from logic of other block languages where search is made consistently in all comprehensive areas.



* An example of the sanction of a name in the enclosed function

x = ' Global area '

def external ():

x = ' Area of function " external () " '

def nested ():

print " Inside nested () x == ' %s " % x

nested ()


external ()


The above-stated example gives out for Python versions 2.0 or 1.5:


Inside nested () x == ' Global area '


Such logic results in the following troubles:


* These rules are unevident for newbies in Python, possessing experience of programming in other languages, for example, Pascal (and even for nenovichkov they continue to remain strange);

* Applicability of a design lambda is limited, as in the unique way to pass in lambda-function the element of a context of comprehensive function appears a unnatural and ugly design with application of default settings;



* An example of use lambda without the enclosed space of names

def incrlist (lst, incr):

* Inside labmbda the variable incr is not visible, therefore we pass her{it} as the held back parameter

map (lambda x, incr = incr: x + incr, lst)


* Impossibility of a recursive call of the enclosed function (for quite obvious reason - the name of the enclosed function is determined in a context comprehensive and as consequence{investigation}, is invisible to it{her}!)


Introduction in version 2.1 of rules of a name resolution similar to another{others} block languages in the enclosed areas is called to solve these problems. But that new rules can call problems with the return compatibility, the enclosed spaces of names are entered as opcional`noe property (__ future __) with a name nested_scopes. In version 2.2 this property becomes obligatory.



* To switch on the enclosed spaces of names

from __ future __ import nested_scopes


Thus, if nested_scopes it is switched on, the name is consistently searched in all comprehensive contexts (except for a context of a class), will not be found yet. The context of a class is excluded to not break edinobrazija rules of access to attributes in Python which demand, that object to which attribute access is necessary, was set always. In result the above-stated example will give out:


Inside nested () x == ' Area of function " external () " '


And the above-stated example with a design lambda can be written down naturally:



def incrlist (lst, incr):

map (lambda x: x + incr, lst)


If nested_scopes it is switched off, Python uses old semantics of spaces of names, but gives out preventions{warnings} of all sites of a code which sense will change at application of new semantics. It enables to correct such code up to an output{exit} of version 2.2 (if you, certainly, do not prefer to remain for ever with version 2.1 or 2.0).



The mechanism of introduction of new properties in language


Developers of language Python traditionally try to make changes to language so that to not mention compatibility with programs on Python, written for the previous versions. But nevertheless from time to time it is necessary to make incompatible changes - more often when any chronic flaw of design of language, or (is corrected much less often!) if compatibility appears an absolute obstacle for entering into language of absolutely necessary property. To soften consequences of such changes and to facilitate transition to new versions, in language the agreement has been added, allowing to include such properties opcional`no, but only on a transition period in one or several versions after which they become obligatory. For this purpose __ future __ directive is used.


__ future __ directive - the usual operator of import using the preserved name of the module __ future __:



from __ future __ import feature


Where feature - a name of included property. __ future __ directive - a design of time of compilation, instead of performance as she can influence generation bajtkoda and even on perception{recognition} of syntax the compiler. Therefore in the text of the module before this design there can be only comments and a line of the documentation (and, naturally, other statements __ future __). Thus for any given release of language all allowable names feature (i.e. names opcional`nykh properties) are strictly determined, and at use of an invalid name the mistake kompiljacii1,2 is given out.


For any property fraught serious nesovmestmost`ju, the transition period (expressed in terms of numbers{rooms} of versions) during which it is opcional`nym is set. After this period it becomes an obligatory part of language (i.e. is present without dependence from the statement __ future __). For example, statically enclosed spaces of names - opcional`noe property in version 2.1, but, since version 2.2 - obligatory.



* To switch on the enclosed spaces of names

from __ future __ import nested_scopes


During transitional if property is not switched on, for the designs, able to change sense after his{its} inclusion, the prevention{warning} is given out. After the transition period for for some property expires, __ future __ directive with a name of this property is simply ignored by the compiler. It provides full " direct compatibility " with the future versions of language for the source codes using __ future __.



The mechanism of preventions{warnings}


Besides the mechanism of delivery of error messages which role in Python is provided with processing of exceptions, in many languages there is also a mechanism of delivery of preventions{warnings}. The prevention{warning}, as against exception. Is not fatal, but signals about a possible{probable} mistake of programming, ambiguity or about use of out-of-date (becoming outdated) property of language.


Since version 2.1, in Python the mechanism of preventions{warnings} also is entered. His{its} main applicability - to inform the programmer on use of out-of-date opportunities, and also opportunities which can be changed or removed in the future version of language (see __ future __). For example, in version 2.1 it is not recommended to use the module regex (actually, he is obsolete in version 2.0):



>>> import regex

__ main __:1: DeprecationWarning: the regex module is deprecated; please use the re module


Preventions{Warnings} can be given out both during compilation, and in execution time. Thus at the prevention{warning} there is a name of the module and a line, whence it is given. Functionality of delivery of the prevention{warning} provides the module warnings, and the user modules also can use it{him} for delivery of own preventions{warnings}. It is entered also C API for delivery of preventions{warnings} from expansions and programs with the built - in interpreter (PyErr_Warn ()) 3.


All preventions{warnings} share on a category. Categories of preventions{warnings} make hierarchy of classes, like exceptions, with root class Warning. Class Warning, in turn, a derivative from class Exception that allows to transform preventions{warnings} to exceptions if it is necessary (see below the description of kill of messages). For today standard hierarchy of categories of preventions{warnings} following:


* Warning

o

UserWarning a base category by default for warning.warn ()

DeprecationWarning a base category for messages on cancelled / out-of-date properties of language

SyntaxWarning a base category for preventions{warnings} of use of doubtful syntax

RuntimeWarning a base category for preventions{warnings} of use of doubtful opportunities of execution time (for example, dependent on realization)


As well as in a case with processing exceptions, at kill the base category includes all derivatives.


To give out the prevention{warning} from programy on Python, it is necessary to use function



warnings.warn (message [, category [, stacklevel]])),


Where message - actually a line of the message; category - a category of the message, a derivative from Warning (by default - UserWarning); stacklevel - a relative level of a stack for which the message is given out.



* An example of delivery of the prevention{warning}

import warnings

warnings.warn (" Property X depends on realization ", RuntimeWarning)


The parameter stacklevel is very useful to creation of the general{common} functions for delivery of preventions{warnings}. For example:



* In this example stacklevel = 2 results to that are present at the given prevention{warning}

* A name of the module and a line, whence there was _vyzvana_ a function implementation_dependent (). If this

* The parameter has not been set, at the prevention{warning} there would be a module and a line where _opredelena_

* Function implementation_dependent (), that would make its{her} definition senseless!

*

def implementation_dependent (feature):

warnings.warn (" the Result %s depends on realization! " % feature, RuntimeWarning, stacklevel = 2)


In spite of the fact that, as a rule, the programmer needs to see all preventions{warnings} (to finish a code with such status, that they will disappear), there are cases when they are necessary for suppressing. So, for example, can happen. If the prevention{warning} is given out from a "another's" code or if terms do not allow to correct a code immediately, and the industrial version should not bombard the user the preventions{warnings} which are not having to it{him} the attitude{relation}. Thus simply to disconnect delivery of all preventions{warnings} it is impossible - can appear suppressed necessary. On the other hand, some preventions{warnings} are reasonable for interpreting as a mistake - for example if the code is modified with the purpose of clearing of long-term stratifications, it is meaningful to interpret all DeprecationWarning as exceptions is will allow to catch all out-of-date code quickly. For this purpose the mechanism of preventions{warnings} supports kill.


Kill allows to set reaction of language to the preventions{warnings} selected by set criteria. As criteria can act:


* A place where the prevention{warning} (the module, number{room} of a line) is generated;

* A category of the message;

* The text of the message (regular expression).


The filter can use one criterion or their any combination. Filters are set by function



warnings.filterwarnings (action [, message [, category [, module [, lineno [, append]]]]]).


Examples of filters are below resulted:


You went from version 1.5.2 on 2.1. All excellently continues to work, but your program uses out-of-date modules regex and TERMIOS, therefore gives out preventions{warnings} at each start. To not frighten users, you add a code overwhelming all preventions{warnings} of out-of-date modules in the industrial version:



import warnings

warnings.filterwarnings (action = "ignore", category = DeprecationWarning)


In the meantime, you want to clean all places where it is used TERMIOS, but decide what to pass with regex on re too difficultly, and add in the debugging version the following code:



import warnings

* To count preventions{warnings} about TERMIOS mistakes

warnings.filterwarnings (action = "error", category = DeprecationWarning, module = "TERMIOS")

* To suppress preventions{warnings} about regex

warnings.filterwarnings (action = "ignore", message = " .*regex module. * " category = DeprecationWarning)


Filters of preventions{warnings} can be set also from command line Python with pomosh`ju parameter-W filter where filter it is set as action:message:category:module:lineno. Any element of the filter can be lowered{omitted}:



python-W ignore:: DeprecationWarning::



Weak links (weak references)


Weak links - the new type of the data entered in Python 2.1, allowing to solve problem of cyclic links and dynamic keshirovanija. Weak links allow to refer to object, not increasing his{its} counter of links.


All usual links in Python - "rigid" - owning object to which refer. Management of memory and time of a life of objects in Python is carried out by calculation of links. It means, that any object lives until on him{it} there is even one link (and it is destroyed immediately at removal{distance} of last link). It is very convenient - on the one hand, allows to not care of management of memory, with another - provides determined time of a life of object (in difference, for example, from Java). But such model is not capable to solve a number{line} of problems:


* Cyclic links. The cyclic link arises, if object A contains direct or indirect (through some other objects) the link to object B, and object B, in turn, contains the direct or indirect link on A. It results to that the objects which are included in a cycle, become "immortal" - their counters of links never become equal 0, even when all links from the outside are removed. The problem will be, that cyclic structures are natural to many problems{tasks} - it is necessary to mention only GUI where the parental window contains links to the elements, and those - the link to a parental window. In part the problem is solved the collector of dust (the module gc), but this decision is unsuccessful - first, time of a life appears not determined, second - destruktory for the collected objects are never caused, that can be fatal to logic of the program;


* Dynamic keshirovanie objects. We shall imagine the function returning object, which creation is expensive enough (and-or borrowing{occupying} many{a lot of;much} memories), thus the inwardness of object can be divided{shared}. In such (enough often) situations the cache of objects is used:



def create_n_cache (param, cache = {}):

try:

* We shall check up, whether is in keshe required value

retval = cache [param]

except KeyError:

cache [param] = retval = _really_create ()

return retval


At this approach there are following problems: or we admit unlimited growth kesha (in the above-stated example the objects stored{kept} in keshe, will be cleaned only at end of the interpreter or at perezagruzke the module in which it is determined create_n_cache ()), or from time to time we cause the function cleaning kesh from inputs{entrances} which counter of links is equal 1. Both approaches can appear, and often appear, unacceptable - the first under the charge of the memory, the second - on speed (at each reference{manipulation} all is scanned kesh).


The mechanism of weak links allows to solve above mentioned (and many others) problems. The weak link - the object specifying object Python, but the counter of links not increasing it. Not on all objects it is possible to create the weak link; it is possible to create weak links to objects of classes, functions (written on Python), methods (connected and untied).


The module weakref gives two kinds of links - actually the link (reference) and delegator (proxy). The link to object can be received, having called the designer



weakref.ref (object [, callback]).


The parameter callback can set function which will be called before removal{distance} of object which the link specifies.



* To create the weak link to object

import weakref

from UserList import UserList

object = UserList ([1, 2, 3, 4])

wr = weakref.ref (object)

* To receive real object, it is necessary razymenovat` the link, simply having called her{it} as function

print " reference == %r object == %r " % (wr, wr ())

* We delete real object. If the object which the weak link specifies, leaves,

* razymenovanie links returns None

del object

print " reference == %r object == %r " % (wr, wr ())


The example will deduce{remove} the following:



reference == <weakref at 0x86475c; to 'instance' at 0x8627cc> object == [1, 2, 3, 4]

reference == <weakref at 86475c; dead> object == None


Delegator (proxy reference) - the weak link behaving (so as far as at it{her} it turns out) as object to which she refers, i.e. access to attributes delegatora perenapravljaetsja to attributes of initial object. Delegator it is created by a call weakref.proxy (object [, callback]):



* To create the weak link - proxy to object

import weakref

from UserList import UserList

object = UserList ([1, 2, 3, 4])

proxy = weakref.proxy (object)

print " reference == %r " % proxy

* Delegator behaves the same as initial object

print " object [0] == %s, object [-1] == %s " % (proxy [0], proxy [-1])

* We delete real object. If the object which specifies delegator, leaves,

* delegator specifies on None (and behaves accordingly)

del object

* Attempt to index None will call rough indignation of the interpreter

print " object [0] == %s, object [-1] == %s " % (proxy [0], proxy [-1])


Predictably, the example comes to the end with a mistake:



reference == <weakref at 0086475C to instance at 008627CC>

object [0] == 1, object [-1] == 4

Traceback (most recent call last):

File "testproxy.py", line 13, in?

print " object [0] == %s, object [-1] == %s " % (proxy [0], proxy [-1])

weakref. ReferenceError: weakly-referenced object no longer exists


The module weakref defines{determines} a class perfectly suitable to creation keshej - WeakValueDictionary. It is the dictionary, links to values in which - weak. At destruction of object on which there is a link in such dictionary, a corresponding input{entrance} in the dictionary (the key and value) automatically leave. Function create_n_cache () with use WeakValueDictionary could look so:



import weakref

def create_n_cache (param, cache = weakref. WeakValueDictionary ()):

* We shall check up, whether is in keshe required value

retval = cache.get (param)

if not retval:

cache [param] = retval = _really_create ()

return retval



New model of reduction of types


The mechanism of reduction of numerical types for expansions on C is considerably modified.


Earlier it was required, that binary numerical operations always received arguments of identical type, and consequently PyNumber_Coerce () always was automatically caused before a call of corresponding operation. Now the module of expansion can establish flag Py_TPFLAGS_CHECKTYPES among flags of structure PyTypeObject to show, that the given type supports new model of reduction. Thus PyNumber_Coerce () it will not be caused in general, and operands will be passed the numerical operations determined in this type, " as the responsibility for processing of operands of different types is shifted directly on operation (naturally is ". Thus, the first operand will always have the set type as it self). In the event that operation cannot process an operand of the set type, she can return the index on special global object - Py_NotImplemented. In this case the interpreter causes symmetric operation of other operand. If also this operation returns Py_NotImplemented, exception is raised. This algorithm can be presented the following pseudo-code on Python:



* A pseudo-code describing performance of binary arithmetic operations for new rules of reduction of types

def binary_operation (o1, o2):

result = o1. __ binary_operation __ (o2)

if result is NotImplemented:

result = o2. __ binary_operation __ (o1)

if result is NotImplemented:

raise TypeError, " operation is not realized for the given types of operands "

return result


If at type flag Py_TPFLAGS_CHECKTYPES is not established, to it{him} old rules of reduction (with call PyNumber_Coerce ()) are applied, that allows to provide full return compatibility.


* New rules of reduction possess essential advantages:

* Give an opportunity to define{determine} individual logic of processing of different types for different operations;

* Do not result in call PyNumber_Coerce () at each operation

* Allow to process elegantly situations, when there is no the general{common} type in which it would be possible to result diverse operands of completely correctly certain operation (an example - above types DateTime and DateTimeDelta from expansion mxDateTime operations of addition and subtraction, but the general{common} type in which they can be resulted are determined, no)



The expanded mechanism of comparison


The new mechanism of comparison allows to define{determine} separate functions for realization of different operations of comparison (<>, <=,> =, ==! =) both for classes, and for expansions on S.Krome togo, he allows to define{determine} the operations of comparison returning values which type is distinct from bulevskogo.


The standard mechanism of comparison Python provides realization of operations of comparison for a class by means of one function - __ cmp __ (or, accordingly, tp_compare slot for type of expansion). This function should return-1, 0 or 1 (it is less, equally, it is more accordingly) and to return bulevskoe value. Such approach is simple, but possesses several serious lacks:


* It is impossible to define{determine} the function of comparison returning result not bulevskogo of type. Sometimes such operation has deep sense - for example, comparison of two matrixes should return a matrix of results poehlementnogo comparisons;

* There is a set of types for which equality is determined, but not the attitude{relation} of the order. At definition of function of comparison for such types it is necessary to enter artificial ordering though would be correct to raise

Exception at attempt to compare objects somehow except for == or! =;

* Often it is possible to optimize essentially operation of comparison, knowing, which comparison is carried out, but function __ cmp __ does not possess such information.


The expanded mechanism of comparison allows to overcome these restrictions, entering an opportunity of definition of separate operations of comparison. In a class the following methods (all or any set) 5,6 can be determined:


== __ eq __

! = __ ne __

<__ lt __

> __ gt __

<= __ le __

> = __ ge __


Functions of the expanded comparison can return values of any types.


The expanded comparison submits to the following rules:


* Python supports reflexivity of operations of comparison. The interpreter considers, that operation A <B is equivalent B> A, and A <= B is equivalent B> = A. If at comparison A <B the interpreter finds out, that operation <for A is not determined, he tries to execute B> A. The same is correct and for <=. It results to that for a class (such as) often it is enough to define{determine} operations ==! =, <, <=;

* Python does not support komplementarnost` operations of comparison, i.e. does not consider, that A! = B it is equivalent! (A == B), or A> = B it is equivalent! (A <B);

* If brief recording of compound comparison (X <Y <Z) is used and any from operations of comparison (for example, X <Y) returns the sequence, Python does not do{make} attempts to interpret result as bulevskij and raises exception;



Attributes of functions


In Python 2.1 functions can have the dictionary of attributes, like classes or modules. To those functions written on Python, any user attributes can be appropriated{given}. This change is in the general{common} channel of evolution Python aside generalizations as does{makes} functions in the greater degree " citizens of the first grade ".


In the previous versions of function also had a set of attributes (__ doc __ AKA func_doc, __ name __ AKA func_name, func_code, func_defaults, func_globals), but this set is fixed, only a part of attributes can be written down (__ doc __, func_code, func_defaults), thus only one of written down attributes possesses more - less "any" semantics, allowing to connect with function some any information - __ doc __. It results to that " the line of the documentation " is used by different systems for set of the different purposes which are not having to the documentation the attitude{relation}. For example, Zope Web-server uses this attribute for the description of the "published" interface; in system of analysis of small languages SPARK in attribute __ doc __ rules of analysis, etc are located. Such approach is unsuccessful for the several reasons:


* Different ways of use are incompatible; as a result of the system, functions using attribute __ doc __, cannot be shared (or, at least, have very serious restriction on the joint interface);

* Such application does{makes} impossible for what this attribute directly is intended - documenting. So, published functions in Zope cannot be normal otdokumentirovany;

* And, at last, unusual use of some opportunity is poorly simple because does{makes} a code unevident.


To solve these problems, the standard attribute is added to object of function __ dict __ and an opportunity of addition of any user attributes. Syntax of manipulations with attributes of function same as with attributes of object of a class, i.e. the first giving to attribute creates it{him}, del - deletes from the dictionary, etc.



* The example creates attributes published and return_type functions cvt ()

def cvt (s):

"" Function returns the argument transformed to floating and delenyj half-and-half ""

return float (s) / 2.0

s.published = 1

s.return_type = type (1.0)


As against a class or object of a class, to attribute __ dict __ value is possible to appropriate{give} functions obviously, but it should be or the real dictionary (i.e., for example, UserDict to appropriate{give} it is impossible), or None. In the latter case all user attributes of function udaljajutsja7.



* The example creates attributes published and return_type functions cvt ()

def cvt (s):

"" Function returns the argument transformed to floating and delenyj half-and-half ""

return float (s) / 2.0

s. __ dict __ = {"published":1, "return_type": type (1.0)}


To methods of a class (both connected (bound), and free (unbound)) attributes directly to appropriate{give} it is impossible, but it is possible to appropriate{give} attributes of the function being realization metoda5:



class A:

def a (): pass


*!!!! THE MISTAKE!!!!

A.a.published = 1


* Correctly

A.a.im_func.published = 1


It is necessary to notice, that attributes can be appropriated{given} only to the functions written on Python; functions of expansions of it to do{make} do not allow.



Obrabotchik exceptions of the top level


Sys.excepthook slot is added, allowing to redefine obrabotchik exceptions of the top level. Value of this slot should be the function accepting type of exception, his{its} value and traceback. This function is caused, if exception is not processed by any block try... except, allowing, thus, to redefine reaction to the raw exception.



Obrabotchik a conclusion of values in an interactive mode of the interpreter


Sys.displayhook slot is added, allowing to redefine a conclusion of values in an interactive mode of the interpreter. The interactive mode is carried out in mode REPL - Read-Evaluate-Print Loop. By default in this mode the result of performance evaluate is deduced with the help of function repr (). sys.displayhook allows to redefine this behaviour. Value sys.displayhook should be function (more precisely, any caused object). This function is caused as a print-stage of cycle REPL with the parameter which is growing out of performance of the entered command (a stage evaluate). The code of this function is by default equivalent to the following:



import __ builtin __

def displayhook (o):

if o is None:

return

__ builtin __._ = None

print 'o'

__ builtin __._ = o


Example of function of a conclusion:



* This function replaces standard sys.displayhook

* Very beautifully deduces complex{difficult} structures of the data (dictionaries / ?»??¬?/¬«?????)

* It is meaningful to place her{it} in sitecustomize.py

import __ builtin __, sys

from pprinter import pprint

def pretty_display (object):

if object is None: return

__ builtin __._ = None

pprint (object)

__ builtin __._ = object

sys.displayhook = pretty_display



Additions in the mechanism of import


* Rules of import the platforms tolerant to the register of names of files (Windows, Mac OS), are simplified and made uniform. Earlier, if at performance of a design import file Python found in way File.py, he immediately raised exception ImportError even if in any from the following catalogues in a way the file file.py was. Now he searches down to the first full concurrence (i.e. in described case File.py it will be missed, file.py is found and loaded). It does{makes} rules of search under Windows/Mac and Unix identical. The one who wants that on such platforms Python at all did not distinguish the register of names at import, can define{determine} a variable of PYTHONCASEOK environment (in the described case it would lead to to loading File.py). Under Unix the register of names differs always;

* The module can obviously define{determine} a set of the names imported from him{it} by a design from... import *. In the module the list __ all __ which elements should be the names determined in the module can be determined. from... import * will import only that is listed in this list (a rule according to which from... import * ignores the names beginning with underlining{emphasis}, remains);

* from M import N works now even in the event that sys.modules ['M'] - not the module. Generally, this operation is equivalent to a code:



N = getattr (sys.modules ['M'] ', name ')


(it is natural, if in sys.modules there is no input{entrance} M, all over again there is an import of the module)

* Call PyImport () C API is realized through call PyImport_ImportModule (). In result all calls of import programs on C/C ++ take into account interception of import (for example, through imputil, etc.)



The new and changed modules


inspect - the new module, allowing to receive weight of the helpful information on the carried out program on Python. Actually, he gives a convenient wrapper for various use of every possible "special" attributes of objects of language (func_ *, co_ *, im_ *, tb_ *, etc.), and also powerful means introspekcii a code, descriptions of classes, etc.


pydoc - tremendous means of operative viewing and searches to the online-documentation for Python. Allocates an interactive mode of the interpreter with the opportunities similar to help means Emacs, man and info. In a status to take the documentation both from a code of modules, and from files HTML. As an additional opportunity can be started as the server of the documentation, allowing to do{make} searches through a usual Web-browser, including on a network; thus the browser receives the answer as fine formatted HTML.


doctest and unittest - the modules intended for support of testing of other modules. doctest provides the shell for the testing, carrying out the tests which have been built - in in __ doc __ - lines of functions, and comparing a real conclusion with expected. unittest - much more powerful module, pitonovskaja version JUnit, shells for testing programs on Java (in turn, being the Java-version of a similar package for Smalltalk). Supports creation and run of packages of tests. Thus packages of tests, as against the approach doctest, are separate suhhnostjami.


difflib - gives class SequenceMatcher, allowing to calculate a difference between the sequences, allowing to restore one sequence from another. It allows to write programs of creation and imposing of patches. Besides the algorithm used by him{it} gives out results which look "correctly" from the point of view of human perception{recognition} that allows to write qualitative programs postrochnogo comparisons, like diff. As an example see Tools/scripts/ndiff.py


New version PyXML. Supports Expat versions 1.2 and the subsequent. For versions Expat 1.95 and above supports additional obrabotchiki. Supports analysis of files in all codings supported Python. Set ipravlenij in modules sax, minidom, pulldom.


In the module zipfile objects of class ZipFile can be designed now not only from a name of a file, but also from any "fajlopodobnogo" object.


The module random now is self-sufficient and gives all functionality earlier given by the module whrandom (which now it is considered out-of-date).

Other changes

continue can be present now at the block try, taking place in a body of a cycle.


The new method is added to the dictionary - popitem (). He returns the any (not determined) element of the dictionary, deleting it{him} from this dictionary. The method is intended for destroying consecutive sample of values of the dictionary if the order of sample has no value, and gives an essential prize for the big dictionaries in comparison with preliminary creation of the list of elements with the subsequent sample. Very conveniently for applications where the dictionary is used as the container of elements which everything is necessary to process, is unimportant in what order;


strochno-guided input from text files is considerably accelerated. The method readline () began to work approximately in 3 times faster;


The new file method - xreadlines () is added. He concerns to readlines () the same as xrange () to range (). Thus, the fastest, economic on memories and an elegant method postrochnogo readings of a text file the following:



for s in f.xreadlines ():

do_somenthing (s)


The special method __ rcmp __ is not supported any more. Instead of him{it} it is caused __ cmp __ with the inverted order of operands;


repr (), applied by the line at which are present not - ASCII and control symbols, uses for their conclusion shetnadcaterichnoe, instead of octal performance (at last!);


Support Windows 3.1 is cancelled, DOS and OS/2 and corresponding plaformo-specific catalogues are removed from library.


[1]. Pay attention, that the design import __ future __ is not special - she simply imports quite real module __ future __.py, present in standard library Python (in which, the truth, is present the certain helpful information about opcional`nykh properties).


[2]. There can be a question - why for support of semantics __ future __ to not provide a special keyword instead of an original design of import? But a problem that any new keyword - in itself a powerful source of incompatibility; there is a vicious circle. Besides


[3]. PyErr_Warn () causes for processing the prevention{warning} a code from the module warnings, written on Python. It should be meant, for example, at creation of the "frozen" applications (i.e. monolithic files where all necessary modules on Python are placed as a byte - code in the static data).


[4]. This restriction is completely justified from the point of view of clearness of a code. As attributes of a method actually are established for function, his{its} realizing, the sanction to appropriate{give} directly through a method results attributes in unevident results:



class C:

def a (self): pass


c1 = C ()

c2 = C ()

c1.a.publish = 1

* c2.a.publish now too it is equal 1!!!


And installation of attributes for a untied method too can lead to to ambiguity:



class D (C): pass

class E (C): pass


D.a.publish = 1

* E.a.publish now too it is equal 1!!!


[5]. For types, opredelnnykh in expansions C, the mechanism of the expanded comparison also is determined. Function of the expanded comparison is set in tp_richcompare slot and accepts dopolnitel`noyj the third parameter - an integer signalling on what operation comparison is called.


[6]. For those who does not know - names of functions of comparison are taken from corresponding operators of language FORTRAN (EQ - EQual, equally; NE - Not Equal, not equally, etc.).


[7]. If the attribute __ dict __ is equal to function None, the first giving to any (user) attribute of function will automatically create the dictionary and will place in him{it} attribute.