What is the standard Sphinx documentation format for a method? - python

I am trying to document my method using a standard format, but in my search I found many "standard" ways of documenting methods. My method is:
#staticmethod
def validateMasterAttribute(attribute):
...
and according to this official Python documentation I should document it like this:
#staticmethod
def validateMasterAttribute(attribute):
""" Validate that the entered master attribute has all the required nodes
Keyword arguments:
attribute -- type lxml.etree._Element, it is the xml node for the master attribute
Return:
Nothing if the node contains all the required sub nodes. Otherwise, it throws a TagNotFoundException exception
"""
...
however, it is written in this question that I should document it like:
#staticmethod
def validateMasterAttribute(attribute):
"""
Validate that the entered master attribute has all the required nodes
:attribute: type lxml.etree._Element, it is the xml node for the master attribute
return: Nothing if the node contains all the required sub nodes. Otherwise, it throws a TagNotFoundException exception
"""
...
I also found another docstring format, which seems old. What is the format that Sphinx can parse and generate web pages from?

You might want to consult Documenting Your Project Using Sphinx.
Alternatively you can use Napoleon which is an extension supporting google syntax for doctrings.
Choose one. Be consistent.

Related

Sphinx typehinting shows full path to classes ant not links

I am currently working on a python project and want to automatically generate the documentation for my project
In order to automatically generate my documentation, I do:
sphinx-apidoc -f -o source ../modules
make html
But When I try to generate documentation via sphinx, the typehints are not shown properly, instead the full path to the class is shown:
In intelj it works perfectly fine though, here is the code:
from src.ConfiguratorOSMData.model import CalculationPhase, ConfigurationManager
class CalculationManager:
"""
The CalculationManager manages Calculation of the Project.
"""
def __init__(self, starting_point: CalculationPhase, configuration_manager: ConfigurationManager):
"""
Gets called when we first create an object of this class, it saves all information it needs for
starting a calculation.
Args:
starting_point: Describes in which calculation-phase we want to start the calculation.
configuration_manager: Saves all information required to configure the calculation.
"""
pass
def cancel_calculation(self):
"""
This method is used when we want to cancel an ongoing calculation.
"""
pass
def _validate_starting_point(self) -> bool:
"""
Validates the correctness of the Staring Point.
Returns:
bool: If true then the starting_point is valid, this means every calculation up to this point exist
and are saved in the project.
"""
pass
def _start_calculation(self):
"""
Starts the calculation.
"""
pass
I already added:
autodoc_typehints = "description"
add_module_names = False
and
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
'sphinx.ext.napoleon', # support for google docstring style
"sphinx_autodoc_typehints"
]
to the conf.py.
Can somebody help me, what am I doing wrong?

Combining Sphinx Autodoc with Manual documentation

I am currently working on a reference documentation that was initially documented manually with .. class:: All classes in the modules where documented this way.
However, it was necessary recently to allow some automation to the documentation, such as show-inheritance of each class, but the problem now is how to combine the current manual documentation with autodoc.
I have tried to just simply replace .. class:: with .. autoclass:: but this resulted in a output where the description and parameters descriptions that were manually typed into the documentation (as against being generated from docstrings) to not be rendered in the output. Can anyone advise on what to do to solve this?
So here is more details:
Take a look at this:
.. autoclass:: wagtail.blocks.CharBlock
:show-inheritance:
.. class:: CharBlock
A single-line text input. The following keyword arguments are accepted in addition to the standard ones:
:param required: If true (the default), the field cannot be left blank.
:param max_length: The maximum allowed length of the field.
:param min_length: The minimum allowed length of the field.
:param help_text: Help text to display alongside the field.
:param validators: A list of validation functions for the field (see `Django Validators <https://docs.djangoproject.com/en/stable/ref/validators/>`__).
:param form_classname: A value to add to the form field's ``class`` attribute when rendered on the page editing form.
The output:
enter image description here
The issue is I have to repeat the class name, which would be rather confusing for the user of the documentation. autoclass would not render the parameters, hence the need for class. I need autoclass to be able to show the inheritance of the class(Bases). So I don't know if there is a directive that can perform the functions of class without me having to mention the class name, or is there any way I can force class not to take in any arguments?
I hope this clearer. Thanks
It is possible to use autodoc for some things (in this case it's just :show-inheritance:) and "manual" documentation (content that does not come from a docstring) for others, within the same directive.
Remove .. class:: and ensure that all lines after the .. autoclass:: line have the same indentation. I think this should produce the output that you want.
.. autoclass:: wagtail.blocks.CharBlock
:show-inheritance:
A single-line text input. The following keyword arguments are accepted in addition to the standard ones:
:param required: If true (the default), the field cannot be left blank.
:param max_length: The maximum allowed length of the field.
:param min_length: The minimum allowed length of the field.
:param help_text: Help text to display alongside the field.
:param validators: A list of validation functions for the field (see `Django Validators <https://docs.djangoproject.com/en/stable/ref/validators/>`__).
:param form_classname: A value to add to the form field's ``class`` attribute when rendered on the page editing form.

Variable format changed to ~class.attribute in docs

So I've been working on some docs for some weeks now and they always appeared fine until last night all the variables started coming up in the format ~Class.Attribute. I attempted to rollback to multiple previous versions that had been working but they all show the Variables like this. Is there something I'm missing to get these to only show the attribute name without the ~Class..
class Certification(TMDbObj):
""" Represents a single Certification.
Attributes:
certification (str): Certification text.
meaning (str): Certification meaning.
order (int): Certification Order.
"""
This is a bug in the Sphinx napoleon extension it was reported in issue #10181 and will be fixed in the next Sphinx 4.5.0 release.
It happens for variables that aren't prefixed in the docstring with the class name or cls or self.

Looking for tips on building an XML parser derived from general file parser

I need to implement a parser class for XML files in python, and I'm required to make it a derived class from the following (incomplete) class.
class AbstractLogsParser(object):
# Different test statuses
TEST_RES_PASS = 0
TEST_RES_FAIL = 1
TEST_RES_SKIP = 2
def __init__(self, logs_extension):
"""
Base class constructor.
#param logs_extension Extension of log files to parse.
"""
self._logs_ext = '.'+logs_extension
def get_result_by_type(self, result_type):
"""
Returns number of passed, failed or skipped tests.
#param result_type Type of results to return.
"""
return -1
def generate_detailed_report(self):
"""
Generates detailed report on each test suite.
"""
raise Exception("generate_detailed_report is not implemented")
def process_logs(self, folder):
"""
Parses all log files with target extension in the specified folder. #param folder Folder to look up for log files.
"""
raise Exception("process_logs is not implemented")
The derived XML parser will have methods for different metrics and statistics, but it seems that the actual parsing needs to happen in the base class. Originally I wanted to use ElementTree to do this, but I can't see how to code the methods in the base class to accommodate the inherited XML parser class I need to build.
The AbstractLogsParser constructor takes the file extension as an argument, so the process_logs method needs to be able to parse files of different formats. Would it be smart to use regular expressions to parse the log files line by line, assuming that the keywords in the log files are always the same? I'm just looking for some tips on how to do the implementation well.
Here is an example of an XML log file the parser should handle.
<test_results test_suite="GAP_CONN_001">
<environment>LOCAL</environment>
<debug>Test suite start</debug>
<tc_result id="conn_bv_001" result="PASS">
<debug>Run 2 sequences</debug>
</tc_result>
<tc_result id="conn_bv_002" result="FAIL" />
<tc_result id="conn_bv_002" result="PASS" />
<tc_result id="conn_bv_004" result="SKIP">
<reason>No pass criteria</reason>
</tc_result>
</test_results>

Instantiate COM object that doesn't have ProgID by class/interface name

pywin32 docs for client-side COM show this basic way to instantiate COM objects:
obj = win32com.client.Dispatch("<ProgID>")
I'm trying to work with PersistentZoneIdentifier akin to Manipulating the zone identifier to specify where a file was download from – The Old New Thing - MSDN blogs. That class, as the registry at HKEY_CLASSES_ROOT\CLSID\{0968e258-16c7-4dba-aa86-462dd61e31a3} shows, doesn't have a corresponding ProgID.
I see that there's an underlying pythoncom.CoCreateInstance function that accepts a CLSID to instantiate and an IID to apparently query from it.
But this is inconvenient because I have to use unintelligible GUIDs instead of human-readable names.
The question is:
Is there a stock way in pywin32/underlying WinAPI to look up the aforementioned GUIDs by names? (do not suggest searching the registry by hand)
Or maybe some other way to instantiate that object with names?
What I tried and failed: win32com.client.IDispatch(<class/interface name>), pythoncom.IID(<class/interface name>). Also looked through the Net, MSDN and PyWin32 docs, of course.
There is no, and can't be any, "stock mechanism" to instantiate a class/query an interface by its name because their names aren't guaranteed to be unique, unlike GUIDs.

Categories