Hi all, I recently ran into a problem trying to adapt mypy into an older codebase, and it got me thinking about a potential addition to the typing library.
This idea comes in two parts (that can even be taken individually): the first is to allow the False singleton literal to be used in type annotations, much like how None is now allowed. False will in fact mean "any object for which the `not` operator will return True". The second part is to add a generic shorthand to the typing module: `typing.Maybe[T]`, that will evaluate to `Union[T, False]`. This will allow us to annotate the results of `and` and `or` operators more effectively. ``` raw_value : str = input() # suppose we want to convert raw_value to an int, but leave it as an arbitrary falsish value if raw_value is an empty string, we can now do this in the following ways: # annotate value as a union (type hint is misleading) value_union = raw_value and int(raw_value) # value: Union[str, int] inferred # annotate the value as optional on first assignment within an if clause (verbose, also type hint is confusing when assigning to a literal) # variants of this method include putting the first assignment in its own clause, or putting an empty variable declaration before any assignment, # but these are all just adding verbosity to what should be a very simple operation value_optional_clause: Optional[int] = None if raw_value: value_optional_clause = int(raw_value) # annotate as an optional, and use the ternary operator (unpythonic and overly verbose) value_ternary = int(raw_value) if raw_value else None # value: Optional[int] inferred # with the new typing.Literal class, we can explain the type of value precisely (it will require a cast however, and be very verbose) value_literal_union: Union[int, Literal['']] = cast(Union[int, Literal['']], raw_value and int(raw_value)) ``` Adding `typing.Maybe`/`False` will open up new possibilities and easier type inference when using the logical operators, at least the following: ``` # T0, T1 and T2 are typevars x : Maybe[T0] y : T1 z: T2 v = x or y # z: Union[T0, T1] inferred v = y and z # z: Maybe[T2] inferred if x: # x: T0 inferred ... if not y: # y: False inferred ... f: False if f: # unreachable code ... ``` Any thoughts?
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/FSMIOMMTXF36T2QHVG7HVTPGO3QO7U2O/ Code of Conduct: http://python.org/psf/codeofconduct/