Skip to main content

Simple decorators for enforcing types during runtime.

Project description

Simple decorators for enforcing types during runtime.

The idea behind this is to reduce time spent developing and using packages that are computationally intensive by allowing for early raising and exiting rather than running for a long time and failing on type or class problems. Currently the easiest way to do this, which is most commonly seen in packages and modules that have type hints applied, is by adding isinstance checks and assert statements throughout the code. This quickly becomes repetitive, doesn’t help readability of the code and can easily be forgotten.

The decorators provided in this module resolve that problem by handling these type checks (as annotated) and raising when unexpected types are provided. They also aid in debugging and development by providing both the expected type and the provided argument’s runtime type. There are separate decorators for functions and classes, please do not use them the wrong way around.

from EnforceTypes import classtypes, functypes, methtypes


@functypes
def add(a: int, b: int) -> None
    print(f"Adding {a} to {b} equals {a + b}")


add(2, 2)  # prints "Adding 2 to 2 equals 4"
add("a", 2)  # This causes the decorator to raise a TypeError!

@classtypes
class Add:
    def __init__(a: int, b: int):
        self.a = a
        self.b = b

    @property
    printadd(self):
        print(f"Adding {self.a} to {self.b} equals {self.add()}")

    @methtypes
    @classmethod
    def add_values(cls, *, a: int = 1, b: int = 1) -> int:
        obj = cls(a, b)
        return obj.add()

    @methtypes
    def add(self) -> int:
        return self.a + self.b


Add(1, 1).printadd  # prints 2
a = Add(1, "a")  # TypeError raised because of a `str` instead of an `int`.
Add(1, "b").printadd  # This causes a TypeError too, before calling `A.calc`!
Add.add_values(b=5)  # returns 6
a = Add(10, 20)
a.add()  # returns 30

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

EnforceTypes-0.0.2.tar.gz (5.5 kB view hashes)

Uploaded Source

Built Distribution

enforcetypes-0.0.2-py3-none-any.whl (4.3 kB view hashes)

Uploaded Python 3

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