Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to document structures in python?

If an argument to a function is expected to be a certain (or equivalent) structure, built using python's list, tuple and dict, how and where should it be documented?

An example documentation:

def foo(bar):
    """
    Args:
        bar: 2-tuple, ([(<mapping>,<number>), ...], <string>)
    """
    pass

A bit cumbersome; some problems:

  • the structure is hard to read
  • hard to indicate semantical meaning of each element of the structure
  • how to indicate not-fix length
  • should it only be documented once, or everywhere
  • edit: how to clearly show that duck-typing is ok for an element (ie. "dict" vs. "mapping-like")

edit: The example is not for trying to enforce types, it's trying to document a structure. For the point, duck typing is ok.

like image 313
n611x007 Avatar asked Feb 07 '13 17:02

n611x007


2 Answers

I ran into this problem a while back in my work. Based on my personal research (ie a decently thorough Google search) there is no standard for documenting complex, nested function arguments. I ended up inventing my approach, which uses <> to denote elements of the data structure, and each element gets its own header and paragraph in the docs. For example:

<options>
---------

A mapping:

  {'years':<years>,
   'states':<states>}

This is the root level of the `options` argument.

<years>
-------

A sequence of integers, each of which is a year to be included in the analysis.


<states>
--------

A sequence of strings, each of which is a state to be included in the analysis.

This documentation could be included in the doc strings for the function, but in my case I opted to break it out into a separate document. The approach can be extended to more complicated structures. See for example my docs here.

like image 197
ericstalbot Avatar answered Oct 09 '22 04:10

ericstalbot


My simple answer to your question is to quote the Zen of Python: "Explicit is better than implicit". In terms of your question, this means write out in full exactly what's needed, even if it takes an entire paragraph to document a single argument. Just read the python docs to see examples. In your specific case, you can indicate duck-typing by referring to a sequence rather than a tuple (see http://docs.python.org/2/library/collections.html#collections-abstract-base-classes).

like image 28
aquavitae Avatar answered Oct 09 '22 04:10

aquavitae