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 | ncogh...@gmail.com | Brisbane, Australia --------------------------------------------------------------- _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com