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

Guido van Rossum guido at python.org
Thu Mar 8 16:27:41 CET 2012


On Thu, Mar 8, 2012 at 1:10 AM, Lennart Regebro <regebro at gmail.com> wrote:
> On Thu, Mar 8, 2012 at 08:46, Ethan Furman <ethan at stoneleaf.us> wrote:
>> I think it would be sad to lose that functionality.
>>>> If we are going to, though, we may as well check the string to make sure
>> it's a valid identifier:
>> That would break even more code. I have encountered many cases of
> attributes that aren't valid identifiers, in particular using dots or
> dashes. Admittedly this is often in cases where the object has both
> attribute access and key access, so you can make foo['bar-frotz']
> instead. But when should we then require that it is a valid identifier
> and when not?
>>> --> class A:
>> -->   pass
>> --> setattr(A, '42', 'hrm')
>> --> A.42
>>  File "<stdin>", line 1
>>    A.42
>>       ^
>> SyntaxError: invalid syntax
>>>> Doesn't seem very useful.
>> You have to set it with setattr, so you have to get it with getattr. I
> don't see the problem.

I'm with Lennart. I've spoken out on this particular question several
times before; it is a *feature* that you can use any arbitrary string
with getattr() and setattr(). However these functions should (and do!)
reject non-strings.
I'm lukewarm on forbidding non-strings in namespace dicts if you can
get them in there by other means. I presume that some people might use
this to hide state they don't want accessible using regular attribute
notation (x.foo) and maybe somebody is even using some namespace's
keys as a dict to store many things with non-string keys, but that
feels like abuse of the namespace to me, and there are plenty of other
ways to manage such state, so if it gives a significant speed-up to
use string-only dicts, so be it. (Although Python's dicts already have
some string-only optimizations -- they just dynamically adapt to a
more generic and slightly slower approach once the first non-key
string shows up.)
As Nick says we should introduce a deprecation period if we do this.
On Wed, Mar 7, 2012 at 11:43 PM, Ethan Furman <ethan at stoneleaf.us> 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.)
-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /