Why is there no natural syntax for accessing attributes with names not being valid identifiers?
sg552 at hotmail.co.uk
Thu Dec 5 02:50:59 CET 2013
On 04/12/2013 20:07, Piotr Dobrogost wrote:
> Unless we compare with what we have now, which gives 9 (without space) or 10 (with space):
> x = obj.'value-1'
> x = getattr(obj, 'value-1')
>> That is not a significant enough savings to create new syntax.
> Well, 9 characters is probably significant enough saving to create new syntax but saving these characters is only a side effect and is not the most important aspect of this proposal which leads us to the next point.
>> Remember the Python philosophy that there ought to be one way to do it.
> Funny you use this argument against my idea as this idea comes from following this rule whereas getattr goes against it. Using dot is the main syntax to access attributes. Following this, the syntax I'm proposing is much more in line with this primary syntax than getattr is. If there ought to be only one way to access attributes then it should be dot notation.
I believe that you are missing the point of getattr. It's not there so
that one can use arbitrary strings as attribute names; it's there so
that one can get attributes with names that aren't known until run time.
For this purpose the dot-notation-with-quotes you suggest above is not
good enough. For suppose e.g. that one does this:
name = 'attribute'
How would the interpreter know whether you're asking for getattr(x,
name) or getattr(x, 'name')?
More information about the Python-list