[Python-Dev] Non-string keys in type dict (original) (raw)

Ethan Furman ethan at stoneleaf.us
Thu Mar 8 17:22:41 CET 2012


Guido van Rossum wrote:

On Wed, Mar 7, 2012 at 11:43 PM, Ethan Furman wrote:

Are you able to modify classes after class creation in Python 3? Without using a metaclass? Yes, by assignment to attributes. The dict is a read-only proxy, but attribute assignment is allowed. (This is because the "new" type system introduced in Python 2.2 needs to track changes to the dict; it does this by tracking setattr/delattr calls, because dict doesn't have a way to trigger a hook on changes.)

Poorly phrased question -- I meant is it possible to add non-string-name attributes to classes after class creation. During class creation we can do this:

--> class Test: ... ns = vars() ... ns[42] = 'green eggs' ... del ns ... --> Test <class '__main__.Test'> --> Test.dict dict_proxy({ 'module': 'main', 42: 'green eggs', 'doc': None, 'dict': <attribute '__dict__' of 'Test' objects>, 'weakref': <attribute '__weakref__' of 'Test' objects>, 'locals': { 42: 'green eggs', 'module': 'main', 'locals': {...}} }) --> Test.dict[42] 'green eggs'

A little more experimentation shows that not all is well, however:

--> dir(Test) Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() < str()

Ethan



More information about the Python-Dev mailing list