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.