Skip to main content

A decorator which prefers a precalculated attribute over calling the decorated method.

Project description

https://img.shields.io/pypi/v/fallback-property.svg Build Status Coverage https://img.shields.io/pypi/pyversions/fallback-property.svg https://img.shields.io/pypi/status/fallback-property.svg https://img.shields.io/pypi/l/fallback-property.svg

Requirements

  • Python 3.6

What is it?

fallback_property transforms a function into a property and uses the decorated function as fallback if no value was assigned to the property itself. A special descriptor (fallback_property.FallbackDescriptor) is used internally.

Django (or similar frameworks)

fallback_property is useful if you have a function that aggregates values from related objects, which could already be fetched using an annotated queryset. The decorator will favor the precalculated value over calling the actual method.

It is especially helpful, if you optimize your application and want to replace legacy or performance critical properties with precalulated values using .annotate().

How to use it?

Simply define a function and use the decorator fallback_property

from fallback_property import fallback_property

class Foo:

    @fallback_property()
    def fallback_func(self):
        return 7

Arguments

The fallback_property() has two optional arguments.

cached: bool = True

If the property is accessed multiple times, call the fallback function only once.

logging: bool = False

Log a warning if there was a fallback to the decorated, original method.

Usage Example (Django)

Suppose we have the following models

from django.db import models


class Pipeline(model.Model):
    @property
    def total_length(self):
        return sum(self.parts.values_list('length', flat=True))


class Parts(models.Model):
    length = models.PositiveIntegerField()
    pipeline = models.ForeignKey(Pipeline, related_name='parts')

Calling pipline.total_length will always trigger another query and is even more expensive when dealing with multiple objects. This can be optimized by using .annotate() and fallback_property()

from django.db import models, QuerySet
from django.db.functions import Coalesce
from django.db.models import Sum
from fallback_property import fallback_property


class PipelineQuerySet(QuerySet):

    def with_total_length(self):
        return self.annotate(
            total_length=Coalesce(
                Sum('parts__length', output_field=models.IntegerField()),
                0,
            )
        )


class Pipeline(model.Model):

    @fallback_property(logging=True)
    def total_length(self):
        return sum(self.parts.values_list('length', flat=True))

You can now access the total_length without triggering another query or get a warning, when the fallback function is used

pipeline = Pipeline.objects.with_total_length().first()
print(pipeline.total_length)

Important: The annotated value and the property must have the same name.

Development

This project is using poetry to manage all dev dependencies.

Clone this repository and run

poetry develop
poetry run pip install django

to create a virtual environment with all dependencies.

You can now run the test suite using

poetry run pytest

This repository follows the angular commit conventions. You can register a pre-commit hook to validate your commit messages by using husky. The configurations are already in place if you have nodejs installed. Just run

npm install

and the pre-commit hook will be registered.

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

fallback-property-0.1.0.tar.gz (5.4 kB view details)

Uploaded Source

Built Distribution

fallback_property-0.1.0-py3-none-any.whl (7.4 kB view details)

Uploaded Python 3

File details

Details for the file fallback-property-0.1.0.tar.gz.

File metadata

  • Download URL: fallback-property-0.1.0.tar.gz
  • Upload date:
  • Size: 5.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/0.12.11 CPython/3.6.6 Linux/4.15.0-45-generic

File hashes

Hashes for fallback-property-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9ffb4adaf381675fff6d27e405ec32dd20a5b87e596600d168361f5ce9149170
MD5 2dd9e571b4c97a5b1252dbc926900d50
BLAKE2b-256 51424005452ed897a00607d889099d7dc79bbe0bf26f1cae0481615756d1638b

See more details on using hashes here.

File details

Details for the file fallback_property-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fallback_property-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/0.12.11 CPython/3.6.6 Linux/4.15.0-45-generic

File hashes

Hashes for fallback_property-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 28e7c589ac747fbf9a119040064142ee482260b13b058db9b4aae37504bd319a
MD5 d3943ee2c40e479024bba029817f46b8
BLAKE2b-256 26f0bdf42f6b358769d0a3f2650645ddff751e3be1e97d81a71e74cdfcafe956

See more details on using hashes here.

Supported by

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