Skip to main content

A few useful decorators for Python functions, classes, class methods, and properties.

Project description

Pretty useful decorators for Python functions, classes, and class methods.

Write Once, Read Many on Class Properties

If a class property takes a long time to compute and is referenced many times, it is useful to lazily compute it once (when it is first referenced) and cache the result for later references. This is where the worm submodule comes in.

class SlowExample:
    @property
    def hard_property(self):
        import time
        time.sleep(5)
        print('This took a long time to compute!')
        return 5

ex = SlowExample()
print(ex.hard_property)
print(ex.hard_property)

In the example above, the code will take around 10 seconds to run. But it only needs to take 5 seconds if the property’s value is cached, like in the example below.

from jafdecs import worm

@worm.onproperties
class QuickerExample:
    @property
    def hard_property(self):
        import time
        time.sleep(5)
        print('This took a long time to compute!')
        return 5

ex = QuickerExample()
print(ex.hard_property)
print(ex.hard_property)

Prime a function by executing something before

Consider a function that takes a long time to compute a value, but once it is computed it may be used over and over again. Exploiting this reusability is the idea behind memoization. The Python standard library offers the functools.cache() and functools.lru_cache() decorators. However, two limitations come to mind in use cases where memoization applies:

  • The returned value is very big and cannot feasibly be cached in memory

  • Programmatic control over when to pull from cache or recompute is not available

For either situation, the jafdecs.initialize.by(...) decorator can help. Consider the examples below.

def naive_function(path: pathlib.Path):
    # This code is somewhat complicated in that it initializes an asset before using it, unless the asset already exists.
    if not path.exists():
        print(f'File at {path} does not exist, so we will generate it before calling the actual function that needs it')
        generated_value = {}
        n = 18
        for i in range(10):
            key = str(i)
            value = i
            generated_value[key] = value

        print('Sleeping to simulate a hard-to-compute function.')
        time.sleep(2)
        with path.open('w') as file:
            json.dump(generated_value, file)

    print(f'File at {path} now exists, so we can get its data.')
    with path.open() as file:
        value = json.load(file)

    pprint(value)

naive_function(path=pathlib.Path('example.json'))

In the example above, the code initializes an asset if it doesn’t exist, and then uses that asset when it does. If the asset already existed, it skips the initialization entirely. For the sake of code cleanliness and ease of reading, the jafdecs.initialize.by(...) decorator allows these two distinct code blocks to be separated.

from jafdecs import initialize, utilities

import pathlib
import time
import json
from pprint import pprint


def priming_function(path: pathlib.Path):
    print(f'File at {path} does not exist, so we will generate it before calling the actual function that needs it')
    generated_value = {}
    for i in range(10):
        key = str(i)
        value = i
        generated_value[key] = value

    print('Sleeping to simulate a hard-to-compute function.')
    time.sleep(2)
    with path.open('w') as file:
        json.dump(generated_value, file)


@initialize.by(func=priming_function, condition=utilities.filenotfound)
def actual_function(path: pathlib.Path):
    print(f'File at {path} now exists, so we can get its data.')
    with path.open() as file:
        value = json.load(file)

    pprint(value)


actual_function(path=pathlib.Path('example.json'))
actual_function(path=pathlib.Path('example.json'))

In the example above, the initializing code is separated in its own function, reducing the clutter in the actual function to only the code that is needed to speed things up. The first execution is primed by the initializing function. When the second execution is called, no priming is needed. The assets produced by the first priming are reused.

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

jafdecs-0.1.0a2.tar.gz (4.1 kB view details)

Uploaded Source

Built Distribution

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

jafdecs-0.1.0a2-py3-none-any.whl (4.5 kB view details)

Uploaded Python 3

File details

Details for the file jafdecs-0.1.0a2.tar.gz.

File metadata

  • Download URL: jafdecs-0.1.0a2.tar.gz
  • Upload date:
  • Size: 4.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.6

File hashes

Hashes for jafdecs-0.1.0a2.tar.gz
Algorithm Hash digest
SHA256 ac10014e461196f884bc9a89805b0ed421e7fe27cfe4d22565326d9f12e3f311
MD5 3cf47165c055fea8f8a5be85f7fa256c
BLAKE2b-256 7c6f368ffedc93cacffe4a611f8bc283503fe123273a22400c858d5ca9f4e9d6

See more details on using hashes here.

File details

Details for the file jafdecs-0.1.0a2-py3-none-any.whl.

File metadata

  • Download URL: jafdecs-0.1.0a2-py3-none-any.whl
  • Upload date:
  • Size: 4.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.6

File hashes

Hashes for jafdecs-0.1.0a2-py3-none-any.whl
Algorithm Hash digest
SHA256 be0298f7e525e8349b84432fbeb141de02acbfb69b9548e6aa43bef857096e02
MD5 d6cdfae2997430ca80274501af0f4967
BLAKE2b-256 8c467aa4147f73ed78494578ed804fe3d52924997171165fb2ba9666e222002f

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