Reputation: 4747
I want to create a Python class that represents a dictionary my_dict that I want to convert as follows
my_class = MyClass(**my_dict)
The issues is that one of the dicts keys is called 'class'
So when I do as follows Python complains:
class MyClass(BaseModel)
name: str
address: str
id: int
class: str <-- Python does not like me using the keyword class
How can I get around this?
Upvotes: 1
Views: 96
Reputation: 19233
As deceze states in their comment, the conventional way of resolving this issue is to suffix the name of the attribute with an underscore. I'm sure there's probably some hacky way of getting an attribute named class
, but it's probably not worth the pain of setting up and maintaining.
This is described in PEP8, which outlines style guidelines for Python code:
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.tkinter.Toplevel(master, class_='ClassName')
Upvotes: 1