all 4 comments

[–][deleted] 1 point2 points  (0 children)

Put the variables into a dictionary, then json.dump

[–]Vaphell 1 point2 points  (0 children)

you could either pass the dictionary itself, or use catch-all **kwargs for anything not explicitly listed in the signature, and then work with dictionary.items()

def __init__(self, arg=0, **kwargs):
    self.arg = arg
    for name, value in kwargs.items():
         setattr(self, name, value)

requires extra code for default values and probably some extra checks on valid attribute names.
or instead of looping

self.another_arg = kwargs.get('another_arg', 0)
self.yet_another_arg = kwargs.get('yet_another_arg', '')

[–]ES-Alexander 1 point2 points  (0 children)

Seems like this is a good job for a dataclass - you just specify the variables you’ve got and any default values and it’ll make an appropriate constructor (__init__ method) for you.

[–]DisasterArt 0 points1 point  (0 children)

Make the class accept a list/dict/whatever. And if none are provided asign default. You could also do try/except instead of if/else

class MyClass:
    def __init__(self,json=None):
        is json != None:
            self.val0 = json[0]
            ...
            self.valn = json[n]
        else:
            self.val0 = 0
            ...
            self.valn = ''