Home > Back-end >  Class init in Python with custom list of parameters, set default if parameters is not explicitly pas
Class init in Python with custom list of parameters, set default if parameters is not explicitly pas

Time:12-22

I want to define in Python 3.9 a class which gets as a parameter a dictionary or a list of arguments and sets the class attributes in the following matter:

  1. If the key name is passed in the argument it uses it to set the corresponding class attribute.
  2. If the key name is not passed, it sets the class attribute with a default value.

One way to do this is:

class example():
   def __init__(self, x=None, y=None):
       if x is None:
          self.x = "default_x"
       else:
          self.x = x
       if y is None:
          self.y = "default_y"
       else:
          self.y = y

or shortly (thank to matszwecja):

class example():
   def __init__(self, x="default_x", y="default_y"):
      self.x = x
      self.y = y

Is there a more Pythonic way to do so without hard-coding if to each parameter? I want some flexibility so that if I add another attribute in the future, I won't be needed to hard-code another if for it.

I want to declare a class with

class example():
   def __init__(kwargs):
     ?

Such as if I pass example(y="some", z=1, w=2) it will generate

self.x = "default_x"
self.y = "some"
self.z = 1
self.w = 2

CodePudding user response:

class example():
    def __init__(self, x="default_x", y="default_y"):
        self.x = x
        self.y = y

CodePudding user response:

Consider using a dataclass to generate the boilerplatey __init__ method for you.

from dataclasses import dataclass


@dataclass
class Example:
    x: str = "default_x"
    y: str = "default_y"

If you need to provide a mutable default (say, a new empty list if no explicit list is provided), you can use dataclasses.field to explicitly create a field with a default factory; the dataclass decorator uses the Field object to generate the necessary code for the instance attribute.

from dataclasses import dataclass, field


@dataclass
class Example:
    x: str = "default_x"
    # Bad!
    # y: list[str] = []
    y: list[str] = field(default_factory=list)  # Good
  • Related