Is there a way to require a certain combination of optional parameters be supplied to a python class constructor?

I have a class which can be constructed from two different sets of data. I want my class constructor to accept either set a of parameters or set b of parameters, and raise an exception otherwise. I imagine the code to complete this would look something like:

class myClass:
    def __init__(self, parameterA, (parameterB OR (parameterC AND parameterD))):
        #Construct class instance

Where class instances must be given parameterA and parameterB, or parameterA, paramaterC and parameterD.

I understand I can do this programmatically by providing a default (=None) statement for each of parameters B, C and D, but this encounters the issue where just parameterA or just parameterA and parameterC (for example) are accepted without a TypeError. I could check for invalid parameter combinations and raise an error, but it feels there should be a cleaner way to do this.

If manual parameter checking is the only option, would this be a TypeError or is a custom error more appropriate?

I have tried creating this by simply giving all arguments default values, however this results in ineffective errors when the function is called with incorrect parameter combinations. I expect that there is a neater way to solve the issue of a constructor function with 2 different sets of parameters.

This question is similar to this question but due to this being a class constructor function, I do not have the luxury of simply using two different functions.

>Solution :

You can create multiple constructors using classmethods:

class myClass:
    def __init__(self, a, other_stuff):
        ...

    @classmethod
    def from_parameter_b(cls, a, b):
        other_stuff = ...  # probably using `b`
        return cls(a, other_stuff)

    @classmethod
    def from_parameter_c_and_d(cls, a, c, d):
        other_stuff = ...  # probably using `c` and `d`
        return cls(a, other_stuff)

Leave a Reply