"my brain hurts" or is isinstance broken?
Jonathan Hogg
jonathan at onegoodidea.com
Wed Jul 3 10:27:23 EDT 2002
On 3/7/2002 14:55, in article
eaef2e43.0207030555.1a63fe10 at posting.google.com, "Robert Kuzelj"
<robert_kuzelj at yahoo.com> wrote:
> one could imagine an object that is a mix between a factory and
> a prototyperegistry.
>
> class ProtoFactory:
> def __init__(self):
> self.SourceObjects = {}
> def register(self, name, source):
> self.SourceObjects[name] = source
> def create(self, name):
> source = self.SourceObjects(name)
> if isinstance(source, types.Instance.Type):
> return copy.copy(source)
> else:
> return source()
Hmmm. Well I can think of a couple of possibilities:
1. Reverse the test and check to see if something is an instance of 'type'
of 'types.ClassType', i.e., a new-style class or an old-style class.
if isinstance(source, type) or isinstance(source, types.ClassType)
return source()
else:
return copy.copy( source )
2. If you know that the instances you are creating will not have '__call__'
methods, then you can differentiate classes and instances by the fact
that classes are callable:
if callable( source ):
return source()
else:
return copy.copy( source )
This works equally well for old- and new-style classes. Conveniently it
also works functions that create objects and callable instances
masquerading as classes or functions that create objects (hoo hah).
> this is just an example. i am sure, that this can be done
> differently. the real reason why i want to do this is something
> i realy dare not to say in this forum ;-)
Oh, you can tell us. No matter what crimes your contemplating, you can take
comfort in the fact that they can probably be made more horrifying with
metaclasses ;-)
Jonathan
More information about the Python-list
mailing list