adventures in bad magic land
Geek
In Python (that now has a shiny new homepage that looks exactly like every other website designed in the last few years, but I digress), there is a global function called type(). It has two forms, the first accepts one parameter and returns the class of the object passed in. The second form accepts three parameters and returns a new type object - that is, it dynamically creates new classes. That second form is badness. Bad magic indeed.
So I wanted to output different text based on the type of an object. Of course I decided to use a dict; this is Python, after all. I used the class as the key and the desired text as the value. I then called type() (using the first form) to get the target object's class, used that as the key for a lookup on the dict, and printed the result. Nice and simple, except it didn't work. I ask Google and get nothing (I wonder how their A.I. is going?) I check the docs and FAQs, find nothing. I jump on IRC, write a test-case to try and explain what the hell I am talking about and... it works. Which is odd. Why is the test-case working and my effectively identical code, not? Why? Because of that second form of type(), of course.
You see, it turns out that I am producing (many, many) sub-classes at runtime of those classes I was using as keys in the map and all those objects I am checking against are instances of the sub-classes, not the keys themselves. When I was trying to debug this, of course these sub-classes had the same name as the super-class, so it was impossible to tell that they were fact different.
Grrr.
PS: thanks to m0no for putting up with me on #python
Comments
AAAAAAH HAHAhahahahahahahaha...
Sorry, but that's a pretty funny story.
Somthing new, every day ;-)
Posted by: Joel on March 10, 2006 01:09 AM
Yah, it is sad, but true. :P
Maybe the lesson from this is "subclass dict early and often." Heh.
Posted by: Mike on March 10, 2006 11:56 PM
Hey, it's Python - you're just subclassing dict anyway ;)
And: +1 on the website thing. Naff, naff, naff.
Posted by: Joel on March 11, 2006 02:08 AM
Add a Comment