Raising objects

Alex Martelli aleax at aleax.it
Wed Apr 30 10:18:54 CEST 2003


Steven Taschuk wrote:

> Quoth Alex Martelli:
>   [...]
>> No, in 2.2 (and 2.3 beta 1) exceptions must still be classic-classes
>> or instances thereof [or strings for backwards compatibility with the
>> dark and distant past], and should be derived from Exception (but this
>> is a recommendation, not enforced).  I do not know when (or if) this
>> restriction will be removed -- in particular, because I do not know
>> of "use cases" where the ability to raise new-style classes or instances
>> thereof would be a major boon to an application.  Maybe you have some...?
> 
> I don't have a real use case either, but it does seem rather
> arbitrary.  Is there an implementation reason for this restriction?

In a sense, yes: there is no way to check if something "is a new-style
class" as opposed to "any type whatsoever" -- so one could end up
raising lists, tuples, strings (shades of the past...), whatever.

What I hope to see happen eventually is a spec that raise can use:

  -- any subclass of Exception (by that time a new-style class), OR
  -- for backwards compatibility any old-style class, OR
  -- for VERY backwards compatibility, any string

[and also INSTANCES as well as classes for the first two cases].  And
maybe we can dispense with the third subcase, since string exceptions
HAVE been deprecated for MANY, MANY years by now, after all.

But that wouldn't make your intended use-case work, anyway:


> A somewhat silly possible use:  A depth-first search to find a
> single object satisfying a given property.  An implementation
> (ab)using exceptions for control flow:
> 
>     def _search(node):
>         if condition(node):
>             raise node
>         else:
>             for child in childrenof(node):
>                 _search(child)
> 
>     def findone():
>         try:
>             _search(root)
>         except Node, found:
>             return found
>         else:
>             return None
> 
> If the objects in the search tree are instances of new-style
> classes, the restriction would be inconvenient.  It would be
> simple enough -- though ugly -- to wrap them in an old-style
> class for raising, of course.

Exactly: even in my hoped-for new spec, you'd have to wrap this
in a subclass of Exception.  Facilitating the [ab]use of the
exception mechanism for generalized control flow is, I suspect,
NOT on the list of priorities in the BDFL's mind;-).  Feel free
to open a PEP to settle that beyond any doubt, though...;-)


Alex





More information about the Python-list mailing list