Type question

nitrogenycs at web.de nitrogenycs at web.de
Tue May 17 12:00:29 EDT 2005


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. however their id()s compare different and
that's why the 1st test doesn't work as I'd expect it to work.
Can somebody tell me why the id()s compare different for the same type
names? Here's the metaclass:

class ProxyMeta(type):
    def __new__(self, classname, bases, classdict):
        return type.__new__(self, 'shadowobj', bases, classdict)

class Proxy(object):
    __metaclass__ = ProxyMeta

Why is (type(Proxy) is shadowobj == False)? Shouldn't type.__new__
reuse the existing shadowobj type and increase its refcount instead of
creating a new instance of it? Then the id()s would compare the same.
So, finally, is checking for types with 'is' as shown above just wrong
and one should use isinstance or is my proxy class showing bad
behaviour or is this a bug in type.__new__?

-Matthias




More information about the Python-list mailing list