3.11
3.10
- PEP 634, Structural Pattern Matching: Specification
- PEP 635, Structural Pattern Matching: Motivation and Rationale
- PEP 636, Structural Pattern Matching: Tutorial
- bpo-12782, Parenthesized context managers are now officially allowed.
3.9
-
PEP 584, union operators added to
dict; - PEP 585, type hinting generics in standard collections;
- PEP 614, relaxed grammar restrictions on decorators.
3.8
-
PEP 572 Assignment expressions (
:=) -
PEP 570 Positional-only parameters (
def quantiles(dist, /, n=4, *, method='exclusive')) -
f-strings support
=(f'{user=} {member_since=}') -
A
continuestatement was illegal in thefinallyclause due to a problem with the implementation. In Python 3.8 this restriction was lifted. (Contributed by Serhiy Storchaka in bpo-32489.) -
The syntax allowed for keyword names in function calls was further restricted. In particular,
f((keyword)=arg)is no longer allowed. It was never intended to permit more than a bare name on the left-hand side of a keyword argument assignment term. (Contributed by Benjamin Peterson in bpo-34641.) -
Generalized iterable unpacking in
yieldandreturnstatements no longer requires enclosing parentheses. This brings the yield and return syntax into better agreement with normal assignment syntax:
def parse(family):
lastname, *members = family.split()
return lastname.upper(), *members
3.7
- PEP 563, postponed evaluation of type annotations.
3.6
- PEP 498, formatted string literals.
- PEP 515, underscores in numeric literals.
- PEP 526, syntax for variable annotations.
- PEP 525, asynchronous generators.
- PEP 530: asynchronous comprehensions.
3.5
- PEP 492, coroutines with async and await syntax.
-
PEP 465, a new matrix multiplication operator:
a @ b. - PEP 448, additional unpacking generalizations.
3.4
- No new syntax features were added in Python 3.4.
3.3
- New
yield fromexpression for generator delegation. - The
u'unicode'syntax is accepted again forstrobjects.
3.2
- Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block:
def outer(x):
def inner():
return x
inner()
del x
This is now allowed. Remember that the target of an except clause is cleared, so this code which used to work with Python 2.6, raised a SyntaxError with Python 3.1 and now works again:
def f():
def print_error():
print(e)
try:
something
except Exception as e:
print_error()
# implicit "del e" here
(See bpo-4617.)
3.1
- The syntax of the
withstatement now allows multiple context managers in a single statement:
with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
for line in infile:
if '<critical>' in line:
outfile.write(line)
With the new syntax, the contextlib.nested() function is no longer needed and is now deprecated.(Contributed by Georg Brandl and Mattias Brändström; appspot issue 53094.)
3.0
-
PEP 238: An expression like
1/2returns a float. Use1//2to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.) -
You can no longer use
u"..."literals for Unicode text. However, you must useb"..."literals for binary data. -
All backslashes in raw string literals are interpreted literally. This means that
'\U'and'\u'escapes in raw strings are not treated specially. For example,r'\u20ac'is a string of 6 characters in Python 3.0, whereas in 2.6,ur'\u20ac'was the single “euro” character. (Of course, this change only affects raw string literals; the euro character is'\u20ac'in Python 3.0.) -
PEP 3131: Non-ASCII letters are now allowed in identifiers. (However, the standard library remains ASCII-only with the exception of contributor names in comments.)
-
PEP 3107: Function argument and return value annotations. This provides a standardized way of annotating a function’s parameters and return value. There are no semantics attached to such annotations except that they can be introspected at runtime using the
__annotations__attribute. The intent is to encourage experimentation through metaclasses, decorators or frameworks. -
PEP 3102: Keyword-only arguments. Named parameters occurring after
*argsin the parameter list must be specified using keyword syntax in the call. You can also use a bare*in the parameter list to indicate that you don’t accept a variable-length argument list, but you do have keyword-only arguments. -
Keyword arguments are allowed after the list of base classes in a class definition. This is used by the new convention for specifying a metaclass (see next section), but can be used for other purposes as well, as long as the metaclass supports it.
-
PEP 3104:
nonlocalstatement. Usingnonlocal xyou can now assign directly to a variable in an outer (but non-global) scope.nonlocalis a new reserved word. -
PEP 3132: Extended Iterable Unpacking. You can now write things like
a, b, *rest = some_sequence. And even*rest, a = stuff. Therestobject is always a (possibly empty) list; the right-hand side may be any iterable. Example:
(a, *rest, b) = range(5)
This sets a to 0 , b to 4 , and rest to [1, 2, 3].
- Dictionary comprehensions:
{k: v for k, v in stuff}means the same thing asdict(stuff)but is more flexible. (This is PEP 274 vindicated.
- Set literals, e.g.
{1, 2}. Note that{}is an empty dictionary; useset()for an empty set. Set comprehensions are also supported; e.g.,{x for x in stuff}means the same thing asset(stuff)but is more flexible. - New octal literals, e.g.
0o720(already in 2.6). The old octal literals (0720) are gone. - New binary literals, e.g.
0b1010(already in 2.6), and there is a new corresponding built-in function,bin(). - Bytes literals are introduced with a leading
borB, and there is a new corresponding built-in function,bytes(). -
PEP 3109 and PEP 3134: new
raisestatement syntax:raise [expr [from expr]]. See below. -
asandwithare now reserved words. (Since 2.6, actually.) -
True,False, andNoneare reserved words. (2.6 partially enforced the restrictions onNonealready.) - Change from
exceptexc, var toexceptexcasvar. See PEP 3110. - PEP 3115: New Metaclass Syntax. Instead of:
class C:
__metaclass__ = M
...
you must now use:
class C(metaclass=M):
...
-
The module-global
__metaclass__variable is no longer supported. (It was a crutch to make it easier to default to new-style classes without deriving every class fromobject.) -
List comprehensions no longer support the syntactic form
[... for var in item1, item2, ...]. Use[... for var in (item1, item2, ...)]instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside alist()constructor, and in particular the loop control variables are no longer leaked into the surrounding scope. -
The ellipsis (
...) can be used as an atomic expression anywhere. (Previously it was only allowed in slices.) Also, it must now be spelled as.... (Previously it could also be spelled as. . ., by a mere accident of the grammar.) -
PEP 3113: Tuple parameter unpacking removed. You can no longer write
def foo(a, (b, c)): .... Usedef foo(a, b_c): b, c = b_cinstead. -
Removed backticks (use
repr()instead). -
Removed
<>(use!=instead). -
Removed keyword:
exec()is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) Also note thatexec()no longer takes a stream argument; instead ofexec(f)you can useexec(f.read()). -
Integer literals no longer support a trailing
lorL. -
String literals no longer support a leading
uorU. -
The
frommoduleimport*syntax is only allowed at the module level, no longer inside functions. -
The only acceptable syntax for relative imports is
from .[module] import name. Allimportforms not starting with.are interpreted as absolute imports. (PEP 328) -
Classic classes are gone.
2.7
- The syntax for set literals (
{1,2,3}is a mutable set). - The new
","format specifier described in PEP 378: Format Specifier for Thousands Separator. - Dictionary and set comprehensions are another feature backported from 3.x, generalizing list/generator comprehensions to use the literal syntax for sets and dictionaries.
- The
withstatement can now use multiple context managers in one statement. Context managers are processed from left to right and each one is treated as beginning a newwithstatement. - Extra parentheses in function definitions are illegal in Python 3.x, meaning that you get a syntax error from
def f((x)): pass. In Python3-warning mode, Python 2.7 will now warn about this odd usage. (Noted by James Lingard; bpo-7362.)
2.6
- Alternate syntax for catching exceptions:
except TypeError as exc. - PEP 3127 - Integer Literal Support and Syntax (backported)
- PEP 3129 - Class Decorators
@foo
@bar
class A:
pass
- It’s also become legal to provide keyword arguments after a *args argument to a function call.
def f(*args, **kw):
print args, kw
f(1,2,3, *(4,5,6), keyword=13)
- Previously this would have been a syntax error. (Contributed by Amaury Forgeot d’Arc; bpo-3473.)
2.5
2.4
- PEP 318 [Decorators for Functions and Methods](https://PEP 318: Decorators for Functions and Methods)
-
Noneis now a constant; code that binds a new value to the nameNoneis now a syntax error. (Contributed by Raymond Hettinger.)
2.2 - 2.3
2.1
x = 1
def f():
# The next line is a syntax error
exec 'x=2'
def g():
return x
2.0
# Syntax error
[ x,y for x in seq1 for y in seq2]
# Correct
[ (x,y) for x in seq1 for y in seq2]
- The full list of supported assignment operators is
+=,-=,*=,/=,%=,**=,&=,|=,^=,>>=, and<<=. - The
printstatement can now have its output directed to a file-like object by following theprintwith>> file
print >> sys.stderr, "Warning: action field not supplied"
-
f(*args, **kw)is a shorter and clearer way to achieve the same effect. This syntax is symmetrical with the syntax for defining functions: - Modules can now be renamed on importing them, using the syntax
import module as nameorfrom module import name as othername. The patch was submitted by Thomas Wouters.