python-cheatsheet Documentation, Study notes of Programming Languages

Welcome to pysheeet. This project aims at collecting useful Python snippets in order to enhance pythoneers' coding ex- periences.

Typology: Study notes

2021/2022

Uploaded on 07/05/2022

allan.dev
allan.dev 🇦🇺

4.5

(86)

1K documents

1 / 375

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
python-cheatsheet Documentation
Release 0.1.0
crazyguitar
May 01, 2022
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download python-cheatsheet Documentation and more Study notes Programming Languages in PDF only on Docsity!

python-cheatsheet Documentation

Release 0.1.

crazyguitar

May 01, 2022

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.

CONTENTS 1

CHAPTER

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

  • New in Python - print is a function - String is unicode - Division Operator - New dict implementation - Keyword-Only Arguments - New Super - Remove <> - BDFL retirement - Not allow from module import * inside function - Add nonlocal keyword - Extended iterable unpacking - General unpacking - Function annotations - Variable annotations - Core support for typing module and generic types - Format byte string - fstring - Suppressing exception - Generator delegation - async and await syntax

- Asynchronous generators - Asynchronous comprehensions - Matrix multiplication - Data Classes - Built-in breakpoint() - The walrus operator - Positional-only parameters - Dictionary Merge

1.1.1 print is a function

New in Python 3.

  • PEP 3105 - Make print a function

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

1.1.2 String is unicode

New in Python 3.

  • PEP 3138 - String representation in Python 3000
  • PEP 3120 - Using UTF-8 as the default source encoding
  • PEP 3131 - Supporting Non-ASCII Identifiers

Python 2

4 Chapter 1. What’s New In Python 3

1.1.4 New dict implementation

New in Python 3.

  • PEP 468 - Preserving the order of **kwargs in a function
  • PEP 520 - Preserving Class Attribute Definition Order
  • bpo 27350 - More compact dictionaries with faster iteration

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.

  • Memory usage is smaller than Python 3.
  • Preserve insertion ordered

>>> 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'}

1.1.5 Keyword-Only Arguments

New in Python 3.

  • PEP 3102 - Keyword-Only Arguments

>>> 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

1.1.6 New Super

New in Python 3.

  • PEP 3135 - New Super

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

1.1.10 Add nonlocal keyword

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

1.1.11 Extended iterable unpacking

New in Python 3.

  • PEP 3132 - Extended Iterable Unpacking

>>> 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]

1.1.12 General unpacking

New in Python 3.

  • PEP 448 - Additional Unpacking Generalizations

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'}

1.1.13 Function annotations

New in Python 3.

  • PEP 3107 - Function Annotations
  • PEP 484 - Type Hints
  • PEP 483 - The Theory of Type Hints

>>> 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]

1.1.14 Variable annotations

New in Python 3.

  • PEP 526 - Syntax for Variable Annotations

>>> 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

1.1.16 Format byte string

New in Python 3.

  • PEP 461 - Adding % formatting to bytes and bytearray

>>> 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'

1.1.17 fstring

New in Python 3.

  • PEP 498 - Literal String Interpolation

>>> 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'

1.1.18 Suppressing exception

New in Python 3.

  • PEP 409 - Suppressing exception context

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

debug

>>> try: ... func() ... except ArithmeticError as e: ... print(e.context) ... division by zero

1.1.19 Generator delegation

New in Python 3.

  • PEP 380 - Syntax for Delegating to a Subgenerator

>>> 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

1.1.21 Asynchronous generators

New in Python 3.

  • PEP 525 - Asynchronous Generators

>>> 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

1.1.22 Asynchronous comprehensions

New in Python 3.

  • PEP 530 - Asynchronous Comprehensions

>>> 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 for ... else

>>> 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 for in list

>>> async def coro(n: int): ... return [f async for f in fib(n)] ... >>> loop.run_until_complete(coro(5)) [0, 1, 1, 2, 3]

await in list

>>> 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 ']

1.1.23 Matrix multiplication

New in Python 3.

  • PEP 465 - A dedicated infix operator for matrix multiplication

>>> # "@" 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