79753023

Date: 2025-09-02 02:34:45
Score: 2
Natty:
Report link

How about add those attributes with a default value None by using a metaclass?

from dataclasses import dataclass

keys = ('id',
    'name',
    'pwd',
    'picture',
    'url',
    'age')

class MyMeta(type):
    def __call__(self, *args, **kwargs):
        for p in keys:
            kwargs[p] = kwargs.get(p)
        cls_obj = self.__new__(self, *args, **kwargs)
        self.__init__(cls_obj, *args, **kwargs)
        return cls_obj


@dataclass
class User(metaclass=MyMeta):
    id: str
    name: str
    pwd: str
    picture: str
    url: str
    age: int



attributes1 = {"id": "18ut2", "pwd": "qwerty", "name": "John Doe", "picture": None, "age": None, "url": "www.example.com"}
user1 = User(**attributes1)
print(user1)

attributes2 = {"id": "18ut2", "pwd": "qwerty", "name": "John Doe", "url": "www.example.com"} # No picture or age key anymore
user2 = User(**attributes2)
print(user2)

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Starts with a question (0.5): How
  • Low reputation (0.5):
Posted by: vassiliev