Python typing: Describe common properties

Viewed 81

I have some auto generated code which defines lots of classes with common properties, e.g. Unfortunately, they have no baseclass, interface etc.

class A:
    errors = []

class B
    errors = []

how can I describe a type for that? I cannot easily change all these types.

def validate(obj: ???):
    if errors:
        raise Exception("something wrong")
1 Answers

You need to define a protocol, which is done with typing.Protocol in Python 3.8 or later (Earlier versions can find Protocol in the typing_extensions module.)

from typing import Protocol


class HasErrors(Protocol):
    errors: list


# Requires an object whose type supports the HasErrors
# protocol, namely one with a list-valued class attribute 
# named "errors"
def validate(obj: HasErrors):
    if obj.errors:
        raise Exception("something wrong")


class GoodClass:
    errors: List[Any] = []

class BadClass1:
    pass

class BadClass2:
    errors: int = 3

validate(GoodClass())  # will pass
validate(BadClass1())  # will not pass; no errors attribute
validate(BadClass2())  # will not pass; errors attribute has wrong type
Related