Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading