Search code examples
pythonpython-3.xpython-typingpython-3.12

python 3.12 typing override function


this type of defining function in python looks a little bit weird to me

def override[F: type](method: F, /) -> F:...

what is the meaning of [F: type] exactly?

is it something like, new way of defining parameter type before defining a function parameter? I cannot found anything about it and I don't know what to search.

I would be thankful if someone can explain this to me.

if you're using python 3.12, this example is available for you by just importing override function from typing module.

you can press Ctrl + LMB on override function to see the code I highlighted above.


Solution

  • This is a new syntax for defining generic types. It's described here in PEP-695:

    Here is an example of a generic function today.

    from typing import TypeVar
    
    _T = TypeVar("_T")
    
    def func(a: _T, b: _T) -> _T:
        ...
    

    And the new syntax.

    def func[T](a: T, b: T) -> T:
        ...
    

    And the type following the colon in for specifying a bound.