Operator Overloading With Right Associativity In Python

It’s actually quite fun that after years of using something, you still find a new way to do something. So at the last Sydney Python meet up, there were showings of how Python interfaces objects.

Consider this for example:

class Blah(object):
    ''' skipping the __init__ and stuff '''
    def __add__(self, other):
        # skips checks and stuff
        return self.value + other

>>> b = Blah(2)
>>> b + 2 
4

However, it was pointed out by my friend Julian, that the other way wouldn’t work – that operator overloading was only left associative:

>>> b = Blah(2)
>>> 2 + b

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'Blah'

Last night as I was preparing my slides and code for my PyConAU talk, I accidentally found this. More specifically, I found out about the __radd__, __rmul__ etc methods.

So, if you implement both __add__ and __radd__ interface methods, you can have right associativity:

class Blah(object):
    ''' skipping the __init__ and others '''
    def __add__(self, other):
        # skips checks and stuff
        return self.value + other
    def __radd__(self, other):
        return self.__add__(other)

>>> b = Blah(2)
>>> b + 2 
4
>>> 2 + b
4

.

Here’s Julian’s proof of concept to show that ambiguities don’t matter:

class Multiplier(object):
    def __init__(self, description):
        self.description = description
 
    def __mul__(self, b):
        print ("__mul__ was called on {0}".format(self.description))
 
    def __rmul__(self, b):
        print ("__rmul__ was called on {0}".format(self.description))
 
    def __int__(self):
        return 43
 
 
 
a = Multiplier("a")
b = Multiplier("b")
 
# Confirm Chew's finding still works.
a*5
5*a

# Which gets priority in this ambiguous situation? Turns out __mul__ does.
a*b

# But, we can force it.
int(a)*b

So, there you go… kinda cool, eh?

Writing… Again

This blog has been awfully silent the past year. I guess now that my job has been made redundant, I’m going to return to writing more.

Hah! Here’s to hoping!

Designing SquatCoach

A few months ago, I blogged about my frustrations with logarithmic progressions with weightlifting. I highly enjoy linear progressions – who doesn’t enjoy work that is easy? But I was wrong about one thing: I hadn’t hit the logarithmic progression part. In fact as at the time of writing of this blog post, I am still firmly in the linear progression phase.

So what went wrong? The answer is form. I was basically squatting with exceedingly poor form. I was using all kinds of stabilizer muscles in an unbalanced way that left me injured often. I took notes and noticed that it was at around 55 to 60kg that I kept getting injured about and hence the weights I squatted lingered around there. There is an old saying goes: “Practice Makes Perfect”. That is wrong. The phrase that should really be passed around is “Perfect Practice Makes Perfect”.

The breakthrough came when I got got my partner to record me squatting for the first time. I had religiously read /r/fitness and /r/formcheck, so I had a fairly good idea of what good form is. I thought I had good form – I didn’t. One of the first things I noticed was that I wasn’t squatting anywhere near deep enough, despite the fact that I had all along thought that I was doing an ass-to-grass squat.

After years spending seated in front of the computer, I had no spatial awareness of how deep I was squatting. I had to learn what a deep squat was (learning the flexibility to do that is a tale on its own). I taught her how to check for correct form: the hip crease must go lower than the top of the kneecap to be counted as a good squat. And so she began to spot me. But this wasn’t fair for her as it was eating into her training time. So after a couple of sessions, I went about developing an app that used computer vision to determine if I was squatting with good form.

The thing about computer vision is while it’s easy to start, accuracy is a Difficult goal with a capital D. One indeed can spend a lot of effort to boost the accuracy a very miniscule amount. I cut down a lot of that by using various hacks like coloured sticker dots on the hip crease, knee and barbell tip to increase the accuracy of the app. By and large, I got it working, for me. But it wasn’t working for my partner, or a colleague who had begun to be interested about the app (he had separately approached me about the feasibility of an idea similar to SmartSpot, whose idea I love). The killing blow, I think was that I had irritated some fellow gym-goers by my wrapping of a gorillapod around their racks or bars in order to set up a static filming point.

And so it transpired I would need a new app. The app would have to do these things in order to teach me to have a better squat form:

  • Monitor my form as I squat
  • Inform me when I have hit a good form
  • Only one person involved – no interfering with anyone else in the gym

Continue reading

The Bane of Communicating Succinctly

You may have noticed I have not blogged for a while. And if you do follow me on twitter you’ll note that my tweet rate has also dropped.

Ever increasingly, I find the need to share some ideas, but the ideas cannot be succinctly communicated in a pithy sentence or two. I have a lot of what I consider to be “dangerous” ideas (in the vein of the Festival of Dangerous Ideas), and I think it is imperative to be clear about the ideas.

And so I would sit down and write a blog post about it, only for it to derail into some mega long essay that is at best reads like mindless rambling (for example, see my previous post). It is in these cases that I sometimes feel I’m better off not writing. But sometimes I get passionate about a topic, and start writing a lot

Then midway through, I’d lose steam. Here are the example of titles that I have in my archive that went nowhere:

  • Why Do Ceramics Heat Up in Microwave Ovens (3997 words and I lost steam) – this article began life exactly a year ago today
  • Making Friends – A Rant (1301 words, and still incomplete, as I’m still gathering data, though I’m quite sure I’ll lose steam on that too)
  • Scrambled Eggs, The Guide (1514 words, lost steam already)
  • Logarithmic (A musing on non linear progression of things)
  • Track (A musing on being on track for a plan, and why sometimes it’s ok to let go)
  • Graveyard of Sideprojects (originally written when there was a craze over having side projects. I have 200+ side projects that I have not touched for years)
  • The Virtuous Molecule (a blog post about the fallacies of natural products)
  • Reviews: I have 3 book reviews, 2 movie reviews in my drafts, and they are nowhere

I have since concluded that it’s the length that makes me lose steam.

Yesterday I read Evan Miller’s Four Days of Go. The takeaway is that I wish I could write like him. I actually felt envious that he was able to get his point across straight, and still not be dry.

I have a problem with communicating succinctly. I look at all the work emails that I sent out – most explanation type emails have graphs, definitions and all sorts of background things. Even when I highlight the key takeaway points, written in normal English, sometimes they are missed.

…[P]erfection is attained not when there is nothing more to add, but when there is nothing more to remove

So says the oft-quoted Antoine de Saint Exupery.

The problem is I don’t know what to take away. I don’t know what to remove. The typical advice of how to improve writing is to “write more”. I’ve written this blog for more than 10 years in one form or another. I actually need to know how to improve, not just write more.

Argh.

Just Fair

Preamble: I have not blogged in a while. I have quite a few things to say, and have started at least 7 blog posts but never found the steam to complete them. Last Friday, I was having a rather interesting conversation with my colleagues, and that was cut short by a prior dinner arrangement. Having left the conversation topic unended, I decided that it’s a good point to jump off and continue blogging.

I lean slightly left towards Marxism, and I made it clear what it is that appeals to me. What appeals to me about Marxism is that it is most sci-fi in nature. “From each according to his ability, to each according to his need” is probably one of the most Star Trek-esque thing you can say. Indeed, I dream about a future where society functions like this, and I am actively working towards making such a change in society.

Of course there are other bits of Marxism that are I think outdated – the concept of class warfare, and proleteriats needing to seize control of Das Kapital[1] is in my opinion, a very 19th century view. I do however, note a similarity between today’s society and the society that Marx lived in, one on the verge of a technological revolution[2]. Just as I note that the philosophy of Marx’s time was that people find meaning of life through work, we are similarly in a period where the same has happened. Think of how you would introduce yourself to other people – it’s your name, followed by what you do.

And there we were, seated at the table. Me, J and P were discussing my Marxist leanings. J posited a very interesting question, which I have paraphrased to omit the amount of obscenities that are wont to come about around groups of male humans speaking:

Imagine if there were two students, A and B. A is super hardworking, and does all the work during the semester. A even does extra work to understand the subject deeply. B on the other hand is a party animal, preferring to skip classes and not study, and would rather spend his time partying.

Then comes exam time. Obviously A does better than B. But here’s the twist. The lecturer for whatever reason, approaches A and proposes that A averages out his grade with B.

If you were A would you do that?

This is obviously a variant of the legendary socialism classroom experiment story that has been floating around the Internet for some time now.
Continue reading

  1. [1] by that I mean, means of production. I think this is a very good pun
  2. [2] Das Kapital was published just as the dust of the Industrial Revolution was settling. Its observations of course, were made by Marx DURING what we call now the Industrial Revolution

Logarithmic

I started lifting weights a few months ago after a bit of health awakening. At first, it was a lot of fuckaround. Eventually I got into a program, and a routine. I started seeing progress in my strength, and I kept a record of how much I can lift – I’ve got nice charts to show my strength progressions. It’s not much but I can bench press about 60% of my body mass now. Slowly but surely I’m getting there.

When you are a newbie to lifting weights, there is a phase you go through what is colloquially called ‘n00b gainz’ online. It’s where an untrained/novice lifter will gain strength faster than a trained lifter. In other words, you will see strength increase (as measured by the weight lifted) linearly as a function of time, until a certain point, where you no longer see that increase.

I’ve been riding the n00b gainz wave since I started, until the last couple of weeks, where I have stalled on my squats and benchpress. The weights I can lift no longer increase linearly with time. And this is frustrating.

It’s mostly psychological, really. There is something nice about linearity. It’s easy work – put in X amount of work, get out Y amount of result. Conversely, we can also say that things get “harder” when the results are logarithmic in response to the effort put in – where you have to put in a lot more work for less result each successive time.

It is said that the n00b gainz phase is determined by one’s genetic potential. The logarithmic progression that comes after is hard work. Some people are more genetically gifted in the strength department, and so spend longer time in the n00b gains phase. By the time they get out into the logarithmic progression bit, they are way ahead.

Thinking about this is kinda stressing. But then I think back on the things I did in life so far. Let’s say everything in life with some sort of progression will follow this form: linear until a certain point, then it becomes logarithmic. It can be studying, understanding of mathematics, or weightlifting. We’ll call this the “easy” and the “hard” parts.

All my life I have coasted on the “easy” parts. Exams? Didn’t have to study much for it, because a lot of things were intuitively understood. Startup? Writing the programs were the easy parts. Initial marketing and press handling was the easy part. Then the going gets tough, and I bail, or abandon the project. It would appear that I have ran from logarithmic progressions all my life.

This isn’t a good thing. How would one be able to persevere? I need to be learning that.

Naming Things (They’re All Named Lucy)

Have you had an experience you couldn’t quite put to words? Or understood some things that cannot be described well, and everything you tried to describe it in feel like poor analogies of it? Or that you even have to resort to using analogies to begin with?

And then someone mentions a word that sounds familiar, and suddenly, the connection makes sense. It made sense for the word to mean the experience/series-of-events/phenomena that you had experienced/understood.

Earlier this afternoon I had that experience. I had experienced something that is really difficult to describe, and put to words. I took a lot of notes about it, but I wasn’t able to accurately or satisfactorily explain it with words. What the experience was and the topics it surrounded is not of much importance, nor is it profound because I spent the rest of the afternoon obssessing about the fact there are no names to describe exactly what I had experienced.

In fact, the whole meta-ness about names makes even writing this blog post a little difficult, but I hope I am able to express what I mean quite clearly.

Names are pretty important, because without them, we do not understand the world. In fact, when you name a colour, you actually start perceiving the colour as a separate colour, as did the Chinese and Japanese discovered when they named the colour blue.

Given that names are pretty important, there are a lot of problems with names.

Continue reading

Small Languages

“I like small languages,” said a friend of mine.

“Yeah, me too. Wait. What do you mean by small languages?” I replied

“You know, small. JavaScript. Lisp. Small, stuff… Not big,” he faltered as he struggled with the rest of his sentence.

That led to a series of discussions about what a small language is. We eventually enumerated a list of languages which we knew and could classify. Languages which we mutually agree are small are listed in small fonts; languages which we mutually agree are large are listed in large fonts:

  • C
  • Scheme
  • Lua
  • Python
  • Go
  • JavaScript
  • Haskell
  • Java
  • C#

Continue reading

The Dinner Party Around the World

TL;DR Last saturday I held a dinner party at my house. This is the recap, with the recipes.

For the last 3-4 months, I had been thinking a lot about holding a dinner party. I had been playing with several ideas in my head. And you know how ideas are like – they are screaming to come out of one’s head and into reality. So last month I decided to send out invites to 6 people, for a dinner party around the world.

For the dinner party I knew there had to be a theme. I originally started with the theme of “Layers”, but as time went on, I convinced myself that the theme would be too subtle. So I changed it to “Travelling Around Planet Earth”. But I still was very enamoured with the idea of layers in my dinner party. So I made a compromise. By the time the invites were sent out, the dinner party was called “A Trip Around Planet Earth”, with the theme of “Layers” Continue reading

Alternate Names For TV Shows

Earlier this afternoon I mentioned to my partner that we should watch an episode of The Adventure of WASP Girl in the Land of Systemically Biased Sampled Population. Which was of course, Orange is the New Black. She got what show that was immediately though, but I don’t think most people would get it. I then recalled a time when my housemate couldn’t find House of Cards on my home media server because I had named the folder “Derps of Capitol Hill”.

So here’s a list of funny names for TV shows I had over the years:

Show Name Nickname
Arrow drop :: Int -> [a] -> [a]
Arrow Woe is Laurel
Castle Beckett, Beckett, Beckett
Castle Caskett
Hannibal Best Cooking Show on TV
House of Cards Derps of Capitol Hill
Marvel’s Agents of SHIELD Agents of Nothing
Orange is the New Black The Adventures of WASP Girl in the Land of Systemically Biased Sampled Population
Person of Interest Adventures of Batman and Brother Eye in a Post-Snowden World
Young Justice Not The Teen Titans