Search code examples
pythonpython-typing

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


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!


Solution

  • 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)  # Can be any subtype of Foo
    
    
    def foo_bar(x: T):
        print(x)
    
    
    foo_bar(Bar()) # valid
    

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