0

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.

2
  • 3
    As the PEP you link to says: "annotations always precede a parameter's default value" Commented May 12, 2014 at 15:00
  • Ah, missed that sentence. Not clear on the downvote though. Commented May 12, 2014 at 15:01

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.