Typing an object based on its methods
![](https://secure.gravatar.com/avatar/3d69cd68bd0b1d00c9083256bccf3337.jpg?s=120&d=mm&r=g)
Is it possible to type an object that comprises of certain user defined methods? I am writing a function that should accept a single argument which should be an instance of any object that implements two methods, get and post. Is their a way of creating a type for it that can be scanned by static type checkers?
![](https://secure.gravatar.com/avatar/5d3fd61f232b3c3597f9d8e5314d124a.jpg?s=120&d=mm&r=g)
I’m pretty sure you’re looking for typing.Protocol. On mobile, so I’ll link to docs instead of elaborating inline: https://docs.python.org/3/library/typing.html#typing.Protocol Jon
On Oct 26, 2022, at 06:45, TobiasHT <higenyi.tobias@gmail.com> wrote:
Is it possible to type an object that comprises of certain user defined methods?
I am writing a function that should accept a single argument which should be an instance of any object that implements two methods, get and post. Is their a way of creating a type for it that can be scanned by static type checkers? _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: jon@jonjanzen.com
![](https://secure.gravatar.com/avatar/8108f546ecf91cc3c2fc754f9b87a3e5.jpg?s=120&d=mm&r=g)
It is indeed possible. You need to create a class inheriting from typing.Protocol, then define those two methods with an empty body (like in stubs). Any class that has matching members will then match that protocol class when used as a type hint. See PEP 544 for all the details: <https://peps.python.org/pep-0544/> PEP 544 – Protocols: Structural subtyping (static duck typing)<https://peps.python.org/pep-0544/> peps.python.org<https://peps.python.org/pep-0544/> [py.png]<https://peps.python.org/pep-0544/> - Spencer Brown On 26 Oct 2022, at 3:45 pm, TobiasHT <higenyi.tobias@gmail.com> wrote: Is it possible to type an object that comprises of certain user defined methods? I am writing a function that should accept a single argument which should be an instance of any object that implements two methods, get and post. Is their a way of creating a type for it that can be scanned by static type checkers? _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: spencerb21@live.com
participants (3)
-
Jon Janzen
-
Spencer Brown
-
TobiasHT