dimanche 2 mai 2021

Pythonic way to do if statement comparisons only if the variable is not None

Is there a more pythonic way to do this if block?

def is_notification_needed(request: RiverPreference, gauge: Gauge) -> bool:
    """
    Decides whether an email should be sent to the user or not based on their provided preferences.
    :param request: RiverPreference dataclass
    :param gauge: Gauge dataclass
    :returns: boolean
    """
    for preference in request:
        if preference.level and preference.trend and preference.level >= gauge.level and preference.trend == gauge.trend:
            return True
        elif preference.level and not preference.trend and preference.level >= gauge.level:
            return True
        elif preference.trend and not preference.level and preference.trend == gauge.level:
            return True
        return False

preference.trend and preference.level default to None when the user doesn't want to set it. I'd like to be able to check these values against the gauge values only if they are set.

Aucun commentaire:

Enregistrer un commentaire