5

I am calling an API that is returning an AttributeDict that has a number of attributes, such as to and from.

To access these attributes, I am using dot notation. For example, I use object.to and that works fine.

When I try to use object.from, I get an error that says SyntaxError: invalid syntax. I assume this is because from is a keyword in Python.

If this is the case, is it possible to access from with a dot? For now, I am using object["from"], which is working, but does not match the rest of my code.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 1
    And this is why `AttributeDict` is usually [a bad idea](https://stackoverflow.com/questions/16279212/how-to-use-dot-notation-for-dict-in-python/16279578#comment23318936_16279450). They're smearing the lines between "data" and "code". – wim Jan 23 '19 at 21:23
  • 1
    Instance and class attributes are subject to the same naming conventions as variables. In a sense, variables are attributes of the module. – hpaulj Jan 23 '19 at 21:51

1 Answers1

4

While it's possible to use getattr to access such attributes:

val = getattr(ad, 'from')

this is more cumbersome than the ad['from'] syntax your AttributeDict supports, and does not satisfy your desire for dotted notation.

There is currently no option to access such attributes with dotted notation. Just stick with indexing. It handles reserved names, names with spaces/hyphens/etc. in them, and names that collide with existing methods (assuming a reasonable AttributeDict implementation). Even if you used getattr, getattr(ad, 'get') would still probably return the AttributeDict's get method instead of the value for a 'get' key.

user2357112
  • 260,549
  • 28
  • 431
  • 505