I have a Python class which needs to accept one of two mutually exclusive arguments. If the arguments are not exclusive, (ie: if both or neither are given), an error should be raised.
class OrgLocation: __init__(self, location_num=None, location_path=None): """location_num & location_path are mutually exclusive"""
In most scenarios, the best option would be to make two separate classes. However, I am working with an external API which requires these two attributes to be mutually exclusive.
Request:
<OrgLocation LocationPathName="ROOT/BU/DIV/SL/DEPT/JOB" LocationNum="1234"/>
Response:
<Error Message="Use either LocationNum or LocationPathName but not both." ErrorCode="1186">
Similar questions seem to indicate that argparse
can be used for mutually exclusive arguments in command-line interfaces, but I’m unsure how to apply this to a class constructor
How can I create a Python function with mutually exclusive arguments?
Advertisement
Answer
You might want to create a test in the init method but a better question might be… Why?
if location_num is not None and location_path is not None: raise TheseParametersAreMutuallyExclusiveError()
Why would you make a class that has multiple purposes? Why not create separate classes?