what does argument "bound" mean in typing.TypeVar?

Viewed 1197

So I am trying to learn typing module and I am completely stuck on bound= part. I've read this comprehensive topic a couple a times, but since I am newbie to this I didn't understand much.

Can you please explain what bound= is for and what does upper-bound means? (on a simple example preferably)

Thank you beforehand!

1 Answers

So the documentation is a bit cryptic about this subject, especially if you are a beginner. Lets take the following example:

class Foo:
    pass


class Bar(Foo):
    pass


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


def foo_bar(x: T):
    print(x)


foo_bar(Bar()) # valid

Here the bound parameter means that any instance of class that ineriths Foo, or any of its subclasses validates the typing criteria defined with T.

Related