Skip to main content

A collection of python decorators I wish existed before

Project description

utde

A collection of utility decorators to simplify my life.

Persist

Instead of recomputing an expensive function annotate it with a generic_persist decorator. This decorator allows you to specify:

- key_or_fn: Either a string or a function
that generates a string from the wrapped_fn args
- load_fn: A function that is used to retrieve
stored data from key
- store_fn: A function that is used to store
the results of the "expensive" function call so that
it can be loaded next time instead

Example:

from utde import generic_persist

cache = dict()

def key_fn(day_str):
    year, month, day = day_str.split("-")
    return f"{year}/{month}/{day}"

def load_fn(key):
    if key in cache:
        return cache[key]

def store_fn(x, key):
    cache[key] = x

@generic_persist(key_fn, load_fn, store_fn)
def wrapped_fn(x, day_str):
    print("Imagine an expensive operation")
    return x * 2

Pandas (optional)

pip install utde[pandas]

There is a overloaded version for pandas that will load/store using the pickle format. Then you only have to provide where to load/store the file from/to.

WARNING: Only provide a key to a location you trust in, as unpickling a pickle file may execute arbitrary code.

import pandas as pd
from utde import persist_pd

@persist_pd(lambda year: f"yearly_report_{year}.pkl")
def yearly_report(year: str) -> pd.DataFrame:
    return pd.DataFrame(data={"year": [year], "profit": [42]})

Timer

Although its a simple function to write I often reinvented the wheel and wrote a function/decorator to track the execution time of a function of interest.

from utde import timer
import time

@timer
def slow_fn():
    time.sleep(2)

slow_fn()

Output:

INFO: `slow_fn` ellapsed time: 2.000s

Checks

Some decorators which can come in handy when working with jupyter notebooks

Dynamic type checking

Given a function with type annotations the decorator @check will assert that the function is not called with types incompatible with the function annotation. Note that there is some performance overhead since the code will be dynamicially passed to beartype which handles dynamic type checking.

from utde import check

@check
def integer_sum(x: int, y:int):
    return x + y

integer_sum(10, 10)  # works
integer_sum(1.25, 2.5)  # raises an utde.errors.TypeCheckError

Note 1: I'm planning to also run a linter that will check the function and hence I didn't call this decorator @check_types or similar.

Note 2: I didn't use pydantic as it didn't complain when I tried to call a function foo(x: int) with foo(1.0). This might be a design decision however I personally prefer stricter type checking here.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

utde-0.1.5.tar.gz (7.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

utde-0.1.5-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file utde-0.1.5.tar.gz.

File metadata

  • Download URL: utde-0.1.5.tar.gz
  • Upload date:
  • Size: 7.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for utde-0.1.5.tar.gz
Algorithm Hash digest
SHA256 60a8fecab212ac8227b967fc3dcda859aa66cfb419dabd1340627cb33224cf14
MD5 503fd8811bb41fc43384767a5fd064ef
BLAKE2b-256 77ccddf44a6cea02f39ec79cbfa0b1a4a599c3d13c31f7ee8b5c2d5be86ba8ed

See more details on using hashes here.

File details

Details for the file utde-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: utde-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for utde-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 22a363a8a5de876a805ae11a8a9e39aaac7fc5b11c160a32ecd81ecea2898d9c
MD5 431a3521c9ae282b8ac6651820fc55b6
BLAKE2b-256 775af543fd39e8e24c15520fe8d1ab46958fea35e7899e7e4113a8747f7bfbf9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page