Python 3.x is the current branch with active development. Python 2.x is still maintained, but without adding new features.
This is a summary of major new features in recent Python versions (thousands of bug fixes, small and parser/C API/internals/performance enhancements are not mentioned):
- Python 3.x
- Python 3.6 · What’s New In Python 3.6
- currently (2015-08-07) in beta phase
- 3.6.0a0 released 2015-10-20
- 3.6.0b4 released 2016-11-07
- f-strings:
x = "world"; y = 42; print(f"Hello {x}, {y}") - underscores in numbers:
10_000_000 __fspath__protocol for pathlib- new module
secrets - local time disambiguation:
datetime(..., fold=1) - development moving to Github
- currently (2015-08-07) in beta phase
- Python 3.5 · What’s New In Python 3.5
- 3.5.0 released 2015-09-13
math.isclose(),cmath.isclose()for approximate equality test- removed
.pyofiles - new matrix multiplication operator:
a @ b - coroutines with
asyncandawaitsyntax - additional unpacking generalizations:
[1, *(2, 3)] == [1, 2, 3] - added
%formatting tobyteandbytearray(not juststr) - new methods
bytes.hex(),bytearray.hex()andmemoryview.hex() - new
subprocess.run() - new modules:
typing- type hintszipapp- improving Python ZIP application support
- SSLv3 is disabled
- automatic retry of system calls failed with EINTR
- performance optimizations:
collections.OrderedDict,os.scandir(),functools.lru_cache()
- Python 3.4 · What’s New In Python 3.4
- 3.4.0 released 2014-03-16
- C files preprocessor "Argument Clinic"
pipcommand should always be available- newly created file descriptors non-inheritable
- new modules:
asynciofor asynchronous I/O- deprecates
asyncoreandasynchat
- deprecates
ensurepipenumpathlibwithPathobject for nice path abstractionselectorsfor I/O multiplexingstatisticstracemalloc
- Python 3.3 · What’s New In Python 3.3
yield fromfor generator delegationu'unicode'syntax is accepted again forstrobjectsvenvfor virtual environments- new modules:
faulthandleripaddresslzmaunittest.mockvenv
- Python 3.2 · What’s New In Python 3.2
- stable ABI
loggingdictionary-based configuration.pycfiles stored in__pycache__directory- WSGI v1.0.1, PEP 3333
- new modules:
argparsefor command line parsingconcurrent.futures
- Python 3.1 · What’s New In Python 3.1
collections.OrderedDict- format specifier for thousands separator:
format(1234567.89, ',.2f') -> '1,234,567.89' - directories and zip archives containing a
__main__.pyfile can now be executed directly by passing their name to the interpreter - fields in
format()strings can now be automatically numbered:'Sir {} of {}'.format('Gallahad', 'Camelot')- formerly, the string would have required numbered fields such as:
'Sir {0} of {1}'
- formerly, the string would have required numbered fields such as:
withstatement now allows multiple context managers in a single statement:with open('mylog.txt') as infile, open('a.out', 'w') as outfile: ...
- Python 3.0 · What’s New In Python 3.0
- also known as "Python 3000" or "Py3K"
- first ever intentionally backwards incompatible Python release
- (some of 3.0 features are already present in Python 2.6)
printis a function<int>/<int>returns float; use<int>//<int>for integer division- no
long, onlyint(even big numbers) dict.keys(),dict.values(),dict.items()return "views" instead of listsdict.iterkeys(),dict.itervalues(),dict.iteritems()gone
range()returns a special object instead of list,xrange() gonesorted()andlist.sort()no longer acceptscmpagument, usekeyinstead- Text vs bytes:
stris the newunicodeb'...'for binary data,'foo'for stringsstrandbytesobjects cannot be mixed (likeunicodeandstrin 2.x)bytesis immutable,bytearrayis mutable
nonlocalkeyword- unpacking:
a, b, *rest = some_sequence - dictionary compehensions:
{k: v for k, v in stuff} - set literals:
{1, 2, 3} - set comprehensions
except Exception, varforbidden (useexcept Exception as var)True,FalseandNoneare reserved keywords- metaclasses and
__metaclass__ - ellipsis:
...can be used anywhere, not only in slices super()- old-style classes gone, all classes are new-style
raw_input()renamed toinput()reload()removed, useimp.reload()- some modules renamed or restructured
- "It is not recommended to try to write source code that runs unchanged under both Python 2.6 and 3.0" - this opinion changed in later 3.x versions :) It was expected to use the tool
2to3. - BTW. most problems with porting from 2.x to 3.x were unicode/str/bytes related, for example in case of WSGI
- Python 3.6 · What’s New In Python 3.6
- Python 2.x
- Python 2.7 · released 2010-07-03 · What’s New in Python 2.7
- last of the 2.x releases, with long-term support
- Python 3.1 features backported to 2.7:
- set literals:
{1, 2, 3} - dictionary and set comprehensions:
{i: i*2 for i in range(3)} multiple context managers in a singlewith` statementiolibrary rewritten in C for performancememoryviewobject- subset of
importlib
- set literals:
collections.OrderedDict,collections.Counterlogging: dictionary-based configurationdictviewsviewskeys(),viewvalues()andviewitems()PYTHONWARNINGSenv variablesubprocess.check_output()weakref.WeakSet- new modules:
argparsesysconfigfrom Distutils
- Python 2.6 · released 2008-10-01 · What’s New in Python 2.6
- prepares the migration path to Python 3.0
- backported from 3.0:
__complex__()magic method for converting objects to a complex number- alternative syntax:
except Exception as e
- command-line switch
-3enables warnings about features removed in Python 3 - Python development process:
- new issue tracker Roundup
- Sphinx and reStructuredText
str.format():'user: {0} {desc}'.format('foo', name='bar')printas function (optional)bytes,bytearrayfrom __future__ import unicode_literals- octal and binary integer literals:
0o21,0b1011 - class decorators
collections.namedtuple(typename, fieldnames)- new packages:
abc- abstract base classesast- Abstract Syntax Tree representation of Python codefractionsiojsonmultiprocessingplistlibfor parsing Mac OS X.plistfilesssl
- deprecated modules:
md5setssha
- Python 2.5 · released 2006-09-19 · What’s New in Python 2.5
- conditional expressions:
x = 'foo' if something else 'bar' withstatement:with open('/etc/passwd') as f: print f.read()- context management protocol - new magic methods:
__enter__()__exit__(exc_type, exc_value, traceback)
- context management protocol - new magic methods:
- absolute and relative imports:
from .foo import bar - unified
try/except/else/finally - generator enhancements
yieldis now expression and returns value- new
GeneratorExitexception
- new
__index__()magic (special) method - new built-in functions:
any(),all() - new modules:
cProfilecontextlibctypesfor calling C functions from Pythonfunctoolshashlibmsilibfor creating Microsoft Installer.msiand CAB filesspwdfor accessing shadow password databasesqlite3- SQLite databaseuuidfor creating universally unique identifiers (UUIDs)wsgirefxml.etree
- conditional expressions:
- Python 2.4 · released 2005-03-30 (2.4.1) · What’s New in Python 2.4
- function and method decorators:
@classmethod,@propertyetc. - generator expressions:
(item for item in items if item.good()) - built-in set objects
set()andfrozenset() string.Templatereversed()Noneis a constant, cannot be assigned a new value- new modules:
collectionscookielibdecimalwithDecimaldata typesubprocess
- function and method decorators:
- Python 2.3 · released 2003-07-29 · What’s New in Python 2.3
- source code encoding header:
# -*- coding: UTF-8 -*- - importing modules from ZIP archives
- universal newline support
enumerate()True,False- extended slices:
L = range(10); L[::2] - new built-in function
sum(iterable, start=0) assertstatement no longer checks the__debug__flag- new types in
datetimemodule:date,timeanddatetime - new modules and packages:
bz2csvitertoolsloggingoptparsesetswithSet()- new data type for mutable setstarfiletextwraptimeit
- source code encoding header:
- Python 2.2 · released 2001-12-21 - 2002-10-14 (2.2.2) · What’s New in Python 2.2
- any built-in type can be subclassed (including integers)
- old-style and new-style classes
- new-style classes are subclassed from other new-style classes or from
objectclass C (object): pass
- new-style classes are subclassed from other new-style classes or from
- descriptors
- objects that live inside class objects, and have a few attributes of their own:
__name__is the attribute’s name.__doc__is the attribute’s docstring.__get__(object)is a method that retrieves the attribute value from object.__set__(object, value)sets the attribute on object to value.__delete__(object, value)deletes the value attribute of object
- For example, when you write
obj.x, the steps that Python actually performs are: descriptor = obj.class.x descriptor.get(obj)
- objects that live inside class objects, and have a few attributes of their own:
- static methods:
staticmethod() - class methods:
classmethod() - properties:
property() - slots:
__slots__ - generators:
yieldkeyword - iterators:
iter(obj),__iter__()method,StopIterationexception - multiple inheritance and diamond rule
__getattribute__(attr_name)(new-style classes)socketwith support for IPv6- new module
hmac
- Python 2.1 · released 2001-04-17 · What’s New in Python 2.1
- Python Software Foundation (PSF) founded
- Python Enhancement Proposals (PEPs) introduced in development process
- statically nested scopes (optional in 2.1)
__future__directives, for examplefrom __future__ import nested_scopes- Python classes can overload operators
<,<=,>,>=,==,!=using magic methods__lt__(),__le__()etc. warningsmodule, warning frameworkweakrefmodule for weak references- function attributes def f(): pass f.foo = 42
sys.displayhook(),sys.excepthook()
- Python 2.0 · released 2000-10-16 · What’s New in Python 2.0
- core development team moved from CNRI to BeOpen
- Unicode strings (
u'čau',u'\u010dau') - list comprehensions:
[s for s in items if s.startswith('foo')] - assignment operators:
+=,-=,*=etc. - string methods:
'joe'.capitalize()) instead ofstring.capitalize('joe')fromstringmodule - garbage collection supports cycles (
instance.myself = instance) f(*args, **kwargs)instead ofapply(f, args, kwargs)printstream redirection:print >> sys.stderr, 'Hello'dict.setdefault(key, default)- new packages:
distutils,xml,gettext,mmapand other
- Python 2.7 · released 2010-07-03 · What’s New in Python 2.7
You can almost learn Python just from this summary :)
Links: