Multi-line Python 2 function annotations

Mypy also supports a multi-line comment annotation syntax. Youcan provide a separate annotation for each argument using the variableannotation syntax. When using the single-line annotation syntaxdescribed above, functions with long argument lists tend to result inoverly long type comments and it’s often tricky to see which argumenttype corresponds to which argument. The alternative, multi-lineannotation syntax makes long annotations easier to read and write.

Here is an example (from PEP 484):

  1. def send_email(address, # type: Union[str, List[str]]
  2. sender, # type: str
  3. cc, # type: Optional[List[str]]
  4. bcc, # type: Optional[List[str]]
  5. subject='',
  6. body=None # type: List[str]
  7. ):
  8. # type: (...) -> bool
  9. """Send an email message. Return True if successful."""
  10. <code>

You write a separate annotation for each function argument on the sameline as the argument. Each annotation must be on a separate line. Ifyou leave out an annotation for an argument, it defaults toAny. You provide a return type annotation in the body of thefunction using the form # type: (…) -> rt, where rt is thereturn type. Note that the return type annotation contains literalthree dots.

When using multi-line comments, you do not need to prefix thetypes of your arg and **kwarg parameters with or **.For example, here is how you would annotate the first example usingmulti-line comments:

  1. from typing import List
  2.  
  3. class Example:
  4. def method(self,
  5. lst, # type: List[str]
  6. opt=0, # type: int
  7. *args, # type: str
  8. **kwargs # type: bool
  9. ):
  10. # type: (...) -> int
  11. """Docstring comes after type comment."""
  12. ...