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
.pyo
files - new matrix multiplication operator:
a @ b
- coroutines with
async
andawait
syntax - additional unpacking generalizations:
[1, *(2, 3)] == [1, 2, 3]
- added
%
formatting tobyte
andbytearray
(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"
pip
command should always be available- newly created file descriptors non-inheritable
- new modules:
asyncio
for asynchronous I/O- deprecates
asyncore
andasynchat
- deprecates
ensurepip
enum
pathlib
withPath
object for nice path abstractionselectors
for I/O multiplexingstatistics
tracemalloc
- Python 3.3 · What’s New In Python 3.3
yield from
for generator delegationu'unicode'
syntax is accepted again forstr
objectsvenv
for virtual environments- new modules:
faulthandler
ipaddress
lzma
unittest.mock
venv
- Python 3.2 · What’s New In Python 3.2
- stable ABI
logging
dictionary-based configuration.pyc
files stored in__pycache__
directory- WSGI v1.0.1, PEP 3333
- new modules:
argparse
for 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__.py
file 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:
with
statement 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)
print
is 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 acceptscmp
agument, usekey
instead- Text vs bytes:
str
is the newunicode
b'...'
for binary data,'foo'
for stringsstr
andbytes
objects cannot be mixed (likeunicode
andstr
in 2.x)bytes
is immutable,bytearray
is mutable
nonlocal
keyword- unpacking:
a, b, *rest = some_sequence
- dictionary compehensions:
{k: v for k, v in stuff}
- set literals:
{1, 2, 3}
- set comprehensions
except Exception, var
forbidden (useexcept Exception as var
)True
,False
andNone
are 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 single
with` statementio
library rewritten in C for performancememoryview
object- subset of
importlib
- set literals:
collections.OrderedDict
,collections.Counter
logging
: dictionary-based configurationdict
viewsviewskeys()
,viewvalues()
andviewitems()
PYTHONWARNINGS
env variablesubprocess.check_output()
weakref.WeakSet
- new modules:
argparse
sysconfig
from 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
-3
enables 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')
print
as function (optional)bytes
,bytearray
from __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 codefractions
io
json
multiprocessing
plistlib
for parsing Mac OS X.plist
filesssl
- deprecated modules:
md5
sets
sha
- Python 2.5 · released 2006-09-19 · What’s New in Python 2.5
- conditional expressions:
x = 'foo' if something else 'bar'
with
statement: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
yield
is now expression and returns value- new
GeneratorExit
exception
- new
__index__()
magic (special) method - new built-in functions:
any()
,all()
- new modules:
cProfile
contextlib
ctypes
for calling C functions from Pythonfunctools
hashlib
msilib
for creating Microsoft Installer.msi
and CAB filesspwd
for accessing shadow password databasesqlite3
- SQLite databaseuuid
for creating universally unique identifiers (UUIDs)wsgiref
xml.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
,@property
etc. - generator expressions:
(item for item in items if item.good())
- built-in set objects
set()
andfrozenset()
string.Template
reversed()
None
is a constant, cannot be assigned a new value- new modules:
collections
cookielib
decimal
withDecimal
data 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)
assert
statement no longer checks the__debug__
flag- new types in
datetime
module:date
,time
anddatetime
- new modules and packages:
bz2
csv
itertools
logging
optparse
sets
withSet()
- new data type for mutable setstarfile
textwrap
timeit
- 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
object
class 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:
yield
keyword - iterators:
iter(obj)
,__iter__()
method,StopIteration
exception - multiple inheritance and diamond rule
__getattribute__(attr_name)
(new-style classes)socket
with 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. warnings
module, warning frameworkweakref
module 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')
fromstring
module - garbage collection supports cycles (
instance.myself = instance
) f(*args, **kwargs)
instead ofapply(f, args, kwargs)
print
stream redirection:print >> sys.stderr, 'Hello'
dict.setdefault(key, default)
- new packages:
distutils
,xml
,gettext
,mmap
and 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: