Home > Software engineering >  Access to an attribute of a class when the name is a reserved keyword- Python
Access to an attribute of a class when the name is a reserved keyword- Python

Time:11-28

I have a "item" object (<class 'zenpy.lib.api_objects.Comment'>) coming from an API call (JSON) like this:

{
"id": 1,
"type": 10,
"via": {
     "from":{
        "id": "511",
        "name": "a"
     },
     "to":{
        "id": "999",
        "name": "b"
     }
   }
}

So, when I do

print(item.via.to['id']) 

it works properly, but when I try to do:

print(item.via.from['id']) 

I'm getting an error SyntaxError: invalid syntax on the "from". Because is a reserved keyword.

How can I access to that value? I can't change the "from" name because is coming from an API call.

Thank you.

CodePudding user response:

Peeking through the code of the API you are referencing, it looks like reserved words the convention for their classes is to prefix it with a leading _ (looking here)

So try using item.via._from, the _from is a valid identifier.

Could also be best to call the to_dict or even actual lower-level __dict__ on the object and access it by string, but I think the first should work:


x = item.via._from.id


x = item.to_dict()["via"]["from"]["id"]

# or worst case…

x = item.via.__dict__["from"].id

  • Related