7

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!

Vlad Vlad
  • 530
  • 1
  • 5
  • 17
  • Welcome to SO. This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask] and the other links found on that page. – wwii Jul 04 '21 at 13:07

1 Answers1

13

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.

May.D
  • 1,832
  • 1
  • 18
  • 34
  • Thanks for your explanation! But in this case, why wouldn't we just use ``Foo`` as typehint directly? Meaning `foo_bar(x: Foo)`. – Cryoris Feb 24 '23 at 13:20
  • 1
    @cryoris: You can, but that doesn't work if you want to return an object related to `T`. Say you perform some mutable changes, then return the instance back. You would be forced to type-hint the return as `Foo`, but the caller probably requires `Bar` on occasion. Type hinting a return of `T` solves this. – Daniel Skovli Feb 27 '23 at 07:10