I want to load credentials into my program from different sources. If one source does not have 'valid' credentials (in my case valid credentials are all tuples of two non empty strings), try the next source until you get a valid credential (or the sources run out).
I wrote a method (validate) that checks if credentials are valid and returns them if that is the case and None otherwise:
MaybeCredentials = Optional[Tuple[Optional[str], Optional[str]]]
def validate(credentials: MaybeCredentials) -> Optional[tuple[str, str]]:
if is_valid_credentials(credentials):
return credentials
return None
def is_valid_credentials(credentials: MaybeCredentials) -> bool:
return isinstance(credentials, tuple) and \
len(credentials) == 2 and \
is_valid_string(credentials[0]) and \
is_valid_string(credentials[1])
def is_valid_string(string: Optional[str]) -> bool:
return isinstance(string, str) and not string.strip() == ''
The code works perfectly fine (tests at the end), however when I check mypy, it shows this error:
Incompatible return value type (got "Optional[Tuple[Optional[str], Optional[str]]]", expected "Optional[Tuple[str, str]]")
for my validate method. How can I let mypy know that when is_valid_credentials returns true, credentials is of type tuple[str, str]?
Tests:
@pytest.mark.parametrize('credentials,expected', [
((), False),
(('',), False),
('', False),
(1, False),
(None, False),
((1, 2), False),
(('test', ''), False),
(('test', 1), False),
(('test', 'testpw'), True),
])
def test_is_valid_credentials(credentials, expected):
actual = is_valid_credentials(credentials)
assert actual == expected