Search code examples
mockingpython-sphinxautodocdefault-arguments

Default arguments using mocked objects


I am using Sphinx v1.8.5 to build documentation for Python 2 code that has external dependencies that I mock using autodoc_mock_imports. I get an error message when I try to use the mocked object (RAMP) as a default argument:

def foo(name, amp=RAMP):

The error says:

NameError: name 'RAMP' is not defined

If I do not use RAMP as a default argument, the error disappears. What am I doing wrong?


Solution

  • Ok, so thanks to the comment of @bad_coder I realised that the hurdle was stemming from how the modules were imported. I needed to resolve the scope with module_defining_RAMP.RAMP instead of directly accessing RAMP.

    Of course, then I got the ugly value of the mocked object in the output of my documentation:

    foo(name, amp=<sphinx.ext.autodoc.importer._MockObject object>)

    but I have already seen the solution to this problem while searching for my own. I needed to simply state the function signature in the doc string:

    def foo(name, amp=RAMP):
    """
    foo(name, amp=module_defining_RAMP.RAMP)
    """