Python


General

sort() vs sorted()

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

*args and **kwargs

fstrings

Involves a mini-language.

Print variable name and value (useful for debugging):

>>> a=3
>>> f"{a=}"
'a=3'

>>> f"{a}"
'3'

Sign (only for numbers):

Syntax Sign
+ Print sign for all numbers
- Pring sign only for negative numbers
Space Print sign for negative and space for positive
z Only for floats. -0.0 will become 0.0 ??

z option is only from v3.11.

More: #, ,, _

Alignemnt:

Syntax Align Comment
< Left
> Right
^ Center
= Padding before number but after sign numbers only
>>> s="hello"
>>> f"{s:^10}"
'  hello   '

>>> f"{s:10}"
'hello     '

>>> f"{s}"
'hello'

>>> f"{s:*^11}"
'***hello***'

>>> f"{s:=10}"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: '=' alignment not allowed in string format specifier

Conversion

Syntax Function
!r repr()
!s str()
!a ascii()

See:

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

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

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

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