C#-style "as" casting syntactic sugar for type hints

This is some real code I wrote the other day: payload = { "birthDate": str(date.strftime('%m/%d/%Y')), ... } Due to the fact that date.strftime returns Any type, for my type hinting and autocomplete to work I either need to pass it to the str function or typing.cast(str, date). It would be nice if I could just write "birthDate": date.strftime(r'%m/%d/%Y') as str, like in C#. It's shorter, (in my opinion) more readable, and avoids having to unnecessarily call a constructor or import typing.cast. It's important to note that this would be syntactic sugar for typing.cast— it wouldn't call any constructor or affect program state, just increase the power of the type hinting system. Will Bradley

But doesn't date.strftime returns str not Any: https://github.com/python/typeshed/blob/main/stdlib/datetime.pyi#L75 ? Damian On Thu, Mar 23, 2023 at 10:00 PM Will Bradley <derivativedude123@gmail.com> wrote:

On Fri, 24 Mar 2023 at 13:02, Will Bradley <derivativedude123@gmail.com> wrote:
It would be nice if I could just write "birthDate": date.strftime(r'%m/%d/%Y') as str, like in C#.
I'm sure it would - for you. Unfortunately it would most definitely NOT be nice to write: with something as str: and then be unsure whether you're casting or assigning. Python's "as" keyword usually indicates a name binding ("import x as y", "except Exception as e", etc), not a type cast. Improve your type hinting upstream (by proper use of typeshed), to avoid the need for these casts. Needing to cast at time of call is usually a bad sign - it means that not only can you not figure out the type from the function call (normally the most common way to get typing information), you also can't figure it out from usage. ChrisA

But doesn't date.strftime returns str not Any: https://github.com/python/typeshed/blob/main/stdlib/datetime.pyi#L75 ? Damian On Thu, Mar 23, 2023 at 10:00 PM Will Bradley <derivativedude123@gmail.com> wrote:

On Fri, 24 Mar 2023 at 13:02, Will Bradley <derivativedude123@gmail.com> wrote:
It would be nice if I could just write "birthDate": date.strftime(r'%m/%d/%Y') as str, like in C#.
I'm sure it would - for you. Unfortunately it would most definitely NOT be nice to write: with something as str: and then be unsure whether you're casting or assigning. Python's "as" keyword usually indicates a name binding ("import x as y", "except Exception as e", etc), not a type cast. Improve your type hinting upstream (by proper use of typeshed), to avoid the need for these casts. Needing to cast at time of call is usually a bad sign - it means that not only can you not figure out the type from the function call (normally the most common way to get typing information), you also can't figure it out from usage. ChrisA
participants (3)
-
Chris Angelico
-
Damian Shaw
-
Will Bradley