Kareem's thread, besides being informative and a great read, reminds me of Operator overloading in Python - something I wish I have know sooner: basically, in Python you can use `+` to combine things - mostly things of the same type - and you can define it to follow specific rule https://twitter.com/kareem_carr/status/1289724475609501697
For example, we can define an integer-like object so you have "2+2=5" and destroy Western civilization:
The trick is to specify a dunder class method `__add__` (ie., overload the operator `+`), which in this case the rule is to always plus 1 whenever you do an addition.
By overwriting different operators, you can have your Python objects follow the set of rules you desired. For example, we might want to make addition commutative with python literal int. To do that, we overwrite the `__radd__` method:
Oops, now the addition between our dunder integer does not work! Let's be a bit more careful, and also make sure the returning object keeps this new addition behavior:
This is not just cute but also super useful! For example, summing random variable is an intractable problem, but in some cases like Gaussian Random Variable it is pretty easy to do and we could define prob programming language to detect these automatically to simply your model!
simply -> simplify 😅
You can follow @junpenglao.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: