Why is there no natural syntax for accessing attributes with names not being valid identifiers?
p at google-groups-2013.dobrogost.net
Wed Dec 4 00:47:37 CET 2013
On Tuesday, December 3, 2013 7:03:41 PM UTC+1, rand... at fastmail.us wrote:
> On Tue, Dec 3, 2013, at 12:14, Piotr Dobrogost wrote:
> > Hi!
> > I find global getattr() function awkward when reading code.
> > What is the reason there's no "natural" syntax allowing to access
> > attributes with names not being valid Python identifiers in a similar way
> > to other attributes?
> > Something along the line of
> > my_object.'valid-attribute-name-but-not-valid-identifier'?
> The getattr function is meant for when your attribute name is in a
> variable. Being able to use strings that aren't valid identifiers is a
> side effect.
Why do you say it's a side effect? Could you elaborate? I see nothing odd in passing literal (string literal in this case) as a value of function's argument.
> Why are you designing classes with attributes that aren't
> valid identifiers?
Attribute access syntax being very concise is very often preferred to dict's interface. That's why various containers expose their elements as attributes. In my case I'm using in-house web form library which provides FieldSet class holding objects of type Field or other FieldSets. This nesting leads to names of the form 'outer_fieldset-inner_fieldset-third_field' which are not valid identifiers due to minus sign.
More information about the Python-list