Question about accessing class-attributes.
Michele Simionato
mis6 at pitt.edu
Wed Apr 30 09:28:28 EDT 2003
Michael Hudson <mwh at python.net> wrote in message news:<7h3y91tiszi.fsf at pc150.maths.bris.ac.uk>...
> 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.
Really, I don't see where is the problem. As far as I understand (correct me
if I am wrong) dictionaries are indexed trough the identifier of their keys
i.e. hash(A) == id(A). In this example, since A is not B, it is clear to me
that d[B] is not defined and cannot work.
This issue has nothing to do with metaclasses:
class O(object):
def __eq__(self, other):
return 1
a=O(); b=O()
assert id(a)==hash(a)
assert id(b)==hash(b)
assert a==b
assert a is not b
d={a:1}
d[a] #=>1
d[b] # error since d[b] is not defined, b is not a
It seems that everybody (including myself) sees more problems in
metaclasses than really are.
Michele
More information about the Python-list
mailing list