import inspect


def call_with_args(element, method_name, program, segment):
    """Calls the given method, optionally with the program and segment arguments set
    if they exist as parameters on the method.
    """
    method = getattr(element, method_name)
    params = inspect.signature(method).parameters
    args = {}
    if "program" in params:
        args["program"] = program
    if "segment" in params:
        args["segment"] = segment
    return method(**args)