all() is slow?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Nov 11 20:18:26 EST 2011


On Thu, 10 Nov 2011 23:35:32 -0500, Devin Jeanpierre wrote:

>> That is patently untrue. If you were implementing namedtuple without
>> exec, you would still (or at least you *should*) prevent the user from
>> passing invalid identifiers as attribute names. What's the point of
>> allowing attribute names you can't actually *use* as attribute names?
> 
> Then why doesn't Python do this anywhere else? e.g. why can I
> setattr(obj, 'a#b') when obj is any other mutable type?

That is implementation-specific behaviour and not documented behaviour 
for Python. If you try it in (say) IronPython or Jython, you may or may 
not see the same behaviour.

The docs for getattr state:

    getattr(x, 'foobar') is equivalent to x.foobar


which implies that getattr(x, 'a!b') should be equivalent to x.a!b which 
will give a syntax error. The fact that CPython does less validation is 
arguably a bug and not something that you should rely on: it is *not* a 
promise of the language.

As Terry Reedy already mentioned, the namespace used in classes and 
instances are ordinary generic dicts, which don't perform any name 
validation. That's done for speed. Other implementations may use 
namespaces that enforce legal names for attributes, and __slots__ already 
does:

>>> class X(object):
...     __slots__ = ['a', 'b!']
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    __slots__ must be identifiers


[...]
> To go off on another tangent, though, I don't really understand how you
> guys can think this is reasonable, though. I don't get this philosophy
> of restricting inputs that would otherwise be perfectly valid

But they aren't perfectly valid. They are invalid inputs. Just because 
getattr and setattr in CPython allow you to create attributes with 
invalid names doesn't mean that everything else should be equally as 
slack.


-- 
Steven



More information about the Python-list mailing list