detly
detly

Reputation: 30332

How can I check whether a Python object satisfies a type constraint?

Let's say I have this type constraint on a dataclass:

from dataclasses import dataclass
from typing import Sequence
from numbers import Integral

@dataclass
class Coefficients:
    coefs: Sequence[Integral]

Now I want to know whether the object [1, 2, 3] will satisfy this type constraint. I want to know this as I'm coding/designing, not necessarily at runtime, so both a static checker solution or runtime solution would be fine.

I tried isinstance() but it doesn't work with parameterised types:

$ mypy -c 'from typing import Sequence; from numbers import Integral; isinstance([1, 2, 3], Sequence[Integral])'
<string>:1: error: Parameterized generics cannot be used with class or instance checks
$ python -c 'from typing import Sequence; from numbers import Integral; isinstance([1, 2, 3], Sequence[Integral])'
[...]
TypeError: Subscripted generics cannot be used with class and instance checks

In general I'd like to know how to check objects against arbitrary type annotations; while I can easily look up whether List is a Sequence and int is an Integral, later I may want to check more complex structures. How do I do that?

Upvotes: 0

Views: 534

Answers (1)

askaroni
askaroni

Reputation: 993

You can annotate the required type, and run mypy on it directly. Mypy has an open issue about support for the numbers module's numeric tower.

mypy -c 'from typing import Sequence
from numbers import Integral
x: Sequence[Integral]
x = [1, 2, 3]'

<string>:4: error: List item 0 has incompatible type "int"; expected "Integral"
<string>:4: error: List item 1 has incompatible type "int"; expected "Integral"
<string>:4: error: List item 2 has incompatible type "int"; expected "Integral"

Upvotes: 2

Related Questions