Domanda

From PEP 3107, http://www.python.org/dev/peps/pep-3107/#parameters, I've just noticed some extra syntax for function annotations that I wasn't aware of and don't quite understand.

def foo(a: expression, b: expression = 5):
    ...

It's the second portion that I am uncertain about, expression = 5. How would you use that in a practical sense? Surely not to specify a default argument, which would already be self-evident.

È stato utile?

Soluzione

The = 5 is not part of the annotation. It is the default value for a keyword argument here.

If you strip the annotations, what you have is:

def foo(a, b = 5):

From the Function definition grammar:

parameter      ::=  identifier [":" expression]
defparameter   ::=  parameter ["=" expression]

where defparameter is a parameter in a function definition; the "=" expression follows parameter, and the definition for parameter includes the ":" expression section that defines an annotation.

Quoting the original proposal, PEP 3107:

Annotations for parameters take the form of optional expressions that follow the parameter name:

def foo(a: expression, b: expression = 5):
    ...

In pseudo-grammar, parameters now look like identifier [: expression] [= expression]. That is, annotations always precede a parameter's default value and both annotations and default values are optional.

Emphasis mine.

Altri suggerimenti

It's a default value of the param 'b'.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top