473,498 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

metaclasses and Exceptions

From previous discussion [1] it seems that it's not possible to raise
new-style objects. Does this effectively mean that it's impossible to
use anything with a metaclass as an exception? i.e., am I missing some
nifty trick that would allow me to do this in the meantime?

If not, does anyone anticipate this changing anytime soon?

Cheers and thanks,

1. http://aspn.activestate.com/ASPN/Mai...n-list/1095990
Jul 18 '05 #1
4 1724
aa**@pythoncraft.com (Aahz) wrote in message news:<ce**********@panix3.panix.com>...
In article <fc*************************@posting.google.com> ,
Mark Nottingham <mn******@gmail.com> wrote:

From previous discussion [1] it seems that it's not possible to raise
new-style objects. Does this effectively mean that it's impossible to
use anything with a metaclass as an exception? i.e., am I missing some
nifty trick that would allow me to do this in the meantime?


Why do you want to do this?


I have to define a fairly large number (~40) of exceptions, and need
to keep a dictionary keyed on an error code for each, so that the
appropriate exception can be looked up. While I can manage it
manually, it would be much cleaner and more reliable to use a
metaclass to automatically create the dictionary from class
attributes.

E.g.,

class MyExceptionNumberOne:
code = "1"

class MyExceptionNumberTwo:
code = "2"

lookup = {
1: MyExceptionNumberOne,
2: MyExceptionNumberTwo,
}

Cheers,
Jul 18 '05 #2
[Mark Nottingham]
I have to define a fairly large number (~40) of exceptions, and
need to keep a dictionary keyed on an error code for each, so that
the appropriate exception can be looked up. While I can manage
it manually, it would be much cleaner and more reliable to use
a metaclass to automatically create the dictionary from class
attributes.


Yes, it is a bit annoying that exceptions are not types. However, what
you could do with metaclasses for building a registry of exceptions,
you could achieve with module introspection. Here is some example code:
---------------------------------------------------------------------->
class Erreur(Exception):
diagnostic = "Erreur Pyam"

def __str__(self):
if self.args:
return self.diagnostic + ': ' + ', '.join(map(str, self.args))
return self.diagnostic

class ErreurDenotation(Erreur):
diagnostic = "Dénotation invalide"

# [etc.]

def fabriquer_erreur_selon_nom():
# J'aurais bien voulu donner une méta-classe à Erreur pour fabriquer le
# registre au vol, mais une classe dérivée de Exception _doit_ être une
# ancienne classe, pour des raisons techniques internes à Python.
from types import ClassType
for nom, valeur in globals().iteritems():
if isinstance(valeur, ClassType) and issubclass(valeur, Erreur):
erreur_selon_nom[nom] = valeur

erreur_selon_nom = {}
fabriquer_erreur_selon_nom()
----------------------------------------------------------------------<
--
François Pinard http://www.iro.umontreal.ca/~pinard
Jul 18 '05 #3
Michael Hudson <mw*@python.net> wrote > One of the areas where PyPy is
different from CPython is that there
are no old-style classes or instances, so exceptions are necessarily
new-style. This has caused no real problems on any Python program
we've tried it on yet...


How does PyPy distinguish between instance and class arguments to
raise?

Given: raise X
Does it pass X or X()?
Raymond Hettinger
Jul 18 '05 #4
py****@rcn.com (Raymond Hettinger) writes:
Michael Hudson <mw*@python.net> wrote > One of the areas where PyPy is
different from CPython is that there
are no old-style classes or instances, so exceptions are necessarily
new-style. This has caused no real problems on any Python program
we've tried it on yet...
How does PyPy distinguish between instance and class arguments to
raise?


"isinstance(x, type)", iirc.

The code is in this file:

http://codespeak.net/svn/pypy/trunk/...ter/pyframe.py

in the function app_normalize_exception(). There's a kind of horrible
issue if you do things like:

class Nasty(type, Exception):
pass

raise Nasty()

I can't remember what PyPy does here (the answer is quite possibly
"break").
Given: raise X
Does it pass X or X()?


Depends on X! Has to, really, or we certainly would have had more
problems from this than we've had.

Cheers,
mwh

--
"declare"? my bogometer indicates that you're really programming
in some other language and trying to force Common Lisp into your
mindset. this won't work. -- Erik Naggum, comp.lang.lisp
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1898
by: Stephan Diehl | last post by:
I have a question about metaclasses: How would be the best way to "merge" different metaclasses? Or, more precisely, what is the best way to merge metaclass functionality? The idea is basicly...
3
2070
by: Mike C. Fletcher | last post by:
Slides from my PyGTA presentation on Tuesday, focusing mostly on why/where you would want to use meta-classes, are available in PDF format: ...
2
1660
by: Santiago Aguiar | last post by:
Im trying to use AOP techniques on python but, even if I understand the idea behind metaclasses, I cant find a way to use AOP in a dynamic way. What im trying to do is to weave an aspect to a...
27
1981
by: Michele Simionato | last post by:
> Hello, my name is Skip and I am metaclass-unaware. I've been programming in > Python for about ten years and I have yet to write a metaclass. At first I > thought it was just that metaclasses...
4
2045
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it...
13
1688
by: Jean-François Doyon | last post by:
Hello, I'm using MetaClasses to create classes. How do I make these new classes "globally" available? I probably just have to assign them to something magic, but I can't seem to figure out...
1
1303
by: Hartmut Goebel | last post by:
Hi, I'm currently implementing a tool for auto-generating webforms from a desription file. The output should become a php-script, an asp-script, zope-formulator or such. Each if it may (or may...
0
1086
by: Jan-Ole Esleben | last post by:
Hi! I've just posted a question about metaclasses in ZOPE on the ZOPE list, and one of the replies said that metaclasses (at least "painless" metaclasses) cannot be used without new-style...
1
2492
by: Alan Isaac | last post by:
Forman's book is out of print. Is there a good substitute? Thanks, Alan Isaac
0
7125
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7002
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7165
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6887
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7379
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5462
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4590
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
291
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.