Question about accessing class-attributes.

Michael Hudson mwh at python.net
Tue Apr 29 04:54:54 EDT 2003


mis6 at pitt.edu (Michele Simionato) writes:

> Michael Hudson <mwh at python.net> wrote in message news:<7h37k9ilm5v.fsf at pc150.maths.bris.ac.uk>...
> > Thomas Heller <theller at python.net> writes:
> > 
> > > Wouldn't a caching class factory be able to do this?
> > 
> > Yes.  I only said "tricky", not impossible.
> > 
> > class MetaGit(type):
> >     def __eq__(self, other):
> >         # aha! this makes class objects unhashable, cackle!
> >         return self is other
> > 
> > I don't know whether you want to cope with things like that.
> > 
> > Cheers,
> > M.
> 
> Two questions:
> 
> 1) I don't see how this solve the problem of avoiding duplications of
> metaclasses;

Well, I imagine a caching class factory would store base classes in a
dict...

> 2) why you say this makes classes unhashable ?

Well, I thought it would.  I was wrong:

> It seems I can still use A and B as keys for a dictionary: 
> 
> class A: __metaclass__ = MetaGit
> class B: __metaclass__ = MetaGit
> 
> dic={A:1, B:2}
> 
> print dic[A]  #=>1 okay
> print dic[B]  #=>2 okay

Then you get this kind of weirdness:

/>> class C(type):
|..     def __eq__(self, other):
|..         return 1
\__ 
/>> class A:
|..     __metaclass__ = C
\__ 
/>> class B:
|..     __metaclass__ = C
\__ 
->> d = {}
->> d[A] = 1
->> d[B] 
Traceback (most recent call last):
  File "<input>", line 1, in ?
KeyError: <class '__main__.B'>
->> A == B
1

Then I suspect whether a instance of C gets A out of the dictionary
depends on accidents of memory allocation and hash table
implementation.  That's not a good thing.

CHeers,
M.

-- 
  ARTHUR:  Yes.  It was on display in the bottom of a locked filing
           cabinet stuck in a disused lavatory with a sign on the door
           saying "Beware of the Leopard".
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 1




More information about the Python-list mailing list