How to specify that return value can either be str or None in the hinting

Viewed 710

For the below code, PyCharm displays 'Expected 'Tuple[str, str]', got 'Tuple[None, None]' instead.

def process(self) -> Tuple[str, str]:
    error_message = None
    report_type = None
    report_type_set = set()
    if not self.config_form.cleaned_data['type_check']:
        return report_type, error_message
    else:
        report_type, error_message = self._get_valid_value(report_type_set)
        return report_type, error_message

The method doesn't always return None, as you can see in the else block [ the method _get_valid_value makes sure we return str values for report_type and error_message]. So, how do I overcome this warning?

Is there a way to specify that it can either be str or None in the hinting?

2 Answers

Using Tuple[str, str], you are indicating that this method always returns a tuple of strings.

Instead you can use: def process(self) -> Tuple[Optional[str], Optional[str]]:

or alternatively: def process(self) -> Tuple[Union[str, None], Union[str, None]]:

It displays the warning because you have explicitly specified that it is returning only Tuple[str, str].

I would suggest you use Union to specify both the str and None cases, if you do not have other cases of data types returning:

def process(self) -> Tuple[Union[str, None], Union[str, None]]:
    error_message = None
    report_type = None
    report_type_set = set()
    if not self.config_form.cleaned_data['type_check']:
        return report_type, error_message
    else:
        report_type, error_message = self._get_valid_value(report_type_set)
        return report_type, error_message
Related