Docstrings & Type Hints - Python

  1. Which function header causes a SyntaxError?
    Answer: def f(x=5: int): The hint goes right after the parameter name and the default comes last: x: int = 5. Writing the default first, as in x=5: int, is a SyntaxError. Spaces around = with a hint are legal and recommended.
  2. Which expression gives the docstring of a function f?
    Answer: f.__doc__ Python stores a function's docstring in its __doc__ attribute, which is also what help(f) displays. f.__annotations__ holds the type hints, not the description.
  3. In a Python function, which of these is a docstring?
    Answer: A string literal as the first statement in the body Python stores a string literal as the docstring only when it is the first statement in the function body. A string written above the def line is not attached to the function, and # comments are ignored.

Start this quiz