Mixing metaclasses and exceptions

Jp Calderone exarkun at divmod.com
Thu Dec 30 09:15:03 EST 2004


On Mon, 27 Dec 2004 21:44:23 -0500, Steve Menard <foo at bar.com> wrote:
>In writing the next version of Jpype (Python to Java bridge), I have hot 
> a rather unpleasant wall ... Hopefully it is I who is doing something 
> wrong and i can be fixed ...
> 
> Since I am bridging Java classes and presenting them as Python classes, 
> I decided to try to create a corresponding python class for every Jva 
> classes accessed inside the python program. So far, everything is great 
> .. until we get to exception handling.
> 
> Since I am creating classes, on the fly, I thought the easiest and most 
> pythonic way to do it would be to create a metaclass. This is true also 
> for the Java exception classes.
> 
> The problem arises when I try to raise one of those exception classes 
> ... it sems Python will not allow classes that have a custom metaclass 
> to be raised as exceptions! Even though those classes derive from 
> Exception! To illustrate, try the following snippet :

  Only instances of classic classes can be raised.  This is an arbitrary 
restriction imposed by CPython.  There's no particular reason it need be 
the case, aside from the fact that no one has bothered to do the necessary 
work to make new-style classes usable as exceptions.

  One way you could get around this problem is by making your metaclass 
return an instance of a classic class.

  I'd skip that, though.  Your problem doesn't sound "Metaclass!" at me.
I wonder if you could elaborate on your usage?  Perhaps there's a better 
solution which doesn't involve metaclasses at all.

  Jp



More information about the Python-list mailing list