4

Python3 has an annotation feature. Should I use it instead documentations string? I. e. what is the right way:

def func(points: [{'x': int, 'y': int}]): -> int
    pass

vs

def func(points):
    ''' Take a list of dicts, dict present a point, and contain keys:
    'x' - int, x position
    'y' - int, y position
    Return int

    '''
    pass
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Dmitriy
  • 1,898
  • 1
  • 15
  • 24
  • There's no hard and fast rule. There's good libraries out there that will happily use doc strings/functions to generate docs (eg: Sphinx) but if you're using them for documentation, you can't really use them for other stuff such as constraint checking... It's mostly just a case of, if you're going to use them, pick how you're going to use them and be consistent. See http://stackoverflow.com/questions/3038033/what-are-good-uses-for-python3s-function-annotations for other uses... – Jon Clements Oct 21 '13 at 14:48
  • Why don't you use both? – OdraEncoded Oct 21 '13 at 15:17
  • Sometimes a lot of documentations is excess. So annotations - way to shorten comments, I think. – Dmitriy Oct 21 '13 at 15:33

1 Answers1

1

No, they are an addition to docstrings. From the official function annotations pep:

Because Python's 2.x series lacks a standard way of annotating a function's
parameters and return values, a variety of tools and libraries have appeared to
fill this gap.

But the Python community likes standartizing things (ref. PEPs). So they came up with the function annotations, which are primarily targeted at third-party libraries and tools - IDEs, code quality / static analysis tools and etc. As the PEP says itself:

By itself, Python does not attach any particular meaning or significance to
annotations.(...)meaning comes from third-party libraries alone.

Edit: A really good article about uses of annotations (early error detection, code completion and tooling support in general) can be found here.