Type question

Serge Orlov Serge.Orlov at gmail.com
Tue May 17 12:52:23 EDT 2005


nitrogen... at web.de wrote:
> Hello,
>
> is this call assumed to be True in any case?
>
> result = type(SomeClass) is SomeClass
>
> I've written a proxy class which shadows a real object. If you call
> type(proxyobj) it returns the type of the proxyobject and not the
type
> of the shadowed object. Example:
>
> p = proxy(shadowobj())
> result1 = type(p) is shadowobj     # will return False
> result2 = isinstance(p, shadowobj)   # will return True
>
> So the first call compares the id()s of both types, while the second
> calll seems to work different.
> I've tried to use a proxy metaclass that creates new objects with the
> name 'shadowobj'. So
>
> print type(p)
> print type(shadowobj())
>
> will look exactly the same.

isinstance is not a law. It's just a convention. You don't
actually need to implement it. Consider PEP 246, I believe,
it is the right way to do what you want to do.
isinstance and metaclasses are not.

Instead of writing
if not isinstance(obj, class):
    report error

ask your users to write
obj = adapt(obj, Interface)

instead of dispatch code like
if isinstance(obj, thisclass):
    do this
elif isinstance(obj, thatclass):
    do that
else:
    report error

ask the users to write:
if kind(obj) is ThisKind:
    do this
elif kind(obj) is ThatKind:
    do that
else:
    report error

where kind can be defined as
def kind(obj):
    return getattr(obj, 'kind', None)

  Serge.




More information about the Python-list mailing list