Skip to content

Run-time type checking for function signatures in Python.

License

Notifications You must be signed in to change notification settings

thehale/signatures

Repository files navigation

Signatures

Utilities for assessing Python function signature equality and compatibility, with the latter accounting for subtypes (including Generics!)

Joseph Hale's software engineering blog

Examples

See the test suite for a full set of examples.

Equality

# Identical function signatures are equal.
import signatures

def foo(thing: Any) -> None:
    pass

def bar(thing: Any) -> None:
    pass

assert signatures.equal(foo, bar)
# Different function signatures are not equal.
import signatures

def foo(eggs: Any) -> None:
    pass

def bar(cheese: Any) -> None:
    pass

assert not signatures.equal(foo, bar)

Compatibility

# A function signature is compatible with a more
# generic function signature.
from typing import TypeVar

import signatures

T = TypeVar("T", bound=int)

def foo(thing: bool) -> None:
    pass

def bar(thing: T) -> None:
    pass

assert signatures.compatible(foo, bar)
# Compatibility checks support nested Generic types.
import signatures

def foo(thing: List[Tuple[bool, str]]) -> None:
    pass

def bar(thing: List[Tuple[int, str]]) -> None:
    pass

assert signatures.compatible(foo, bar)
# A function signature is not compatible when
# Generic types are not compatible.
import signatures

def foo(thing: List[int]) -> None:
    pass

def bar(thing: List[Tuple[int, str]]) -> None:
    pass

assert not signatures.compatible(foo, bar)

Mozilla Public License v2.0