On Tue, Mar 9, 2021 at 9:15 PM Ben Avrahami <avrahami....@gmail.com> wrote:
> 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
>

I'm hoping this is nothing more than a weak example, and it isn't
something you'd actually do in your code, because IMO this has bigger
problems than the type annotation - namely, the inconsistency of
actual type. I'd much rather write this as:

value = int(raw_value or 0)

and then it's consistently an integer. It'll still be usable the exact
same ways, but it's much easier to work with.

(Case in point, albeit not from Python: An API gave me back the
JavaScript "undefined" value in a context where I was expecting false
or 0, and it caused problems when I used it subsequently with
something that treated undefined as "toggle" instead of as true or
false. Was very annoying.)

ChrisA
_______________________________________________
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/S2HFPZR3G4PVLYCRH2S44PNIJESY3TDI/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to