1

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?

6
  • A class is also an object and an attribute of an object can be set with setattr. Commented Jan 20, 2023 at 5:42
  • 2
    you can use __annotations__['class'] = str -- though every metaprogramming class I tried crashed in some other way later on with a SyntaxError building their __init__ or __new__ method Commented Jan 20, 2023 at 5:44
  • 1
    Usually you name it klass or cls or class_ because of this restriction. Commented Jan 20, 2023 at 5:45
  • What is BaseModel? Is that from some framework, whose solution for this issue you should thus use? Commented Jan 20, 2023 at 6:09
  • @KellyBundy BaseModel is from pydantic Commented Jan 20, 2023 at 6:13

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.