0

How do I specify a type where a tuple could have any values with types I specified?

For example:

    def _get_writable_values(self, *, username: str, password: str) -> Tuple[WritableValue]:
        h = md5()
        h.update(username.encode(DEFAULT_ENCODING) + password.encode(DEFAULT_ENCODING))
        concatenated_hash = h.hexdigest()
        return (
            username,
            password,
            182,  # ???
            concatenated_hash,
            157,  # ???
        )

I get this error:

Expected type 'Tuple[Union[str, int, bytes]]', got 'Tuple[str, str, int, str, int]' instead.

WritableValue is defined like this:

WritableValue = Union[str, int, bytes]

I don't wanna override the type signature for every subclass, what's the correct signature for my use case?

  • Does this answer your question? [How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)](https://stackoverflow.com/questions/54747253/how-to-annotate-function-that-takes-a-tuple-of-variable-length-variadic-tuple) – Georgy Jun 17 '20 at 13:55

2 Answers2

0

Turns out you can use dots for that:

def _get_writable_values(self, *, username: str, password: str) -> Tuple[WritableValue, ...]:
0

in this case, you know what the Tuple is supposed to contain. The right thing would be for the function to declare that. If, at some point in the future, you accidentally change the type of one of the elements in the tuple you'd like to know about it as soon as possible - that it, in compile type (static code analysis) and not during run-time.

The solution I would therefore propose is the following:

def _get_writable_values(<arguments go here>) -> Tuple[str, str, int, str, int]:
    ...
Roy2012
  • 11,755
  • 2
  • 22
  • 35