Skip to content

Instantly share code, notes, and snippets.

View MartinThoma's full-sized avatar

Martin Thoma MartinThoma

View GitHub Profile
from typing import Awaitable, Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def add_logging(f: Callable[P, R]) -> Callable[P, Awaitable[R]]:
async def inner(*args: P.args, **kwargs: P.kwargs) -> R:
await log_to_database()
return f(*args, **kwargs)
# Before 3.10
from typing import Union
def foo() -> Union[float, str]: ...
isinstance(bar (float, int))
# With 3.10
def foo(a: int) -> float | str: ...
isinstance(bar, float | int)
from typing import TypedDict, TypeGuard
class User(TypedDict):
name: str
email: str
def is_user(data: dict) -> TypeGuard[User]:
return "name" in data and "email" in data
def fibonacci(n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a+b
return a
[ 0.674772] RAS: Correctable Errors collector initialized.
[ 0.674830] microcode: sig=0x406e3, pf=0x80, revision=0xd6
[ 0.674880] microcode: Microcode Update Driver: v2.2.
[ 0.674884] IPI shorthand broadcast: enabled
[ 0.674889] sched_clock: Marking stable (674497976, 379423)->(682190101, -7312702)
[ 0.674973] registered taskstats version 1
[ 0.674995] Loading compiled-in X.509 certificates
[ 0.675591] Loaded X.509 cert 'Build time autogenerated kernel key: f55c4634ad654377a9ba7bad1ef0d32977b1cff1'
[ 0.676095] Loaded X.509 cert 'Canonical Ltd. Live Patch Signing: 14df34d1a87cf37625abec039ef2bf521249b969'
[ 0.676592] Loaded X.509 cert 'Canonical Ltd. Kernel Module Signing: 88f752e560a1e0737e31163a466ad7b70a850c19'
# from pydantic import BaseModel
# class Transaction(BaseModel):
# version_number: str # 4 Byte
# # How many UTXOs are consumed?
# input_counter: int
# tx_out_hash : str
# tx_out_index : int
from typing import Union
def upcase(s: Union[str, bytes]) -> Union[str, bytes]:
if isinstance(s, str):
return s.upper()
elif isinstance(s, bytes):
return bytes(x - 0x20 if 0x61 <= x <= 0x7A else x for x in s)
else:
raise TypeError("need str or bytes")
from typing import List
def fib_list(n: int = 0) -> List[int]:
fib_numbers: List[int] = [0, 1]
for _ in range(n):
fib_numbers.append(fib_numbers[-1] + fib_numbers[-2])
return fib_numbers
from typing import overload
@overload
def upcase(s: str) -> str:
...
@overload
def upcase(s: bytes) -> bytes:
# Core Library modules
import json
from typing import List
# Third party modules
import pydantic.json
from pydantic import BaseModel, parse_obj_as
class User(BaseModel):