[Python-Dev] Experiences with Creating PEP 484 Stub Files (original) (raw)

Guido van Rossum guido at python.org
Wed Feb 10 13:15:02 EST 2016


On Wed, Feb 10, 2016 at 10:01 AM, Phil Thompson <phil at riverbankcomputing.com> wrote:

On 10 Feb 2016, at 5:52 pm, Guido van Rossum <guido at python.org> wrote: [...] That should do it, thanks. A followup question...

Is... def foo(bar: str = Optional[str]) ...valid? In other words, bar can be omitted, but if specified must be a str or None?

The syntax you gave makes no sense (the default value shouldn't be a type) but to do what your words describe you can do

def foo(bar: Optional[str] = ...): ...

That's literally what you would put in the stub file (the ... are literal ellipses).

In a .py file you'd have to specify a concrete default value. If your concrete default is neither str nor None you'd have to use cast(str, default_value), e.g.

_NO_VALUE = object() # marker

def foo(bar: Optional[str] = cast(str, _NO_VALUE)): ...implementation...

Now the implementation can distinguish between foo(), foo(None) and foo('').

-- --Guido van Rossum (python.org/~guido)



More information about the Python-Dev mailing list