[Python-Dev] The interpreter accepts f(**{'5':'foo'}); is this intentional?

Guido van Rossum guido at python.org
Thu Feb 5 21:32:57 CET 2009


I'd prefer a compromise -- the keys should be strings, but should not
be required to be valid identifiers. All Python implementations should
support this. Rationale: a type check is cheap, and using strings
exclusively makes the use of a faster dict implementation possible. A
check for a conforming identifier is relatively expensive and serves
no purpose except being pedantic.

--Guido

On Thu, Feb 5, 2009 at 12:19 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Michael Haggerty wrote:
>> Is this behavior required somewhere by the Python language spec, or is
>> it an error that just doesn't happen to be checked, or is it
>> intentionally undefined whether this is allowed?
>
> Generally speaking, Python namespace dictionaries (be it globals(),
> locals(), the __dict__ attribute of an instance or a set of keyword
> arguments) aren't required to enforce the use of legal identifiers (in
> many cases, the CPython variants don't even enforce the use of strings).
>
> Enforcing legal identifiers is usually the compiler's job and if you're
> using dict syntax to access the contents of a namespace, the compiler
> doesn't care.
>
> That laxness is a CPython implementation detail though - other
> implementations are quite free to be stricter with their namespaces
> (e.g. I believe Jython namespaces use explicitly string-keyed
> dictionaries, so Jython would reject the example below).
>
> Cheers,
> Nick.
>
> P.S. An example of messing about with a class's dictionary in CPython:
>
> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class C: pass
> ...
>>>> C.__dict__[5] = "Not an identifier!"
>>>> C.5 # obviously not allowed
>  File "<stdin>", line 1
>    C.5 # obviously not allowed
>      ^
> SyntaxError: invalid syntax
>>>> C.__dict__['5'] = "Still not an identifier!"
>>>> C.5 # still not allowed
>  File "<stdin>", line 1
>    C.5 # still not allowed
>      ^
> SyntaxError: invalid syntax
>>>> C.__dict__[5]
> 'Not an identifier!'
>>>> getattr(C, 5)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: getattr(): attribute name must be string
>>>> getattr(C, '5')
> 'Still not an identifier!'
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> ---------------------------------------------------------------
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org
>



-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list