Suppose we have the following classes:
class Foo:
def __init__(self, method):
self.method = method
def __get__(self, instance, owner):
if instance is None:
return self
return self.method(instance)
class Bar:
@Foo
def do_something(self) -> int:
return 1
Bar().do_something # is 1
Bar.do_something # is Foo object
How to type hint __get__ and method correctly so that Pylance understands Bar().do_something is of the return type of do_something? (like a standard property)
You'll need to overload the
__get__method.I do not use VSCode myself, but I tested the code below with MyPy and I would expect Pyright to infer the types correctly as well.
Python
>=3.9To make this as flexible as possible, I would suggest making
Foogeneric in terms ofDemo:
Running MyPy over this gives the desired output:
NOTE: (thanks to @SUTerliakov for pointing some of this out)
>=3.10, you can importConcatenateandParamSpecdirectly fromtypingand you can use the|-notation instead oftyping.Union.>=3.11you can importSelfdirectly fromtypingas well, meaning you won't needtyping_extensionsat all.Python
<3.9Without
Concatenate,ParamSpecandSelfwe can still makeFoogeneric in terms of the return value of the decorated method:MyPy output for the same demo script from above: