Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create type-hints for method chaining?

I’m writing a library containing an object that allows for method chaining on some of its methods. I’d like to provide users of this library with an easy way to know if any specific method supports chaining (and "users" includes IDEs that offer auto-completion).

According to this question and this question, chaining is easily accomplished by returning self at the end of the method call(s) that support chaining.

However, neither of those questions address how to indicate to a user that a method supports chaining (aside from the obvious docstring comment). As shown in the example code below, I tried to add a type hint, but since the class A isn’t fully defined by the time I try to use it in a type hint, Python fails to instantiate an instance of the class.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class A():

    def chain(self) -> A:  # `self` is of type A, so `-> A` is an appropriate return type
        print("Chaining!")
        return self        # Enable method chaining
>>> A().chain().chain().chain()       # Should print "Chaining!" three times.
Traceback (most recent call last):
  File "scratch.py", line 1, in <module>
    class A():
  File "scratch.py", line 3, in A
    def chain(self) -> A:
NameError: name 'A' is not defined

What is an effective way to indicate that a method supports chaining in Python?

An ideal answer will use type hints or some other construct that allows IDEs to support auto-completion.

>Solution :

You can use your class in type hints, according to this excellent post, using your class as string.

In this case, you will need to modify your function signature as the following:

def chain(self) -> "A":
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading