Why is there no natural syntax for accessing attributes with names not being valid identifiers?

Chris Angelico rosuav at gmail.com
Wed Dec 4 05:33:14 EST 2013


On Wed, Dec 4, 2013 at 9:09 PM, rusi <rustompmody at gmail.com> wrote:
> OP wants attribute identifiers like outer_fieldset-inner_fieldset-third_field.
> Say I have a python expression:
> obj.outer_fieldset-inner_fieldset-third_field

I don't think so. What the OP asked for was:

my_object.'valid-attribute-name-but-not-valid-identifier'

Or describing it another way: A literal string instead of a token.
This is conceivable, at least, but I don't think it gives any
advantage over a dictionary.

What you could do, though, is create a single object that can be
indexed either with dot notation or as a dictionary. For that to work,
there'd have to be some restrictions (eg no leading underscores - at
very least, __token__ should be special still), but it wouldn't be
hard to do - two magic methods and the job's done, I think; you might
even be able to manage on one. (Code golf challenge, anyone?) Of
course, there's still the question of whether that even is an
advantage.

ChrisA



More information about the Python-list mailing list