Python

My personal python code snippets and tips.

Function decorators

Post mortem debugging

python3 -m pdb -c continue Rozpis.py -p Bik 2024-06.xls

Pandas

import pandas as pd

pd.isna(pd.NA)  # True
pd.isna(np.nan) # True

isnull is the same, it was original function, but due to NumPy isna, it was renamed and stayed as an alias.

Drop duplicates keep max

df.drop_duplicates(subset=['col'], keep='last')

It does not aggregate. To get max or mean:

df.groupby('col', as_index=False).agg({'value': 'max'})
df.groupby('col', as_index=False).agg(['mean','max'])

subprocess

import subprocess

cmd = ["command", "arguments"]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)

CLI arguments

import argparse

parser = argparse.ArgumentParser(
    prog = "Program name"
    description = "program description"
    epilog = "text at the end of help page"
    )
parser.add_argument("filename")
parser.add_argument("-i", "--interactive", action="store_true", help="argument description")
parser.add_argument("-o", "--output", type=str, help="argument description")

args = parser.parse_args()

Code improvements

flake8 and black

Style checkers, similar.

 flake8 .
 black .

ruff

can do similar.

pylinter

Check for common programming mistakes, import order etc.

 pylint .

Static types

uv run mypy *.py 
uv run mypy dir/