Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit list of functions python

I have a class with some method like this

class Validator:
    def _is_valid_code(self):
        return bool(#some logic here)

    def _is_valid_role(self):
        return bool(#some logic here)

    def _is_valid_age(self):
        return bool(#some logic here)
    .
    .
    .

if all of them are True I want to continue, else return a string

if not _is_valid_code():
    #short circuit and return a string
    return "not valid code"
if not _is_valid_role():
    #short circuit and return a string
    return "not valid role"
if not _is_valid_age():
    #short circuit and return a string with description
    return "not valid age"
#if we got here the request is valid so return a valid response
return valid_scenario

Now I do not have any problem with this because there are just three conditions, but for example, if I have more, let say like 10 conditions, I would end up with a lot of if scenarios, so I was thinking if something like this is possible, where I just add the condition logic and the condition to the list and that's it, the problem is to get the string value if the condition is false

conditions = [_is_valid_code(), _is_valid_role(), _is_valid_age()]
if all_conditions_true(conditions):
    return valid_scenario
else:
    return last_message_before_shortcut

Also want to know if this is valid and if this could be considered pythonic and recommended

like image 202
jam Avatar asked Mar 02 '23 12:03

jam


1 Answers

You can use a dict to store the functions mapped to their respective strings.

checks = {
    _is_valid_code: "not valid code",
    _is_valid_role: "not valid role",
    _is_valid_age: "not valid age",
    }

for f in checks:
    if not f():
        return checks[f]
return valid_scenario

Note that dicts preserve insertion order in Python 3.7+. If you're using an older version or want to be stricter about the ordering, use an OrderedDict or list of tuples containing functions and strings.


This by itself is perfectly Pythonic, but I don't know the context so I can't say for sure in your case. For example, if valid_scenario isn't a string, I'd strongly recommend using exceptions instead of having a mixed return type. This question covers that: Why should functions always return the same type? And I'd recommend the same if the functions are checking for error conditions.

like image 182
wjandrea Avatar answered Mar 15 '23 23:03

wjandrea