Search code examples
pythontype-hintingmethod-chaining

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.

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":