Python (language)


Python is a programming language object , multi- paradigm and cross-platform . It promotes imperative programming structured , functional and object-oriented . It is equipped with strong dynamic typing , automatic garbage memory management and an exception management system ; It is similar to Perl , Ruby , Scheme , Smalltalk and Tcl .

The Python language is placed under a free license close to the BSD 3 license and runs on most computer platforms, from supercomputers to central computers 4 , from Windows to Unix including GNU / Linux via macOS , and Android , IOS , and also with Java or .NET . It is designed to optimize programmers’ productivity by providing high-level tools and easy-to-use syntax.

It is also appreciated by some educators who find a language where the syntax, clearly separated from mechanisms low level , enables easy introduction to basic programming concepts 5 .

Use

Python is a language that can be used in many contexts and can be adapted to any type of use through specialized libraries. It is, however, particularly used as a scripting language to automate simple but time-consuming tasks, such as a script that would retrieve weather from the Internet or integrate with computer- aided design software to automate repetitive action sequences See the Adoption section ). It is also used as a prototype development language when you need a functional application before optimizing it with a lower level language.

History

At the CWI

Guido van Rossum, creator of Python, at OSCON 2006.

In the late 1980s , the programmer Guido van Rossum participated in the development of the programming language ABC at Centrum Wiskunde & Informatica (CWI) of Amsterdam , the Netherlands . He was working in the team of the operating system Amoeba  (in) whose calls were difficult systems interfaced with the Bourne shell used as a user interface. He believes then that a script language inspired by ABC could be interesting as an ordering interpreter for Amoeba 6 .

In 1989 , taking advantage of a holiday week during the Christmas holidays, he uses his personal computer 7 to write the first version of the language. Fan of the television series Monty Python’s Flying Circus , he decides to baptize this project Python 8 . It was mainly inspired by ABC, for example for indentation as syntax or the high level types but also for Modula-3 for the management of exceptions , the C language and UNIX tools 9 .

During the following year, the language began to be adopted by the Amoeba project team, Guido continuing its development mainly during his free time. In February 1991, the first public version, numbered 0.9.0 10 , is posted on the Usenet alt.sources forum . The latest version released at CWI was Python 1.2.

At the NCRI

In 1995 , Van Rossum continued his work on Python at CNRI  (in) in Reston , the United States , where he released several versions of the software.

From’, The Python team works at NCRI on Grail 11 a web browser using Tk . It is the Python equivalent of the HotJava browser, allowing you to run applets in a secure environment. The first public version, available in November, is 0.2 12 . It has led to the development of modules for the standard library like rexec 13 , htmllib or urllib 14 . Version 0.6 will be the last version of Grail ; It is published in April 1999 15 .

In 1999 , the Computer Programming for Everybody (CP4E) project was launched in collaboration with the NCRI and DARPA . This is to use Python as programming language. This initiative will lead to the creation of the IDLE development environment . However, due to the lack of funding for the project by DARPA and the departure of many Python developers from the NCRI (including Guido van Rossum), the project ended in 2000 16 . Python 1.6 was the latest version released at the NCRI.

To BeOpen

In 2000 , Python’s main development team moved to BeOpen.com to form BeOpen ‘s PythonLabs team . Python 2.0 was the only version released at BeOpen.com. After this version, Guido Van Rossum and the other developers joined Digital Creations PythonLabs (now known as the Zope Corporation ) 17 .

Andrew M. Kuchling published in December 1999 18 a text called Python Warts 19 which summarizes the most frequent complaints against language. This document will have some influence on the future development of language 20 .

The Python Software Foundation

Python 2.1 was a derived version of Python 1.6.1, as well as Python 2.0. His license was renamed Python Software Foundation License . Any code, documentation and specification added since the release of Python 2.1 alpha is owned by the Python Software Foundation (PSF), a nonprofit organization founded in 2001, modeled after the Apache Software Foundation .

In order to repair some language flaws (eg object oriented with two types of classes), and to clean the standard library of its obsolete and redundant elements, Python chose to break backward compatibility in the new major version, Python 3.0 , Released in December 2008. This version was followed quickly by a version 3.1 which corrects the errors of youth version 3.0.

Features

Syntax

Python was designed to be a readable language. It aims to be visually refined. For example, it has fewer syntactic constructs than many structured languages ​​such as C , Perl , or Pascal . Comments are indicated by the cross character (#).

The blocks are identified by the indentation , instead of braces as in C or C ++ ; Or begin ... endas in Pascal or Ruby . An increase in indentation marks the beginning of a block, and a reduction in indentation marks the end of the current block. By convention, the indentation is usually four spaces in Python 21 .

C factorial function Python factorial function
Int factorial ( int n ) {
 if ( n < 2 ) {
 return 1 ;
 } Else {
 return n * factorial ( n - 1 );
 }
}
def factorial ( n ):
 if n < 2 :
 return 1
 else :
 return n * factorial ( n - 1 )

NB: the indentation could be modified or deleted in the C version without modifying its behavior. Similarly, the Python function can be written with a conditional expression 22 . However, a correct indentation makes it easier to detect errors in case of nesting several blocks and thus facilitates the elimination of these errors. This is why it is better to indent suitably the programs in C. The short version would be as follows:

C factorial function Python factorial function
Int factor ( int n ) {
 return n < 2 ? 1 : n * factorial ( n - 1 );
 }
def factorial ( n ):
 return 1 if n < 2 else n * factorial ( n - 1 )

Language Keywords

The keywords are provided in the list keyword.kwlistof module keyword23 . Keyword Python 2.7.5 are: and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield.

From Python 3.0, printand execare no longer keywords of the language, but functions of the module builtins24 . Are added to keywords: True, False, Noneand nonlocal. The first three were present in previous versions, but they are not modifiable (formerly the assignment True = 1possible) 25 . nonlocalHas been introduced by PEP 3104 26 and allows, in a function defined within another function, to modify a variable of a higher level of range . Before that, only the local variables to the function, and global variables (module level) were modifiable. However, it was possible, and it still is without the keyword nonlocal,append

Basic Types

The basic types in Python are relatively comprehensive and powerful, including:

  • The digital objects
    • intIs an unlimited integer. Before version 3.0, this type was named long, and the type intwas a 32- or 64-bit integer. Nevertheless, automatic conversion avoided any overflow.
    • floatIs a float equivalent to doublethe C type , which is a number between -1.7 × 10 308 and 1.7 × 10 308 on the platforms in accordance with the IEEE 754 .
    • complexIs an approximation of a complex number (typically two float).
  • The “iterable” objects
    • Objects tuple( n-tuple ) are immutable lists of heterogeneous objects.
    • Objects listare dynamic arrays (they automatically extend their size when needed) and accept heterogeneous data types.
    • Objects setare unordered sets of objects.
    • The objects frozensetform an immutable variant of the set.
    • Objects dictare associative arrays (or dictionaries) to associate an object (a key) with another.
    • Objects strare strings. Starting with version 3.0, the characters are in Unicode on 16 or 32 bits; The byte strings are objects bytes27 . In previous versions, these objects were of type unicodeand str. Objects strand bytesare immutable .
    • Objects bytearrayare modifiable byte strings. The version of Unicode used by Python can be determined using the unidata_versionmodule variable unicodedata.

The iterable objects are traversed by means of a loop forin the following way:

for element in objet_iterable:
 traiter(element)

Pour une chaîne de caractères, l’itération procède caractère par caractère.

Il est possible de dériver les classes des types de base pour créer ses propres types. On peut également fabriquer ses propres types d’objets itérables sans hériter des itérables de base en utilisant le protocole d’itération du langage.

Programmation fonctionnelle[modifier | modifier le code]

Python allows to program in a functional style . It also features understandings lists , and more generally the understanding can produce generators, dictionaries or sets 28 . For example, to construct the list of squares of natural numbers smaller than 10, we can use the expression:

list = [ x ** 2 for x in ranks ( 10 )]
# list = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The list of even numbers :

List = [ integer for integer in range ( 10 ) if integer % 2 == 0 ]
# list = [0, 2, 4, 6, 8]

A table passing the letters of the alphabet to their ASCII code:

{ Chr ( n ): n for n in range ( 65 , 91 )}

The set of letters of a word (produces the set {'r', 'c', 'd', 'b', 'a'}):

S = "abracadabra"
{ c for c in s }

An understanding can include several loops and filters, and there is a correspondence with the code performing the same calculation using instructions forand if :

Comprehension Equivalent code
[ I + j if i ! = J else 0
 for i in ranks ( n )
 if i % 2 ! = 0
 for j in ranks ( n )
 if j % 3 ! = 0 ]
a = []
for i in ranks ( n ):
 if i % 2 ! = 0 :
 for j in ranks ( n ):
 if j % 3 ! = 0 :
 a . Append ( i + j if i ! = J else 0 )

A limited form of anonymous function is possible:

Lambda x : x + 2

Lambda functions can be defined online and used as arguments in functional expressions:

 Filter ( lambda x : x < 5 , a list )

Will return a list consisting of elements of a list less than 5. The same result can be obtained with

 [ X for x in a_list if x < 5 ]

Python lambdas admit only expressions and can not be used as generalized anonymous functions; But in Python, all functions are objects, so they can be passed into arguments to other functions, and called when necessary. Indeed, a function defined with def can be created within another function and thus a function definition is obtained in a local variable, for example:

def filtre_inferieur_a_5 ( une_liste ):
 def mon_filtre ( x ): # locale mon_filtre
 return x < 5
 return filter ( mon_filtre , une_liste )

A local function can modify the environment of the function that created it, thanks to the keyword nonlocal(see Closing (computer) ):

Def accum ( not ):
 total = 0
 def add ( n ):
 nonlocal total
 total + = n * not
 return total
 return add

It is thus possible to create several accumulators, each referring to its own total. It is possible to access the environment of a local function using the attribute __closure__.

Programming object

All basic types, functions, class instances (the “classical” objects of C ++ and Java) and the classes themselves (which are instances of meta-classes) are objects.

A class is defined with the keyword class. Python classes support multiple inheritance; There is no static overhead as in C ++, or restrictions on inheritance as is the case in Java (a class implements multiple interfaces and inherits from a single class) but the mechanism of optional arguments and Keyword is more general and more flexible. In Python, the attribute of an object can reference an instance or class variable (usually a method). It is possible to read or modify an attribute dynamically with functions:

  • getattr(objet, "nom_attribut")
  • setattr(objet, "nom_attribut", nouvel_attribut)

Example of two simple classes:

Class Person :
 def __init__ ( self , name , first name ):
 self . Name = name
 self . firstname = firstname
 def present ( self ):
 return self . Name + "" + self . first name
Class Student ( Person ):
 def __init__ ( self , level , name , first name ):
 Person . __init__ ( self , name , first name )
 self . Level = level
 def presenter ( self ):
 return self . Level + "" + Person . Presenter ( self )
E = Student ( "INFO License" , "Dupontel" , "Albert" )
assert e . Name == "Dupontel"

Special Methods and Definition of Operators

Python provides an elegant, object-oriented mechanism for defining a predefined set of operators: any Python object can be endowed with so-called special methods.

These methods, starting and ending with two underscores , are called when using an operator on the object: +(method __add__), +=(method __iadd__), [](method __getitem__), ()(method __call__), and so on. Methods like __repr__and __str__allow to define the representation of an object in the interactive interpreter and its rendering with the function print .

The possibilities are numerous and are described in the documentation of the language 29 .

For example, the addition of two two-dimensional vectors can be defined with the following class:

Class Vector2D :
 def __init__ ( self , x , y ):
 # A tuple is used to store the
 self coordinates . Coords = ( x , y )
 def __add__ ( self , --other ):
 # + b The instruction will be resolved as a .__ add __ (b)
 # We built a Vector2D object from the own contact with the object, and the other operand
 return Vector2D ( self . coords [ 0 ] + --other . coords [ 0 ] self . coords [ 1 ] + --other . coords [ 1 ])
 def __repr__ ( self ):
 # The display of the object in the interpreter
 return "Vector2D ( % s , % s )" % self . Coords
a = Vector2D ( 1 , 2 )
b = Vector2D ( 3 , 4 )
print ( a + b ) # Vector2D (4, 6)

Generators

The keyword yieldused in a function makes this function a generator. Calling this function returns an object of type generator , which can be used in a loop for, for example.

At each call, the generator performs its processing until it encounters the keyword yield, returns the value of the expression yield, and at the next call, resumes its operation just after the call yield. For example, to calculate the Fibonacci sequence , we can write:

def gen_fibonacci ():
 "" "Generator Fibonacci" ""
 a , b = 0 , 1
 while True :
 yield a # Returns the value of "a" result of the current iteration
 is , b = b , A + b
Fi = gen_fibonacci ()
for i in range ( 20 ):
 print ( next ( fi ))

The module itertoolsallows manipulation of the generators. For example, to extract the first 10 elements of the previous generator:

import itertools
list ( itertools . iSlice ( gen_fibonacci (), 10 ))
# returns [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Since Python 3.3, it is possible to produce a generator from a recursive function, with syntax yield from, appeared in PEP 380 30 and “delegates” to calculate a sub-generator. The following example calculates the permutations of the ladies corresponding to the solutions of the problem of the eight ladies extended to a chessboard of size n × n.

def queens ( n ):
 a = list ( Range ( n ))
 up = [ True ] * ( 2 * n - 1 )
 down = [ True ] * ( 2 * n - 1 )
 def sub ( i )
 for k in Range ( i , n ):
 j = a [ k ]
 p = i + j
 q = i - j + n - 1
 yew up [ p ] and down [ q ]:
 if i == n - 1 :
 yield tuple ( a )
 else :
 up [ p ] = Down [ q ] = False
 a [ i ], a [ k ] = a [ k ], a [ i ]
 yield from sub ( i + 1 )
 up [ p ] = Down [ q ] = True
 has [ i ], a [ k ] = a [ k ], a [ I ]
 yield from sub ( 0 )a [ i ] yield from sub ( i + 1 ) up [ p ] = Down [ q ] = True has [ i ], a [ k ] = a [ k ], a [ i ] yield from sub ( 0 )a [ i ] yield from sub ( i + 1 ) up [ p ] = Down [ q ] = True has [ i ], a [ k ] = a [ k ], a [ i ] yield from sub ( 0 )A [ i ] yield from sub ( 0 )A [ i ] yield from sub ( 0 )A [ i ] yield from sub ( 0 )A [ i ] yield from sub ( 0 )A [ i ] yield from sub ( 0 )A [ i ] yield from sub ( 0 )
Sum ( 1 for a in queens ( 8 )) # Number of solutions, returns 92

A generator may look like a function that returns a list, but unlike a list that contains all of its elements, a builder calculates its elements one by one .
Thus, the test 36 in [n * n for n in range(10)]will be done on the list calculated in full, while in 36 in (n * n for n in range(10)), which uses a generator, the calculation of the squares stops as soon as 36 is found. One can be convinced by replacing it n * nwith a function call carrying out an edge effect , for example an on-screen display.

Reflexivity

Thanks to the intensive use of dictionaries (an associative container developed with hash tables ), Python allows to explore the various objects of the language ( introspection ) and in some cases to modify them ( intercession ).

Typing

The typing is not checked at compile time. Python uses the typing duck : at runtime, if a method invoked on an object has the same signature as a declared method on that object, then this method is executed. Therefore, invoking a method that does not exist on an object will fail, meaning that the object in question is not the right type. Despite the absence of static typing, Python is strongly typed, forbidding operations with little meaning (such as adding a number to a string) instead of silently trying to convert it into a form that makes sense . Python provides functions for transforming variables into another type:

Points = 3.2 # points is of type float
print ( "Tu as" + points + "points!" ) # Generates a typing error
Points = int ( point ) # point now of type int (integer), the value is rounded to the nearest unit (here 3)
print ( "You" + point + "points!" ) # Generate a typing error
Points = str ( points ) # points is now of type str (string)
print ( "You have" + points + "points!" ) # More typing error, displays 'You have 3 points!'

Similarly, each variable must be declared before being used.

Python also offers a strong typing mechanism thanks to the API trait 31 or the design pattern decorators .

Compilation

It is possible to perform a static analysis of Python modules with tools like Pylint 32 or PyChecker. Without requiring an execution, these tools detect faults or constructions deprecated. For example, a class that inherits from an abstract class and does not redefine abstract methods, or variables used before being declared, or instance attributes declared outside of the method __init__.

It is also possible to generate a Python bytecode .

Tools such as PyInstaller 33 or other more specific like cx_Freeze under Unix , Windows and MacOS , py2app 34 under macOS and py2exe under Windows allow to “compile” a Python program in the form of an executable comprising the program and a Python interpreter.

The program does not run faster (it is not compiled in the form of machine code) but it simplifies its distribution widely, especially on machines where the Python interpreter is not installed.

Object Model

En Python, tout est objet, dans le sens qu’une variable peut contenir une référence vers tous les éléments manipulés par le langage : nombres, méthodes, modules, etc.35. Néanmoins, avant la version 2.2, les classes et les instances de classes étaient un type d’objet particulier, ce qui signifiait qu’il était par exemple impossible de dériver sa propre sous-classe de l’objet list.

Méthodes[modifier | modifier le code]

Le modèle objet de Python est inspiré de celui de Modula-336. Parmi ces emprunts se trouve l’obligation de déclarer l’instance de l’objet courant, conventionnellement nommée self, comme premier argument des méthodes, et à chaque fois que l’on souhaite accéder à une donnée de cette instance dans le corps de cette méthode. Cette pratique n’est pas naturelle pour des programmeurs venant par exemple de C++ ou Java, la profusion des self étant souvent critiquée comme étant une pollution visuelle qui gène la lecture du code. Les promoteurs du self explicite estiment au contraire qu’il évite le recours à des conventions de nommage pour les données membres et qu’il simplifie des tâches comme l’appel à une méthode de la superclasse ou la résolution d’homonymie entre données membres37.

Python recognizes three types of methods:

  • The instance methods, which are the default methods. They receive as the first argument an instance of the class where they were defined.
  • The class methods, which receive as the first argument the class where they were defined. They can be called from an instance or directly from the class. They allow the definition of alternative constructors such as the fromkeys()object method dict. They are declared with the decorator @classmethod.
  • Static methods, which do not receive a first implicit argument. They are similar to the static methods found in Java or C ++. They are declared with the decorator @staticmethod.

Visibility

The language has a very limited support for encapsulation . There is not, as in Java for example, control of accessibility by key words like protectedor private.

Python’s philosophy is to conceptually differentiate encapsulation from information masking. Information masking is intended to prevent fraudulent use, it is a computer security concern . The bastion module of the standard library, which is no longer maintained in the latest versions of the language, allowed to control the access to the attributes of an object in the context of a restricted execution environment.

Encapsulation is a software development issue. The Python developer slogan is we’re all consenting adults here 38 (we are between consenting adults). They consider that it is enough to indicate, by writing conventions, the public parts of the interfaces and that it is the users of the objects to comply with these conventions or to assume their responsibilities. The usage is to prefix by an underscore private members. The language also allows to use a double underscore to avoid collisions of names, automatically prefixing the name of the data with that of the class where it is defined.

The use of the function property()makes it possible to define properties which are intended to intercept, by means of methods, the accesses to a data item. This makes it unnecessary to systematically define accessors and hide data as is common in C ++ for example.

Inheritance

Python supports multiple inheritance . Since version 2.3, it uses the algorithm C3  (en) , derived from the Dylan 39 language , to solve the order of method resolution ( MRO ). Previous versions used a deep traversal algorithm that caused problems in the case of an inheritance diamond 40 .

Standard library

Python is provided “batteries included”.

Python has a large standard library , providing tools suitable for many different tasks. The number of modules in the standard library can be increased with specific modules written in C or Python.

The standard library is particularly well suited for writing applications using the Internet, with a large number of standard formats and protocols (such as MIME and HTTP ). Modules for creating graphical interfaces and handling regular expressions are also provided. Python also includes a framework for unit testing ( unittestformerly PyUnit before version 2.1) to create suites of comprehensive tests.

Style Conventions

Although each programmer can adopt his own conventions for writing Python code, Guido van Rossum has put a guide available, referenced as “PEP 8” 21 . Published in 2001, it is always maintained to adapt it to the evolutions of language. Google also offers a guide 41 .

Graphical Interfaces

Python has several modules available for creating software with a graphical interface. The most widespread is Tkinter . This module is suitable for many applications and can be considered sufficient in most cases. However, other modules have been created in order to link Python to other software libraries (” toolkit “), for more functionalities, for better integration with the operating system used, or simply to be able to use Python with its Library. Indeed, some programmers find the use of Tkinter more painful than other libraries. These other modules are not part of the standard library and must therefore be obtained separately.

The main modules giving access to the GUI libraries are Tkinter and Pmw (Python megawidgets) 42 for Tk , wxPython for wxWidgets , PyGTK for GTK + , PyQt and PySide for Qt , and finally FxPy for the FOX Toolkit . There is also an adaptation of the SDL library : Pygame , a binding of the SFML : PySFML, as well as a library written specifically for Python: Pyglet  (en) .

It is also possible to create Silverlight applications in Python on the IronPython platform .

The Python Community

Guido van Rossum is the principal author of Python, and his role as Python’s permanent central decision-maker is humorously acknowledged as the Benevolent Dictator for Life ( BDFL).

It is assisted by a team of core developers who have write access to the CPython repository and who coordinate on the python-dev mailing list. They mainly work on the language and the basic library. They receive punctual contributions from other Python developers via the Roundup bug management platform , which replaced SourceForge .

Third-party users or developers use a variety of other resources. The main generalist media around Python is the English Usenet forum comp.lang.python.

The allusions to the Monty Pythons are quite frequent. Python tutorials often use spam and eggs as the metasyntactic variable . This is a reference to the Monty Python Spam Sketch , where two customers try to order a meal using a card that contains SPAM brand canned ham in virtually every dish. This sketch was also taken as a reference for an unsolicited e-mail .

Adoption of Python

Several companies or organizations mention on their official website 43 that they use Python:

  • Google ( Guido van Rossum worked in this company between 2005 and 2012 44 );
  • Industrial Light & Magic ;
  • the NASA ;
  • And CCP Games, the creators of the video game EVE Online .

Python is also the command language of a large number of free software:

  • FreeCAD , 3D CAD software
  • Blender , 3D modeling and video editing software
  • Inkscape , vector drawing software
  • LibreOffice and Apache OpenOffice , the two branches of development of an office suite from StarOffice
  • Portage , the Gentoo Operating System Package Manager
  • ParaView , digital data visualization software
  • Kodi , a multimedia player
  • QGIS , a mapping software
  • Weblate , a translation tool

And commercial:

  • Wing IDE , an integrated development environment specialized on Python, and written in Python
  • Corel Paint Shop Pro , image editing and graphics editing software
  • Capella , music notation software
  • ArcGIS , a mapping software 45
  • Visual Studio 46

Python is used as the programming language in elementary and higher education, particularly in France 47 . Since 2013, he is taught at the same time as Scilab , to all students of scientific preparatory classes within the framework of the common core (computer for all). Previously, computer education was limited to an MP option, and was done in Caml or Pascal language . The first competition exams on the Python language are those of the 2015 session 48 , 49 .

Language Implementations

In addition to the reference version, called CPython (as written in language C ), there are other systems implementing Python 50 :

  • Stackless Python , a version of CPython that does not use the C language call stack;
  • Jython , a Python interpreter for Java virtual machine . It has access to the libraries provided with the Java development environment ;
  • IronPython , an interpreter / compiler (experimental) for .Net / Mono platform ;
  • Brython, an implementation of Python 3 for web browsers
  • PyPy a Python interpreter written in a subset of Python compilable to C or LLVM ;
  • a compiler (experimental) for Parrot , the virtual machine for Perl 6;
  • Shed Skin (in) 51 , a compiler of a subset of Python producing code in C ++ ;
  • Unladen Swallow (in) 52 , a version of CPython and optimized based on LLVM, now abandoned (the latest was in October 2009).

These other versions do not necessarily benefit from the entire library of functions written in C for the reference version, nor the latest evolutions of the language.

Distributions of Python

Different distributions are available, which sometimes include many packages dedicated to a given domain 53 :

  • ActivePython 54 : available as a free version (can not be “used in production”) or commercial.
  • Python (x, y) 55 : Python distribution for use by scientists based on Qt and Eclipse .
  • Enthought Canopy 56 : distribution for scientific use, available in free version (Canopy Express) or commercial.
  • Anaconda 57 : distribution for scientific use, available in free or commercial version.
  • Intel Distribution for Python 58 : Anaconda-based distribution, including in particular the library MKL (in) Intel to accelerate the numerical calculations of libraries like NumPy and SciPy , integrated distribution. It is only available for free, or integrated with Intel Parallel Studio (in) , which requires a paid license.
  • Pyzo 59 : ” Python to the people “, intended to be easy to use.

These are not different implementations of the Python language: they are based on CPython, but are delivered with a number of preinstalled libraries.

Version history

Version Release date What’s New 60
1.5 (.2)
  • Adding the keyword assert
  • Ability to import a module hierarchy (import spam.ham.eggs)
  • New re module that replaces regex
  • Exceptions are now classes
  • Added the -O option that removes assertions and file line information
1.6
  • The append()list method accepts only one argument
  • The result of functions str()and repr()is now much more often different, example:str(1L)=='1' et repr(1L)=='1L'
  • Strings now have methods ( " abc ".strip())
  • The module reis compatible with the old engine, is faster, and accepts Unicode strings
  • Adding the distutils module
  • New prototype def f(*args, **kw)for functions, before it was necessary to useapply()
  • int()And long()now accept a second argument basis
  • The in operator can be overloaded with a method __contains__()
2.0
  • Major change: Unicode support
  • Add list comprehensions ( List Comprehensions )
  • Adding operators with assignment ( a+=b, a*=b, etc.)
  • Str strings now have methods
  • New garbage collection cycles
  • Adding modules distutils, xml.dom.minidomandxml.sax
2.1
  • Creating the module __future__to make transitions softer
  • Rich comparisons (methods __lt__, __le__…)
  • Warning Framework
  • Add inspect , pydoc , doctest , pyunit modules
  • Adding weak references ( weak references )
  • Functions can have attributes
  • Nested Scopes
  • Version 2.0.1 () Will be the first GPL- compliant version
2.2
  • Unification of Type and Class: we can now inherit the basic types
  • Adding Iterators and Generators
  • New operator a // b for the entire division
2.3
  • Adding the enumerate () and sum () functions
  • The bool type is now really distinct from an integer
  • Many improvements to Unicode support
2.4
  • Added function / method decorators (@decorator)
  • Automatically converts a short integer to a long integer if the result of an operation is too large
  • Generator expressions returning the results one after the other and not in the form of a list, example: sum( x for x in xrange(10000) )
  • Adding functions reversed()andsorted()
  • The sort function sort()accepts keywords cmp, key, and reverse
  • Creating the decimal module and the router
2.5
  • Adding the with statement
  • Added send (), throw () and close () methods to the generators
  • Conditional expression ( a if test else b)
  • Module imports can be relative
  • Added partition () and rpartition () methods to str and unicode strings
  • Adding any () and all ()
  • Integration of libraries ctypes, ElementTree, hashlib, sqlite3 and wsgiref
2.6
  • New string formatting syntax
  • Basic abstract classes
  • Classroom Decorators
  • JSON modules , multiprocessing, contextmanager and fractions
  • Improved compatibility with Python 3
2.7
  • Syntax for literals: {1, 2, 3}instead ofset((1, 2, 3))
  • Comprehension of dictionary and set, examples: {i: i*2 for i in range(3)}(dictionary) and {i*2 for i in range(3)}(together)
  • Ability to specify multiple context handlers with a single declaration with
  • Reimplementation of the io library (inputs / outputs) in C for better performance. This library is especially useful for accessing a text file in Unicode.
  • Dictionaries ordered as described in PEP 372: from collections import OrderedDict
  • The format method manages automatic numbering: '{} {}!'.format('Hello', 'World')give ‘Hello World’!
  • Formatting numbers handles thousands separators, for example: '{:,}'.format(10800)gives ’10, 800 ‘
  • Improved accuracy when converting to floating and floating to string. For a float, float (repr (x)) will always give x.
  • New argparse module to parse the command line: improved version of the optparse module
  • Dictionary-based configuration for the logging module
  • Memoryview objects: read-only view or read-write of a binary object (API similar to that of type bytes)
  • Type PyCapsule for PLC C (for expansion modules)
  • The int and long types gain a method bit_length (): number of bits needed to represent the absolute value of the number
3.0 61
  • Fusion of types ‘int’ and ‘long’
  • Strings are in Unicode by default, ‘bytes’ replaces the old type ‘str’
  • Uses iterators instead of lists where appropriate (eg dict.keys())
  • a/b Is the default real division
  • Exec and print become functions
  • None, TrueAnd Falsebecome keywords
  • The file __init__.pyis no longer needed for Python modules
  • `x`And the operator <>disappear
  • Many functions disappear: apply(), buffer(), callable()
  • reduce() Disappears in favor of explicit loops

See PEP 3100  [ archive ] for details

3.1 62
  • Added an ordered dictionary type,
  • Various optimizations made to the ‘int’ type,
  • New features of the module ‘unittest’
  • Input / output module ‘io’ made faster,
  • Integration of the import statement into pure Python
  • New syntax for nested ‘with’ statements.
3.2 63
  • Adding the argparse module for parsing arguments passed to a program
  • Changing the management of compiled .pyc files
  • Adding certificates (HTTPS protocol)
  • Improvement of the pickle module
  • Reintroduction of function callable()(removed in 3.0)
3.3 64
  • Adding syntax yield from​to use sub-generators 64
  • Syntax u’unicode ‘is accepted again 65
  • Added faulthandler module to help debug low-level issues
  • Support for LZMA compression
  • Adding a module for Mock in unittest
  • Incorporating virtualenv module features with the venv module
  • Rebuild the system error hierarchy (I / O).
3.4 66
  • Addition of asynchronous module for asynchronous programming 67
3.5 68
  • New operator for the matrices: a @ b​69
  • Added syntax await​
3.6 70
  • Possibility of writing large numbers in the form: 1_000_000​71 .
  • Addition of the module secret​to simplify the generation of pseudo-random numbers of cryptographic quality 72 .
  • New string formatting 73 :
    >>> var = 50
    >>> print ( f 'On {var}' )
    We display 50
    

Development

The PEP

Python Enhancement Proposal (PEP: Python Enhancement Proposal ) are text documents that are intended to be the way of improving Python and precede all amendments 74 . A PEP is a proposal for guidance for development (PEP process) , a technical proposal (Standard Track PEP) or a simple recommendation ( Informational PEP ).

Python 3000

A new version of Python, called Python 3.0 (the project was called “Python 3000” or “Py3K”) abolishes backwards compatibility with the 2.x version series, in order to eliminate language weaknesses. The project’s policy was to “reduce redundancy in Python’s operation by removing obsolete methods”. Python 3.0a1, the first alpha version was published August 31, 2007 75 , and there is a PEP 76 detailing the planned changes, and a page to guide programmers in their choice of Python 2 or 3 77 .

Philosophy

Python 3.0 has been developed with the same philosophy as in its earlier versions, so any reference to the Python philosophy will apply as well to version 3.0. As always, Python has accumulated a lot of new methods that actually make redundancy with other preexisting ones. Python 3.0, looking for deletion of redundant code and similar modules, follows Python’s great philosophical guideline: “There should be only one method that is both optimal and natural for every thing.”

In spite of this, Python 3.0 will remain a multi-paradigm language. Programmers will still have the choice between object orientation, structured programming, functional programming and other paradigms; In spite of the existing choice, Python 3.0 is however intended to be used more naturally than in versions 2.x.

Planning and Compatibility

Python 3.0a1, the first alpha version of Python 3.0, was released on August 31, 2007. Python versions 2.x and 3.x will be released in parallel during several development cycles, during which the 2.x series will continue Mainly for compatibility, including some features imported from Python 3.x. The PEP 3000 78 contains more information about the release process of a version.

Like Perl 6 , Python 3.0 breaks down compatibility (backwards compatibility). The use of written code for the 2.x series is not guaranteed with Python 3.0. The latter brings fundamental changes, such as the generalized switch to Unicode for strings and a strong distinction between strings and “bytes” objects. Dynamic typing associated with certain methods on dictionary objects makes a perfect transition from Python 2.x to Python 3.0 very difficult. As always, a tool named “2to3” performs most of the translation work from version 2.x to version 3.x, indicating the code areas that are subject to caution with special comments and warnings. Moreover, in its pre-version, 2to3 frankly seems to succeed to achieve a correct translation 79 . As part of a migration to Python 2.x to Python 3.x, PEP 3000 recommends keeping the original code base as modifications and the result for the 3.x platform using 2to3.

Python 2.6 will provide backward compatibility features, as well as a “warning” mode which should raise awareness of the potential transition issues for the transition to Python 3.0 80 .

Python for smartphones

There are versions of Python adapted for Android and iPhone in version 2.5 or 2.6. Available in Jailbreak of iOS on iOS thanks to “setup tools”, and on Android thanks to SL4A which even gives a possibility to make small graphical interfaces thanks to the module “android” which allows to send SMS , The camera 81 , or else to vibrate the telephone. The following few lines show how to do this:

Droid = android . Android () # client linked to local server launched by SL4A application
 # to control a remote phone at address 192.168.0.5, with SL4A running on port 9887
 # just do it: android.Android ('192.168.0.5 ', 9887)
Droid . Vibrate ( 2.5 ) # vibrates the phone (local or remote) for 2.5 seconds

A Python port on the Blackberry devices came out, For the BlackBerry OS 10 system 82 . A lighter version was released in September 2012, called “BlackBerry-Tart” 83 , 84 , because of a pun in English, ” a” tart “is lighter-weight than a” pie “ ,” in reference to the Traditional ” apple pie “. It is based on Python 3.2.2.

Notes and references

  1. ↑ https://www.python.org/downloads/release/python-360/  [ archive ]
  2. ↑ https://www.python.org/downloads/release/python-2713/  [ archive ]
  3. ↑ ( en ) ” Python License [ archive ]
  4. ↑ Download Python for Other Platforms  [ archive ]
  5. ↑ ( en ) “it takes thirteen paragraphs to explain a Hello, World! In C ++, only two in Python “ [ archive ]
  6. FAQ Python 1.2 Why was Python created in the first place?  [ Archive ]
  7. Introduction to MacPython [ archive ]
  8. ↑ Foreword for “Programming Python” (1st ed.)  [ Archive ]
  9. ↑ Introduction of the first edition of the book Programming Python by Mark Lutz  [ archive ] , Guido van Rossum 1996
  10. ↑ According to the HISTORY file  [ archive ] but the oldest version available in the forum archive is 0.9.1  [ archive ] , also available in tarball on python.org  [ archive ]
  11. ↑ The Grail Development Team  [ archive ]
  12. Grail – The Browser For The Rest Of Us [ archive ]
  13. ↑ 28.1 rexec – Restricted execution framework [ archive ]
  14. ↑ http://grail.sourceforge.net/info/diagram.gif  [ archive ]
  15. ↑ Grail Home Page  [ archive ]
  16. ↑ Computer Programming for Everybody  [ archive ]
  17. ↑ ( in ) History of the software  [ archive ]
  18. ↑ Andrew M. Kuchling, Python warts  [ archive ] , Python Mailing List, December 22, 1999
  19. ↑ Python Warts
  20. ↑ Unifying Types and Classes in Python 2.2  [ archive ]
  21. a and b PEP 8 – Style Guide for Python Code  [ archive ]
  22. ↑ PEP 308 – Conditional Expressions  [ archive ]
  23. ↑ The Python Standard Library – 31.6. Keyword – Testing for Python keywords  [ archive ]
  24. ↑ The Python Standard Library – 2. Built-in Functions  [ archive ]
  25. ↑ ( en ) ” Python 3.0 – Core Language Changes [ archive ]
  26. ↑ ( en ) ” PEP 3104 – Access to Names in Outer Scopes [ archive ]
  27. ↑ The objects byteswere introduced by the PEP 358  [ archive ] , see also PEP 3137 [ archive ]
  28. ↑ The understandings were introduced in the PEP 202  [ archive ] in July 2000, and the comprehension of dictionaries and sets in the PEP 274  [ archive ] in October 2001
  29. ↑ The Python Language Reference »3. Data model» 3.3. Special method names  [ archive ]
  30. ↑ PEP 380 – Syntax for Delegating to a Subgenerator  [ archive ]
  31. ↑ traits – explicitly typed attributes for Python  [ archive ]
  32. ↑ http://www.pylint.org  [ archive ]
  33. ↑ ( in ) official website PyInstaller  [ archive ]
  34. ↑ http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html#abstract  [ archive ]
  35. ↑ Dive into Python 3 – 1.5 Everything Is An Object  [ archive ]
  36. Python Tutorial [ archive ] chapter 9
  37. ↑ Why should ‘self’ be used explicitly in definitions and calls?  [ Archive ]
  38. ↑ Python For AppleScripters  [ archive ]
  39. ↑ Kim Barrett, Bob Cassels, Paul Haahr, David A. Moon, Keith Playford and P. Tucker Withington, ” A superclass monotonic linearization for Dylan ,” ACM SIGPLAN Records , vol.  31, n o 10,, P.  69-82 ( DOI  10.1145 / 236337.236343 , read online  [Archive ] )
  40. ↑ The Python 2.3 Method Resolution Order  [ archive ]
  41. ↑ Google Python Style Guide  [ archive ]
  42. ↑ Pmw – Python megawidgets  [ archive ]
  43. ↑ Quotes about Python  [ archive ]
  44. Python Creator Guido van Rossum now working at Google [ Archive ] , article on ONLamp.com
  45. ↑ Python for ArcGIS  [ archive ]
  46. ↑ Visual Studio 2015 – Getting Started with Python  [ archive ] on MSDN
  47. Special Official Bulletin n o 3 of 30 May 2013 [ archive ] , article http://www.education.gouv.fr/  [ archive ]
  48. ↑ Mines-Ponts Contest Topics  [ archive ]
  49. ↑ Topics of the Centrale-Supélec competition  [ archive ]
  50. ↑ Python Implementations  [ archive ] , in Python Wiki
  51. ↑ Shed Skin  [ archive ]
  52. ↑ Unladen Swallow  [ archive ]
  53. ↑ Python Distributions  [ archive ] , in the Python Wiki
  54. ↑ ActivePython  [ archive ]
  55. ↑ Python (x, y)  [ archive ]
  56. ↑ Enthought  [ archive ]
  57. ↑ Anaconda  [ archive ]
  58. ↑ Intel Distribution for Python  [ archive ]
  59. ↑ Pyzo  [ archive ]
  60. ↑ ( in ) What’s New in Python  [ archive ] on python.org
  61. ↑ Python 3.0 http://www.python.org/download/releases/3.0/  [ archive ]
  62. ↑ Python 3.1 http://www.python.org/download/releases/3.1/  [ archive ]
  63. ↑ Python 3.2 http://www.python.org/download/releases/3.2/  [ archive ]
  64. a and b Python 3.3 http://www.python.org/download/releases/3.3.0/  [ archive ]
  65. ↑ http://www.python.org/dev/peps/pep-0380/  [ archive ]
  66. ↑ ” Python 3.4 [ archive ]
  67. ↑ ” What’s New In Python 3.4 – Python 3.4.5 documentation »  [ archive ] , on docs.python.org (accessed 2 February 2017 )
  68. ↑ ” Python 3.5 [ archive ]
  69. ↑ ” What’s New In Python 3.5 – Python 3.5.3 documentation [ archive ] , on docs.python.org (accessed February 2, 2017 )
  70. ↑ Python 3.6.0  [ archive ]
  71. ↑ PEP 515 – Underscores in Numeric Literals  [ archive ]
  72. ↑ PEP 506 – Adding A Secrets Module To The Standard Library  [ archive ]
  73. ↑ PEP 498 – Literal String Interpolation  [ archive ]
  74. ↑ Index of Python Enhancement Proposals  [ archive ]
  75. ↑ Python 3.0a3 Release  [ archive ]
  76. ↑ Python 3000  [ archive ]
  77. ↑ Should I use Python 2 or Python 3 development for my activity?  [ Archive ]
  78. ↑ Development Plan PEP 3000  [ archive ]
  79. ↑ Sam Ruby, 2to3  [ archive ] , 1 st September 2007
  80. ↑ PEP 361  [ archive ]
  81. ↑ http://code.google.com/p/android-scripting/  [ archive ]
  82. ↑ BlackBerry-Py Project  [ archive ]
  83. ↑ blackberry-py  [ archive ] on Bitbucket
  84. ↑ BlackBerry-Tart Preview  [ archive ]