[Python-Dev] Non-string keys in type dict

Ethan Furman ethan at stoneleaf.us
Thu Mar 8 18:23:46 CET 2012


Guido van Rossum wrote:
> On Thu, Mar 8, 2012 at 8:22 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> 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 "<stdin>", line 1, in <module>
>> TypeError: unorderable types: int() < str()
> 
> So what conclusion do you draw?

That other changes (that have definitely been for the better) are making 
the 'feature' of non-string keys in namespace dicts less and less 
friendly.  Rather than letting it slowly fall into complete shambles we 
should go ahead and deprecate, then remove, that functionality.

Because namespace dicts already have tacit approval to not support 
non-string keys, it doesn't make much sense to spend developer resources 
on fixing dir and whatever other functions exist that deal with 
namespace dicts and assume string-only keys.

~Ethan~


More information about the Python-Dev mailing list