Am 17.12.21 um 13:50 schrieb Paul Moore:
On Fri, 17 Dec 2021 at 11:32, Sebastian Rittau <srittau@rittau.biz> wrote:
But "Optional" does *not* mean that you can "miss this out". (" = ..." means that in arguments like in rest of Python.) It means "you can provide an int or the value None". This is a common mistake and a good demonstration why "Optional" should be deprecated.
So how do I annotate the following function to say that callers can only pass an int, or omit the argument?
def my_fn(a=None): if a is None: a = <some complex calculation that I don't want to do in the function header>
def my_fn(a: int | None = None): ... The intention that the argument is optional is expressed by the "=" operator. None is a valid type here and the annotation above makes this explicit. The following are completely legal calls: f(None) f(some_dict.get("abc")) Using "Optional" to mark an argument could mean that the argument is optional and accepts None, but it can (and is) also used for non-optional arguments. On the other hand, there are optional arguments that can't be marked with "Optional", because they don't accept None. And finally there are optional arguments that accept None, but where None is not the default. typing.Optional and optional arguments are completely orthogonal concepts. - Sebastian