(WIP, ignore for now) Like 2 Chainz but better
A metaclass for automatic method chaining. (Only for methods that return None
, obviously)
What is Method Chaining?
Method chaining describes the Syntax of not having to assign objects between methods which are changing the state.
For example, in JS one can just chain the array transformations like
[1,2,3,4,5,6].filter(x => x % 2 == 0).map(x => x * x).find(x => x > 30)
How to do it manually?
Pretty easy. You just return self
. Here is an example:
class MyNum:
def __init__(self, x):
self.x = x
def inc(self):
self.x += 1
return self
three = MyNum(3)
six = three.inc().inc().inc()
assert three.x+3 == six.x
Install
pip install nchainz
Use
Just use the Chainz
metaclass:
class MyClass(metaclass=Chainz)
Why? Like seriously, Why?
I had my 5 minutes
Further reading
It's such a great read, you should really read it. (Written for Python 2)