pythonpython-3.xparameters

How do I define two mutually dependent parameters in Python?


I want to create a Python class with two mutually inclusive parameters that are dependent on each other. The user must either provide a value for both parameters or neither. If one parameter is specified without the other, an exception should be raised.

class TestEvent:
    def __init__(self, start_date = None, end_date = None , **kwargs):
        # Check if start_date and end_date are defined 
        pass

valid_event_1 = TestEvent()
valid_event_2 = TestEvent(start_date = '2022-07-01', end_date = '2022-08-01')
invalid_event_1 = TestEvent(start_date = '2022-07-01')  # Raise exception
invalid_event_2 = TestEvent(end_date = '2022-08-01')  # Raise exception

How can I define two mutually dependent parameters in Python?


Solution

  • You could express the mutual exclusive ^-operator.

    if (start_date is None) ^ (end_date is None):
       print('Error')
    

    Here the table of values for the ^-operator

    from itertools import product
    
    def xor_table_of_values():
        """
          1   ^   1   -> 0
          1   ^   0   -> 1
          0   ^   1   -> 1
          0   ^   0   -> 0
        """
        print(*(f'{i:^5} ^ {j:^5} -> {int(i^j)}' for i, j in product((True, False), repeat=2)), sep='\n')
    
    xor_table_of_values()
    

    Here a (verbose) abstraction:

    def test(start_date=None, end_date=None):
    
        is_given_sd = start_date is not None
        is_given_ed = end_date is not None
    
        if is_given_sd ^ is_given_ed:
            print('Error')
    
    
    test(start_date='7', end_date='767')
    #
    test(start_date='2')
    # Error
    test(end_date='43')
    # Error
    test()
    #