[Python-ideas] PEP-3151 pattern-matching

Michael Foord fuzzyman at gmail.com
Thu Apr 7 15:32:38 CEST 2011

On 7 April 2011 12:48, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Thu, Apr 7, 2011 at 7:17 PM, Antoine Pitrou <solipsis at pitrou.net>
> wrote:
> >> Perhaps the IOError constructor could be made to switch
> >> the class of the generated object based on the errno
> >> attribute passed to the constructor.
> >
> > Nice suggestion. I'll try to see if that is possible.
> It should be possible with appropriate fancy footwork in __new__. You
> do need to be careful to avoid calling __init__ on the created object
> twice.
> I know I've read an example that demonstrates the principle, but I
> unfortunately don't remember where (I initially thought it was in
> Guido's new-style class essay, but I checked and that wasn't it)

__init__ is called for you on construction so long as the object returned by
__new__ is an instance of the type being constructed or a subclass.

So if what you want __new__ to return *is* a subclass, then you create it
with subclass.__new__(...) and not subclass(...) (the latter would call
__init__ which would then be called again after __new__ returns).

If what you're returning *isn't* a subclass (which is best avoided anyway)
then you can construct it with otherclass(...) as __init__ won't be called
for you.

All the best,

Michael Foord

> Cheers,
> Nick.
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110407/f92219d3/attachment.html>

More information about the Python-ideas mailing list