[Python-ideas] Allow isinstance second argument to be a set of types

Michael Foord fuzzyman at gmail.com
Thu Jul 7 19:14:51 CEST 2011


On 7 July 2011 01:02, Alexander Belopolsky
<alexander.belopolsky at gmail.com>wrote:

> On Wed, Jul 6, 2011 at 7:35 PM, Benjamin Peterson <benjamin at python.org>
> wrote:
> ..
> > Mm. I don't blame you. I'll speak code:
> >
> > class Evil(type):
> >    def __iter__(self):
> >        return range(42)
> >
> >
> > class Accomplice(metaclass=Evil):
> >    pass
> >
> > isinstance(12, Accomplice()) # boom if arbitrary iterables are allowed
>
> What is "boom"?  If "boom" is a TypeError - it is to be expected.  For
> example, with
>

I think the instantiation of Accompalice there is a typo. The point is that
as Accompalice (the type) is an instance of Evil and is therefore an
iterable type. So if isintance naively iterated over *anything iterable* it
would attempt to iterate over Accomplice.


>
> def better_isinstance(object, classinfo):
>    if isinstance(classinfo, (type, tuple)):
>        return isinstance(object, classinfo)
>    else:
>        return any(isinstance(object, cls) for cls in classinfo)
>
>

You avoid this problem by checking explicitly for type.

Michael


> I get:
>
> >>> better_isinstance(12, Accomplice)
> False
>
> and
>
> >>> better_isinstance(12, Accomplice())
> Traceback (most recent call last):
>  ..
> TypeError: 'Accomplice' object is not iterable
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 

http://www.voidspace.org.uk/

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/20110707/7c18b6c2/attachment.html>


More information about the Python-ideas mailing list