I am incredibly proud of you all for producing such a great release. As the marketeers would say, "Python 3.3 is the best Python ever!"
The feature list is amazing.
Guido van Rossum
This slide intentionally left blank
Before the PEP (Python 2.x, 3.0, 3.1, 3.2):
Two Python builds: narrow and wide
After the PEP (Python 3.3, 3.4, ...):
No more distinctions between narrow and wide
PEP written by Martin von Löwis;
implemented by Torsten Becker
and Martin von Löwis
*.py
files are associated to the py launcherPY_PYTHON
,
PY_PYTHON3
envvarspy.ini
fileExamples:
#! python
, #! python3
#! /usr/bin/python
,
#! /usr/bin/python -v
PY_PYTHON
values:PY_PYTHON=3
, PY_PYTHON3=3.2
py.ini
values:[defaults]
python=3
python3=3.2
py
, py foo.py
py -3
, py -3.2
,
py -3.2 foo.py
py -3.3 -m antigravity
PEP written by Mark Hammond
and Martin v. Löwis;
implemented by Vinay Sajip.
venv
modules and pyvenv
scriptPEP written by Carl Meyer;
implemented by Carl Meyer and
Vinay Sajip.
Usage example:
3.3$ python -m venv venvtest
3.3$ cd venvtest/
3.3/venvtest$ tree
.
├── bin
│ ├── activate
│ ├── pydoc
│ ├── python -> /path/to/3.3/python
│ └── python3 -> python
├── include
├── lib
│ └── python3.3
│ └── site-packages
└── pyvenv.cfg
5 directories, 5 files
3.3/venvtest$ cat pyvenv.cfg
home = /path/to/3.3
include-system-site-packages = false
version = 3.3.0
3.3/venvtest$ python -c 'import sys; print(sys.executable)'
/usr/bin/python
3.3/venvtest$ source bin/activate
(venvtest) 3.3/venvtest$
(venvtest) 3.3/venvtest$ python -c 'import sys; print(sys.executable)'
/path/to/3.3/venvtest/bin/python
(venvtest) 3.3/venvtest$ deactivate
3.3/venvtest$
__init__.py
are now supportedPEP written by Eric V. Smith;
implementation by Eric V. Smith.
yield from
syntaxyield from iterable
is equivalent to
for item in iterable:
yield item
send()
/throw()
/close()
PEP written by Greg Ewing;
implementation by Greg Ewing et al.
raise SomeError() from None
__context__
PEP written by Ethan Furman;
implementation by Ethan Furman and
Nick Coghlan
Without context suppression:
>>> try:
... 5/0
... except ZeroDivisionError:
... raise RuntimeError("You can't divide by zero!")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: You can't divide by zero!
With context suppression:
>>> try:
... 5/0
... except ZeroDivisionError:
... raise RuntimeError("You can't divide by zero!") from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: You can't divide by zero!
errno
anymoreOSError
is now an alias for OSError
,
IOError
, EnvironmentError
,
WindowsError
, mmap.error
,
socket.error
and select.error
OSError
):
BlockingIOError
, ChildProcessError
,
ConnectionError
, FileExistsError
,
FileNotFoundError
, InterruptedError
,
IsADirectoryError
, NotADirectoryError
,
PermissionError
, ProcessLookupError
,
TimeoutError
ConnectionError
):
BrokenPipeError
, ConnectionAbortedError
,
ConnectionRefusedError
,
ConnectionResetError
Before PEP 3151:
from errno import ENOENT, EACCES, EPERM
try:
with open("document.txt") as f:
content = f.read()
except IOError as err:
if err.errno == ENOENT:
print("document.txt file is missing")
elif err.errno in (EACCES, EPERM):
print("You are not allowed to read document.txt")
else:
raise
After PEP 3151:
try:
with open("document.txt") as f:
content = f.read()
except FileNotFoundError:
print("document.txt file is missing")
except PermissionError:
print("You are not allowed to read document.txt")
PEP written by Antoine Pitrou;
implementation by Antoine Pitrou
__qualname__
attribute for classes and functions__name__
, but with the full "path"
(module name excluded)__repr__
PEP written by Antoine Pitrou;
implementation by Antoine Pitrou
>>> class Foo:
... def meth(self): pass
... class Bar:
... def meth(self):
... def func(): pass
... return func
...
>>> Foo.__name__, Foo.__qualname__
('Foo', 'Foo')
>>> Foo.meth.__name__, Foo.meth.__qualname__
('meth', 'Foo.meth')
>>> Foo.Bar.__name__, Foo.Bar.__qualname__
('Bar', 'Foo.Bar')
>>> Foo.Bar.meth.__name__, Foo.Bar.meth.__qualname__
('meth', 'Foo.Bar.meth')
>>> Foo.Bar().meth().__name__, Foo.Bar().meth().__qualname__
('func', 'Foo.Bar.meth.<locals>.func')
dict
typeobject.__dict__
are shared between instancesPEP written by Mark Shannon;
implementation by Mark Shannon
inspect.signature()
functionSignature
, Parameter
,
and BoundArguments
classessignature(obj)
returns a
Signature
objectsig.parameters
is an OrderedDict
of name -> Parameter
Parameter
s have name
, kind
,
default
, annotation
attrsBoundArguments
allows to associate args with
parametersPEP written by Brett Cannon,
Yury Selivanov, Larry Hastings,
Jiwon Seo;
implementation by Yury Selivanov
>>> def foo(a, *, b, c=None): pass
...
>>> sig = inspect.signature(foo)
>>> str(sig)
'(a, *, b, c=None)'
>>> print(sig.parameters)
OrderedDict([('a', <Parameter at 0xb736a474 'a'>),
('b', <Parameter at 0xb73c9574 'b'>),
('c', <Parameter at 0xb73c95b4 'c'>)])
>>> for p in sig.parameters.values():
... print(p.name, p.kind, p.default)
...
a POSITIONAL_OR_KEYWORD <class 'inspect._empty'>
b KEYWORD_ONLY <class 'inspect._empty'>
c KEYWORD_ONLY None
sys.implementation
with info about the Python
implementationname
, version
,
hexversion
, and cache_tag
name
: implementation name,
e.g. 'cpython', 'pypy', 'jython', ...version
: a sys.version_info objecthexversion
: implementation version in hex formatcache_tag
: used in cached modules filenames,
e.g. 'cpython-33'>>> sys.implementation
namespace(cache_tag='cpython-33', hexversion=50528496, name='cpython',
version=sys.version_info(major=3, minor=3, micro=0,
releaselevel='final', serial=0))
types.SimpleNamespace
>>> ns = types.SimpleNamespace(foo=15, bar=42)
>>> ns
namespace(bar=42, foo=15)
>>> ns.foo, ns.bar
(15, 42)
>>> ns.foo = 9000
>>> ns
namespace(bar=42, foo=9000)
PEP written by Eric Snow;
implementation by Eric Snow
u'foo'
syntax is accepted again
for Unicode stringsPEP written by Armin Ronacher.
This slide intentionally left blank
import faulthandler; faulthandler.enable()
python -X faulthandler
PYTHONFAULTHANDLER
Without faulthandler:
>>> import ctypes
>>> ctypes.string_at(0)
Segmentation fault (core dumped)
With faulthandler:
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault
Current thread 0xb77c76c0:
File "/path/to/3.3/Lib/ctypes/__init__.py", line 497 in string_at
File "<stdin>", line 1 in <module>
Segmentation fault (core dumped)
ip_address
, IPv4Address
,
IPv6Address
ip_network
, IPv4Network
,
IPv6Network
ip_interface
, IPv4Interface
,
IPv6Interface
AddressValueError
,
NetmaskValueError
address example:
>>> ipaddr = ip_address('127.0.0.1')
>>> ipaddr
IPv4Address('127.0.0.1')
>>> ipaddr.is_loopback
True
>>> print(str(ipaddr), int(ipaddr))
127.0.0.1 2130706433
>>> next_ipaddr = ipaddr + 1
>>> next_ipaddr
IPv4Address('127.0.0.2')
>>> ipaddr < next_ipaddr
True
network example:
>>> ipnet = ip_network('192.168.1.0/24')
>>> ipnet
IPv4Network('192.168.1.0/24')
>>> list(ipaddr.hosts())
[IPv4Address('192.168.1.1'), IPv4Address('192.168.1.2'), ...,
IPv4Address('192.168.1.253'), IPv4Address('192.168.1.254')]
>>> list(ipnet.subnets())
[IPv4Network('192.168.1.0/25'), IPv4Network('192.168.1.128/25')]
>>> ipnet.supernet()
IPv4Network('192.168.0.0/23')
>>> ipnet[10]
IPv4Address('192.168.1.10')
>>> ipnet[10] in ipnet
True
Reading example:
>>> with lzma.open("file.xz") as f:
... file_content = f.read()
Writing example:
>>> with lzma.open("file.xz", "w") as f:
... f.write(b"data to be compressed")
Mock
objectpatch
decorator/context managerMock example:
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
...
KeyError: 'foo'
patch example:
>>> def func():
... sys.exit('farewell')
...
>>> @patch('sys.exit')
... def test(mock_exit):
... func()
... mock_exit.assert_called_once_with('farewell')
...
>>> test()
>>>
This slide intentionally left blank
urlopen(Request('http://www.python.org', method='HEAD'))
Questions?