Code completion with "self" defined classes and methods (Method Chaining)

Question:

Forgive me if the title isn’t correctly explaining what I am trying to achieve, but I don’t quite know how to put it..

Basically, I came across the assertpy lib and looked around at the code a bit.

I liked the implementation of:

assert_that(1).is_equal_to(1)

And I kind of messed around with something similar locally after seeing this and it got me thinking about how could you build this out to be more than just one "option".

Following the above example, something like this:

assert_that(10).of_modulus(3).is_equal_to(1)

Perhaps this is not the best example, but I’m interested to know how one can build out these kinds of code completion "options".

Here is a small example of how it’s been done in the assertpy lib mentioned above:

def assert_that(value: any):
    return CustomAssertsBuilder(value)


class CustomAssertsBuilder(BaseAssertions):

    def __init__(self, value):
        self.value = value

class BaseAssertions:

    def is_equal_to(self, check_value):
        assert self.value == check_value
        return self

And used like this:

assert_that(2).is_equal_to(2)

One thing I’ve noticed with this approach is that in the def is_equal_to method, self.value doesn’t actually "exist" – it’s kind of like at runtime, Python does some background magic to link that self.value to the value passed into the assert_that method.

So I don’t quite understand how it’s doing this either. It seems a bit flakey to assume that somehow, python will know where this value belongs.

Asked By: Eitel Dagnin

||

Answers:

So I searched a bit more and I learnt a couple of things about what my initial question was about.

  1. The terminology I was looking for is method chaining
  2. Returning self from a method within a class returns the class and it’s methods
  3. self.value in is_equal_to is setting value at that point and since I didn’t know point number 2 above, I couldn’t understand how/why it’s accessible later up the ladder

Here’s the SO question I found that helped me understand this a bit better:

Basic method chaining

Answered By: Eitel Dagnin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.