[BangPypers] Object Oriented Programming in python

Sirtaj Singh Kang sirtaj at sirtaj.net
Tue Oct 22 07:16:55 CEST 2013

On 10/21/2013 11:53 AM, Saager Mhatre wrote:
> That's pretty much what always foiled my attempts at understanding Python
> MetaClasses, I was looking for power where there was none to find. The best
> comparison I could find was to Groovy's Compile time AST transforms, but
> even those are even more powerful as they drop down a level of abstraction
> and hand you the AST for the an rated element.

I agree with you partially - MOP in python can get ugly, but there's 
plenty of power there. I'll try to explain, though this stuff is 
notoriously hard to articulate (may be just for me).

So the main role of metaprogramming was to expose the language's object 
system as an object model to the programmer, so that it could be queried 
and manipulated at runtime. Does python do this? Yes, but not quite in 
the way that Kiczales outlined.

Instead we get some rough-and-ready tools with which you can simulate 
the effects that a "proper" MOP system (such as in CLOS) might have, and 
when having to make a choice between flexibility vs performance and code 
clarity, python's designers have almost invariably chosen the latter.

To begin with, there is a level of metacircularity in the new-style type 

 >>> isinstance(object, object)
 >>> isinstance(type, type)
 >>> isinstance(object, type)
 >>> isinstance(type, object)

This is what the metaclass system uses. With old-style classes, you had 
a lot of flexibility to change the class of objects at runtime. Nowadays 
there are a lot more restrictions, mostly due to performance, but you 
can still do some silly stuff:

 >>> MyType = type('MyType', (type,), {})
 >>> MyCircularType = MyType('MyCircularType', (MyType,), {})
 >>> MyCircularType.__class__ = MyCircularType
 >>> isinstance(MyCircularType, MyCircularType)

And then of course there's things like get/setattribute - combined with 
the abc module in the standard library, the type trickery above and 
python's basic metaclass system, you could effectively create your own 
metacircular MOP protocol on top of python.*

Another major issue is that python's syntax makes it just not a great 
language for embedded DSLs and MOP, even to the extent that other 
dynamic languages (Ruby!) are. That's not going to change though, and 
I'm personally okay with it for the most part. If I wanted to program 
CLOS, I'd program CLOS.


* In fact, I spent quite a while doing so a few years ago - implementing 
the OMG MOF on python - and it worked pretty well, but it proved 
difficult to get it to the point where I could even properly explain it 
to people.

More information about the BangPypers mailing list