Python

Misc Topics

Data Filtering

taking a generator, using lambda and then unpack the result into a list

# only numbers divisible by 13
print([*filter(lambda x: not x % 13, range(100))])

JS style map()

return an iterator of the return value of the lambda applied to each item in the given iterable generator

data = [*map(lambda x: (c := x**2, format(c, "04X")), range(100))]
for item in data: print(item)

Data Representation

  • Integer
    • Decimal

    • Hexa

    • Octal

    • binary

  • Float
    • Decimal

    • Scientific

  • Complex

  • bytes

  • utf-8 and utf-16

n = 10   # decimal literal
n = 0x10 # hexadecimal literal, decimal value 16
n = 0o10 # Octal literal, decimal value 8
n = 0b10 # binary literal,decimal value 3

n, t, s = 3.14, .1, 4. # float literals
c = 2.99e8 # speed of light in scientific notation

k = 3 + 4j # complex numbers
n = 2j # imaginary number

Pydantic and Datamodels

When parsing a dict, configure whether pydantic ignore and forebids extra fields

from typing import Optional
from pydantic import BaseModel, Extra
class Query(BaseModel):
    id: str
    name: Optional[str]
    class Config:
        extra = Extra.forbid

# this will fail
Query.parse_object({'name':'', id: 12345, 'type': 'generic'})