On 9 Feb 2016, at 11:48 pm, Guido van Rossum
wrote: [Phil]
I found the documentation confusing regarding Optional. Intuitively it seems to be the way to specify arguments with default values. However it is explained in terms of (for example) Union[str, None] and I (intuitively but incorrectly) read that as meaning "a str or None" as opposed to "a str or nothing". [me] But it *does* mean 'str or None'. The *type* of an argument doesn't have any bearing on whether it may be omitted from the argument list by the caller -- these are orthogonal concepts (though sadly the word optional might apply to both). It's possible (though unusual) to have an optional argument that must be a str when given; it's also possible to have a mandatory argument that may be a str or None. [Phil] In the case of Python wrappers around a C++ library then *every* optional argument will have to have a specific type when given.
IIUC you're saying that every argument that may be omitted must still have a definite type other than None. Right? In that case just don't use Optional[]. If a signature has the form
def foo(a: str = 'xyz') -> str: ...
then this means that str may be omitted or it may be a str -- you cannot call foo(a=None).
You can even (in a stub file) write this as:
def foo(a: str = ...) -> str: ...
(literal '...' i.e. ellipsis) if you don't want to commit to a specific default value (it makes no difference to mypy).
So you are saying that a mandatory argument that may be a str or None would be specified as Union[str, None]?
Or as Optional[str], which means the same.
But the docs say that that is the underlying implementation of Option[str] - which (to me) means an optional argument that should be a string when given.
(Assuming you meant Option*al*.) There seems to be an utter confusion of the two uses of the term "optional" here. An "optional argument" (outside PEP 484) is one that has a default value. The "Optional[T]" notation in PEP 484 means "Union[T, None]". They mean different things.
Can you help improve the wording in the docs (preferably by filing an issue)?
When I eventually understand what it means...
I understand now. The documentation, as it stands, is correct and consistent but (to me) the meaning of Optional is completely counter-intuitive. What you suggest with str = ... is exactly what I need. Adding a section to the docs describing that should clear up the confusion. Thanks, Phil