




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Welcome to pysheeet. This project aims at collecting useful Python snippets in order to enhance pythoneers' coding ex- periences.
Typology: Study notes
1 / 375
This page cannot be seen from the preview
Don't miss anything!





























































































ii
Welcome to pysheeet. This project aims at collecting useful Python snippets in order to enhance pythoneers’ coding ex- periences. Please feel free to contribute if you have any awesome ideas for improvements to code snippets, explanations, etc.
Any snippets are welcome. If you’d like to contribute, fork pysheeet on GitHub. If there is any question or suggestion, please create an issue on GitHub Issues.
ONE
WHAT’S NEW IN PYTHON 3
The official document, What’s New In Python, displays all of the most important changes. However, if you’re too busy to read the whole changes, this part provides a brief glance of new features in Python 3.
1.1 New in Python
Table of Contents
- Asynchronous generators - Asynchronous comprehensions - Matrix multiplication - Data Classes - Built-in breakpoint() - The walrus operator - Positional-only parameters - Dictionary Merge
New in Python 3.
Python 2
>>> print "print is a statement" print is a statement >>> for x in range(3): ... print x, ... 0 1 2
Python 3
>>> print("print is a function") print is a function >>> print() >>> for x in range(3): ... print(x, end=' ') ... else: ... print() ... 0 1 2
New in Python 3.
Python 2
4 Chapter 1. What’s New In Python 3
New in Python 3.
Before Python 3.
>>> import sys >>> sys.getsizeof({str(i):i for i in range(1000)}) 49248
>>> d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'} >>> d # without order-preserving {'barry': 'green', 'timmy': 'red', 'guido': 'blue'}
Python 3.
>>> import sys >>> sys.getsizeof({str(i):i for i in range(1000)}) 36968
>>> d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'} >>> d # preserve insertion ordered {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
New in Python 3.
>>> def f(a, b, *, kw): ... print(a, b, kw) ... >>> f(1, 2, 3) Traceback (most recent call last): File "", line 1, in TypeError: f() takes 2 positional arguments but 3 were given >>> f(1, 2) Traceback (most recent call last): (continues on next page)
6 Chapter 1. What’s New In Python 3
(continued from previous page) File "", line 1, in TypeError: f() missing 1 required keyword-only argument: 'kw' >>> f(1, 2, kw=3) 1 2 3
New in Python 3.
Python 2
>>> class ParentCls(object): ... def foo(self): ... print "call parent" ... >>> class ChildCls(ParentCls): ... def foo(self): ... super(ChildCls, self).foo() ... print "call child" ... >>> p = ParentCls() >>> c = ChildCls() >>> p.foo() call parent >>> c.foo() call parent call child
Python 3
>>> class ParentCls(object): ... def foo(self): ... print("call parent") ... >>> class ChildCls(ParentCls): ... def foo(self): ... super().foo() ... print("call child") ... >>> p = ParentCls() >>> c = ChildCls() >>> p.foo() call parent >>> c.foo() call parent call child
1.1. New in Python3 7
New in Python 3.
PEP 3104 - Access to Names in Outer Scopes
Note: nonlocal allow assigning directly to a variable in an outer (but non-global) scope
>>> def outf(): ... o = "out" ... def inf(): ... nonlocal o ... o = "change out" ... inf() ... print(o) ... >>> outf() change out
New in Python 3.
>>> a, *b, c = range(5) >>> a, b, c (0, [1, 2, 3], 4) >>> for a, *b in [(1, 2, 3), (4, 5, 6, 7)]: ... print(a, b) ... 1 [2, 3] 4 [5, 6, 7]
New in Python 3.
Python 2
>>> def func(*a, *k): ... print(a) ... print(k) ... >>> func([1,2,3,4,5], **{"foo": "bar"}) (1, 2, 3, 4, 5) {'foo': 'bar'}
Python 3
1.1. New in Python3 9
>>> print(*[1, 2, 3], 4, [5, 6]) 1 2 3 4 5 6 >>> [range(4), 4] [0, 1, 2, 3, 4] >>> {"foo": "Foo", "bar": "Bar", *{"baz": "baz"}} {'foo': 'Foo', 'bar': 'Bar', 'baz': 'baz'} >>> def func(a, *k): ... print(a) ... print(k) ... >>> func([1], *[4,5], **{"foo": "FOO"}, **{"bar": "BAR"}) (1, 4, 5) {'foo': 'FOO', 'bar': 'BAR'}
New in Python 3.
>>> import types >>> generator = types.GeneratorType >>> def fib(n: int) -> generator: ... a, b = 0, 1 ... for _ in range(n): ... yield a ... b, a = a + b, b ... >>> [f for f in fib(10)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
New in Python 3.
>>> from typing import List >>> x: List[int] = [1, 2, 3] >>> x [1, 2, 3]
>>> from typing import List, Dict >>> class Cls(object): ... x: List[int] = [1, 2, 3] ... y: Dict[str, str] = {"foo": "bar"} ... >>> o = Cls() (continues on next page)
10 Chapter 1. What’s New In Python 3
New in Python 3.
>>> b'abc %b %b' % (b'foo', b'bar') b'abc foo bar' >>> b'%d %f ' % (1, 3.14) b'1 3.140000' >>> class Cls(object): ... def repr(self): ... return "repr" ... def str(self): ... return "str" ... 'repr' >>> b'%a' % Cls() b'repr'
New in Python 3.
>>> py = "Python3" >>> f'Awesome {py}' 'Awesome Python3' >>> x = [1, 2, 3, 4, 5] >>> f'{x}' '[1, 2, 3, 4, 5]' >>> def foo(x:int) -> int: ... return x + 1 ... >>> f'{foo(0)}' ' 1 ' >>> f'{123.567:1.3}' '1.24e+02'
New in Python 3.
Without raise Exception from None
>>> def func(): ... try: ... 1 / 0 ... except ZeroDivisionError: ... raise ArithmeticError (continues on next page)
12 Chapter 1. What’s New In Python 3
(continued from previous page)
... >>> func() Traceback (most recent call last): File "", line 3, in func ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "", line 1, in File "", line 5, in func ArithmeticError
With raise Exception from None
>>> def func(): ... try: ... 1 / 0 ... except ZeroDivisionError: ... raise ArithmeticError from None ... >>> func() Traceback (most recent call last): File "", line 1, in File "", line 5, in func ArithmeticError
>>> try: ... func() ... except ArithmeticError as e: ... print(e.context) ... division by zero
New in Python 3.
>>> def fib(n: int): ... a, b = 0, 1 ... for _ in range(n): ... yield a ... b, a = a + b, b ... >>> def delegate(n: int): ... yield from fib(n) ... (continues on next page)
1.1. New in Python3 13
New in Python 3.
>>> import asyncio >>> async def fib(n: int): ... a, b = 0, 1 ... for _ in range(n): ... await asyncio.sleep(1) ... yield a ... b, a = a + b , b ... >>> async def coro(n: int): ... ag = fib(n) ... f = await ag.asend(None) ... print(f) ... f = await ag.asend(None) ... print(f) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(coro(5)) 0 1
New in Python 3.
>>> import asyncio >>> async def fib(n: int): ... a, b = 0, 1 ... for _ in range(n): ... await asyncio.sleep(1) ... yield a ... b, a = a + b , b ...
>>> async def coro(n: int): ... async for f in fib(n): ... print(f, end=" ") ... else: ... print() ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(coro(5)) 0 1 1 2 3
(continues on next page)
1.1. New in Python3 15
(continued from previous page)
>>> async def coro(n: int): ... return [f async for f in fib(n)] ... >>> loop.run_until_complete(coro(5)) [0, 1, 1, 2, 3]
>>> async def slowfmt(n: int) -> str: ... await asyncio.sleep(0.5) ... return f'{n}' ... >>> async def coro(n: int): ... return [await slowfmt(f) async for f in fib(n)] ... >>> loop.run_until_complete(coro(5)) [' 0 ', ' 1 ', ' 1 ', ' 2 ', ' 3 ']
New in Python 3.
>>> # "@" represent matrix multiplication >>> class Arr: ... def init(self, arg): ... self._arr = arg ... def matmul(self, other): ... if not isinstance(other, Arr): ... raise TypeError ... if len(self) != len(other): ... raise ValueError ... return sum([xy for x, y in zip(self._arr, other._arr)]) ... def imatmul(self, other): ... if not isinstance(other, Arr): ... raise TypeError ... if len(self) != len(other): ... raise ValueError ... res = sum([x*y for x, y in zip(self._arr, other._arr)]) ... self._arr = [res] ... return self ... def len(self): ... return len(self._arr) ... def str(self): ... return self.repr() ... def repr(self): ... return "Arr({})".format(repr(self._arr)) ... (continues on next page)
16 Chapter 1. What’s New In Python 3