On Wed, May 6, 2020 at 6:20 PM Louis St-Amour
In TypeScript "optional" works fine for naming the addition of null/etc. -- it isn't an issue because for JS, all arguments are optional if "undefined" is an allowed value and so TS requires all method arguments when "undefined" is not allowed. In TS, ? is shorthand for adding both null and undefined and allowing undefined is thus what makes it optional, no need to explicitly define a default value. This is described here: https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-def...
Thanks for bringing TypeScript into the conversation. I believe we can learn from it, but there are differences as you point out.
In Python, the other way we could work around this is if Optional[int] were given the additional behavior of assigning the default value of "None" implicitly if no other default value were specified:
def f(a: float, b: Optional[int]) -> float:
I agree this would be good, but it breaks the current rule that type annotations should not have effects at runtime (although there is a precedent in dataclasses, where the ClassVar "type" causes a class variable to be created, while other type hinted vars disappear at runtime unless they are initialized).
If "?" appended to a variable name could be defined similarly to Optional[int] as a shorthand for = None as well, you'd have even shorter syntax to express the intent of an "optional argument":
def f(a: float, b?: int) -> float:
and it would still be "optional" but with less typing...
Yep, I like that. From Guido's answer, I gather there is a preference to use a unary operator on the type, to reduce the impact on the parser, so that would be `b: ?int`. And if we want to prevent the type hint from having a runtime effect, it would be `b: ?int = None`. Still, better than the current situation, IMHO. For TypeScript, they created a transpiler so they could add syntax at will. We don't have that luxury in Python. Cheers, Luciano -- Luciano Ramalho | Author of Fluent Python (O'Reilly, 2015) | http://shop.oreilly.com/product/0636920032519.do | Technical Principal at ThoughtWorks | Twitter: @ramalhoorg