7

I'm using Sphinx to generate documentation from code. Does anyone know if there is a way to control the formatting of floating point numbers generated from default arguments.

For example if I have the following function:

def f(x = 0.97):
    return x+1

The generated documentation ends up looking like:

foo(x = 0.96999999999997)

Obviously this is a floating point precision issue, but is there a way to make the documentation not look so ugly?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ctrlc
  • 95
  • 1
  • 3

2 Answers2

1

You can override a function signature with the .. autofunction:: directive. So to address your example, a function defined as foo(x=0.97) in module bar:

.. automodule:: bar

   .. autofunction:: foo(x=0.97)

And the resulting doc will use the signature provided instead of the interpreted version with the really long number.

You can do this equivalently with .. autoclass:: and .. automethod:: and the like. This is usage is documented in "Options and advanced usage" in this part of the sphinx.ext.autodoc docs.

ddbeck
  • 3,855
  • 2
  • 28
  • 22
0

I haven't used Sphinx so I am not sure this will work, but my assumption is that repr() is used to determine the format of the documentation. You can try subclassing float with a custom __repr__ method that will return a nicer looking number to see if that helps:

class my_float(float):
    def __repr__(self):
        return str(self)

>>> float(0.97)
0.96999999999999997
>>> my_float(0.97)
0.97

>>> def foo(x = my_float(0.97)):
...     return x+1
... 
>>> foo()
1.97
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Thanks for the reply. I was really hoping for a documentation side solution that didn't include modifying the actual project source. – ctrlc Aug 31 '11 at 19:14