Python


General

sort() vs sorted()

  • list.sort():
    • only for list
    • modifies list in place
  • sorted():
    • for any iterable
    • input is not modified

https://docs.python.org/3/howto/sorting.html

Positional only argument syntax (PEP 570)

def foo(pos_only_args, /, pos-or-kw-args, *, kw-only-args):
    body

Ellipsis

A type with only a single possible value.

>>> type(Ellipsis)
<class 'ellipsis'>

>>> type(...)
<class 'ellipsis'>

>>> Ellipsis: Ellipsis; print("OK")
OK

>>> Ellipsis: ellipsis
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ellipsis' is not defined

>>> type(ellipsis)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ellipsis' is not defined

I guess ellipsis is something not meant to be accessed by users.

re (regular expression)

https://docs.python.org/3/library/re.html

>>> c = re.compile("\w\da")
>>> c.match("a0abbb")
<re.Match object; span=(0, 3), match='a0a'>

Syntax

  • ., ^, $, *, +, ?

  • {m}, {m,}, {m,n}, {,m}

  • [], |, (..)

  • \NUM: refer to a group

  • \b: ??

  • \B: ??

  • \d: [0-9]

  • \D: negation of \d

  • \s: whitespaces ([\t\n\f\v ] and more)

  • \S: negation of \s

  • \w: [0-9A-Za-z_]

  • \W: negation of \w

  • \A: match start of the string ??

  • \Z: match end of the string ??

  • *?, +?, ??, {m}+ (non-greedy / minimal version)
  • *+, ++, ?+ (possessive quantifiers ??)

enum types

import enum

class Op(enum.Enum):
    ADD = 1
    SUBTRACT = 2

Structural pattern matching (match & case)

https://peps.python.org/pep-0636/* mypy https://docs.python.org/3/library/typing.html

  • # type: ignore: skip type checking for line with this at the end
  • Type variable: A = TypeVar("A")
  • Any type: Any

numpy support type annotations too: https://numpy.org/doc/stable/reference/typing.html

pdb

Python debugger part of stdlib: https://docs.python.org/3/library/pdb.html

Commands

  • l: show current position in code
    • l <line-num>
  • n: next command
  • b: set break point
  • s: next step
  • p: print value
  • a: print arguments of current function as a list
  • pp: same as p but with pretty-printing
  • w: where
  • r: continue execution till current function returns
  • q: abort and program being debugged and exit debugger
  • whatis: print type of an expression
  • source: attempt to print the source code of an object
  • restart: restart program being debugged
  • run: start debugging the program
  • display <expr>: show a message when the argument expression changes
  • interact: start an interpreter at this point
  • alias: create an alias for a command
  • unalias: delete an alias

Drop to pdb during execution

import pdb
pdb.set_trace()

The builtin breakpoint() available from 3.7 onwards, does the same thing. https://docs.python.org/3/library/functions.html#breakpoint

.pdbrc

https://stackoverflow.com/questions/5169702/how-do-i-list-the-current-line-in-python-pdb

alias ll u;;d;;l