Package: darglint2
Darglint2A functional docstring linter which checks whether a docstring's
description matches the actual function/method implementation.Darglint2expects docstrings to be formatted using theGoogle Python Style Guide,
orSphinx Style Guide,
orNumpy Style Guide.Feel free to submit an issue/pull request if you spot a problem or
would like a feature indarglint2.Table of Contents:Project StatusInstallationConfigurationUsageScopeSphinxNumpyIntegrationsFlake8RoadmapContributionProject StatusThis is a renamed fork of the originaldarglintby@terrencepreilly, and I'm maintaining it
and accepting bugfixes.InstallationTo installdarglint2, use pip.pipinstalldarglint2Or, clone the repository,cdto the directory, andpipinstall.Configurationdarglint2can be configured using a configuration file.  The configuration
file must be named either.darglint2,.darglint,setup.cfg, ortox.ini.  It must
also have a section starting with the section header,[darglint2].
Finally, the configuration file must be located either in the directorydarglint2is called from, or from a parent directory of that working
directory.Currently, the configuration file allows us to ignore errors, to specify
message templates, to specify the strictness of checks and to ignore common
exceptions.Error ConfigurationIf we would like to ignoreExcessRaiseErrors (because we know that
an underlying function will raise an exception), then we would add its
error code to a file named.darglint2:[darglint2]ignore=DAR402We can ignore multiple errors by using a comma-separated list:[darglint2]ignore=DAR402,DAR103Instead of specifying error codes to ignore in general one can also specify a
regex to exclude certain function names from tests. For example, the following
configuration would disable linting on all private methods.[darglint2]ignore_regex=^_(.*)Message Template ConfigurationIf we would like to specify a message template, we may do so as
follows:[darglint2]message_template={msg_id}@{path}:{line}Which will produce a message such asDAR102@driver.py:72.Finally, we can specify the docstring style type usingdocstring_style("google" by default):[darglint2]docstring_style=sphinxStrictness ConfigurationStrictness determines how lax darglint2 will be when checking docstrings.
There are three levels of strictness available:short: One-line descriptions are acceptable; anything
more and the docstring will be fully checked.long: One-line descriptions and descriptions without
arguments/returns/yields/etc. sections will be allowed.  Anything more,
and the docstring will be fully checked.full: (Default) Docstrings will be fully checked.For example, if we have the following function:defdouble(x):# <docstring>returnx*2Then the following table describes which errors will be raised for
each of the docstrings (rows) when checked against each of the
configurations (columns):┌──────────────────────────────┬──────────────────┬────────────────┬──────────────────┐
│ Docstring                    │  short           │  long          │  full            │
├──────────────────────────────┼──────────────────┼────────────────┼──────────────────┤
│ """Doubles the argument."""  │ None             │ None           │ Missing argument │
│                              │                  │                │ Missing return   │
│                              │                  │                │                  │
│                              │                  │                │                  │
├──────────────────────────────┼──────────────────┼────────────────┼──────────────────┤
│ """Doubles the argument.     │ Missing argument │ None           │ Missing argument │
│                              │ Missing return   │                │ Missing return   │
│ Not very pythonic.           │                  │                │                  │
│                              │                  │                │                  │
│ """                          │                  │                │                  │
│                              │                  │                │                  │
├──────────────────────────────┼──────────────────┼────────────────┼──────────────────┤
│ """Doubles the argument.     │ Missing return   │ Missing return │ Missing return   │
│                              │                  │                │                  │
│ Args:                        │                  │                │                  │
│     x: The number to double. │                  │                │                  │
│                              │                  │                │                  │
│ """                          │                  │                │                  │
└──────────────────────────────┴──────────────────┴────────────────┴──────────────────┘In short, if you want to be able to have single-line docstrings, and check
all other docstrings against their described parameters, you would specify[darglint2]strictness=shortIn your configuration file.Ignoring common exceptionsWe can specify a list of exceptions that don't need to be documented in the
raises section of a docstring. For example,[darglint2]ignore_raise=ValueError,MyCustomErrorLoggingWhendarglint2fails unexpectedly, you can try to gather more
information when submitting a bug by running with logging.
For example,darglint2--log-level=INFOunexpected_failures.pyDarglint2accepts the levels,DEBUG,INFO,WARNING,ERROR, andCRITICAL.UsageCommand Line useGiven a python source file,serializers.py, you would check the docstrings
as follows:darglint2serializers.pyYou can give an optional verbosity setting todarglint2.  For example,darglint2-v2*.pyWould give a description of the error along with information as to this
specific instance.  The default verbosity is 1, which gives the filename,
function name, line number, error code, and some general hints.To use an arbitrary error format, you can pass a message template, which
is a python format string.  For example, if we pass the message
templatedarglint2-m"{path}:{line} -> {msg_id}"darglint2/driver.pyThen we would get back error messages likedarglint2/driver.py:61->DAR101The following attributes can be passed to the format string:line: The line number,msg: The error message,msg_id: The error code,obj: The function/method name,path: The relative file path.The message template can also be specified in the configuration file
as the valuemessage_template.darglint2is particularly useful when combined with the utility,find.
This allows us to check all of the files in our project at once.  For example,
when eating my own dogfood (as I tend to do), I invokedarglint2as follows:find.-name"*.py"|xargsdarglint2Where I'm searching all files ending in ".py" recursively from the
current directory, and callingdarglint2on each one in turn.Ignoring Errors in a DocstringYou can ignore specific errors in a particular docstring.  The syntax
is much like that ofpycodestyle, etc.  It generally takes the from
of:# noqa: <error> <argument>Where<error>is the particular error to ignore (DAR402, orDAR201for example), and<argument>is what (if anything) the ignore
statement refers to (if nothing, then it is not specified).Let us say that we want to ignore a missing return statement
in the following docstring:defwe_dont_want_a_returns_section():"""Return the value, 3.# noqa: DAR201"""return3We put thenoqaanywhere in the top level of the docstring.
However, this won't work if we are missing something more specific,
like a parameter.  We may not want to ignore all missing parameters,
either, just one particular one.  For example, we may be writing a
function that takes a class instance as self. (Say, in a boundcelerytask.) Then we would do something like:defa_bound_function(self,arg1):"""Do something interesting.Args:arg1: The first argument.# noqa: DAR101 arg1"""arg1.execute(self)So, the argument comes to the right of the error.We may also want to mark excess documentation as being okay.  For example,
we may not want to explicitly catch and raise aZeroDivisionError.  We
could do the following:defalways_raises_exception(x):"""Raise a zero division error or type error.oArgs:x: The argument which could be a number or could not be.Raises:ZeroDivisionError: If x is a number.  # noqa: DAR402TypeError: If x is not a number.  # noqa: DAR402"""x/0So, in this case, the argument fornoqais really all the way to
the left.  (Or whatever description we are parsing.)  We could also
have put it on its own line, as# noqa: DAR402 ZeroDivisionError.Type AnnotationsDarglint2 parses type annotations in docstrings, and can, optionally,
compare the documented type to the actual type annotation.  This can
be useful when migrating a codebase to use type annotations.In order to make these comparisons, Darglint2 only accepts types
accepted by Python (seePEP 484.)
That is, it does not accept parentheses in type signatures. (If
parentheses are used in the type signature, Darglint2 will mark that
argument as missing.  See Issue #90.)Error CodesDAR001: The docstring was not parsed correctly due to a syntax error.DAR002: An argument/exception lacks a descriptionDAR003: A line is under-indented or over-indented.DAR004: The docstring contains an extra newline where it shouldn't.DAR005: The item contains a type section (parentheses), but no type.DAR101: The docstring is missing a parameter in the definition.DAR102: The docstring contains a parameter not in function.DAR103: The docstring parameter type doesn't match function.DAR104: (disabled) The docstring parameter has no type specifiedDAR105: The docstring parameter type is malformed.DAR201: The docstring is missing a return from definition.DAR202: The docstring has a return not in definition.DAR203: The docstring parameter type doesn't match function.DAR301: The docstring is missing a yield present in definition.DAR302: The docstring has a yield not in definition.DAR401: The docstring is missing an exception raised.DAR402: The docstring describes an exception not explicitly raised.DAR501: The docstring describes a variable which is not defined.The number in the hundreds narrows the error by location in the docstring:000: Syntax, formatting, and style100: Args section200: Returns section300: Yields section400: Raises section500: Variables sectionYou can enable disabled-by-default exceptions in the configuration file
using theenableoption.  It accepts a comma-separated list of error
codes.[darglint2]enable=DAR104ScopeDarglint2's primary focus is to identify incorrect and missing documentationd
of a function's signature. Checking style is a stretch goal, and is supported
on a best-effort basis.  Darglint2 does not check stylistic preferences expressed
by tools in the Python Code Quality Authority (through tools such aspydocstyle).
So when using Darglint2, it may be a good idea to also usepydocstyle, if you
want to enforce style.  (For example,pydocstylerequires the short summary
to be separated from other sections by a line break.  Darglint2 makes no such check.)SphinxDarglint2 can handle sphinx-style docstrings, but imposes some restrictions
on top of the Sphinx style. For example, all fields (such as:returns:)
must be the last items in the docstring.  They must be together, and all
indents should be four spaces.  These restrictions may be loosened at a
later date.To analyze Sphinx-style docstrings, pass the style flag to the command:darglint2-ssphinxexample.py
darglint2--docstring-stylesphinxexample.pyAlternatively, you can specify the style in the configuration file using
the setting, "docstring_style":[darglint2]docstring_style=sphinxNumpyDarglint2 now has an initial implementation for Numpy-style docstrings.
Similarly to Sphinx-style docstrings, you can pass a style flag to the
command:darglint2-snumpyexample.py
darglint2--docstring-stylenumpyexample.pyOr set it in a configuration file:[darglint2]docstring_style=numpyThe numpy parser and error reporter are not yet fully stabilized.
Add issues or suggestions to the tracking bug, Issue #69.IntegrationsFlake8Darglint2 can be used in conjunction with Flake8 as a plugin.  The only
setup necessary is to install Flake8 and Darglint2 in the same environment.
Darglint2 will pull its configuration from Flake8. So, if you would like to
lint Sphinx-style comments, then you should havedocstring_style=sphinxin a
Flake8 configuration file in the project directory.  The settings would
be entered under the flake8 configuration, not a separate configuration
for Darglint2.  E.g.:[flake8]strictness=shortdocstring_style=sphinxTo see which options are exposed through Flake8, you can check the Flake8
tool:flake8--help|grep--before-context=2Darglint2SublimeLinterA plugin for SublimeLinter can be foundhere.
Note that it was built for the originaldarglint, notdarglint2, and its
compatibility withdarglint2is yet to be verified.Pre-commitDownloadpre-commitandinstallit. Once it is installed, add this
to.pre-commit-config.yamlin your repository:repos:-repo:https://github.com/akaihola/darglint2rev:masterhooks:-id:darglint2Then runpre-commit installand you're ready to go. Before commiting,darglint2will be run on the staged files. If it finds any errors, the user
is notified and the commit is aborted. Store necessary configuration (such as
error formatting) in.darglint2,.darglint,setup.cfgortox.ini.RoadmapBelow are some of the features or efforts from the originaldarglintproject
at the time of forking in February 2023.  Where a milestone or
issue is associated with the idea, it will be mentioned.  Some of these
ideas were moonshots and may not get implemented.  They are ordered
roughly according to priority/feasibility stated by the original author.Expose command-line options through sphinx.Robust logging for errors caused/encountered bydarglint2.Check class docstrings (Seedarglint#25).Autoformatting docstrings. (Seedarglint milestone #3).Optional aggressive style checking through command line flag.ALE support.Syntastic support. (Syntastic is not accepting new checkers until
their next API stabilizes, so this may take some time.)Development and ContributionsDevelopment SetupInstalldarglint2. First, clone the repository:gitclonehttps://github.com/akaihola/darglint2.gitcdinto the directory, create a virtual environment (optional), then setup:cddarglint2/
virtualenv-ppython3.6.envsource.env/bin/activate
pipinstall-e.You can install dependencies usingpipinstallpoetry
poetryinstallYou can run the tests usingpythonsetup.pytestOr, installpytestmanually,cdto the project's root directory,
and runpytestThis project tries to conform by the styles imposed bypycodestyleandpydocstyle, as well as bydarglint2itself.A dockerfile exists for testing with Python3.4.  Although it's not
officially supported (only 3.6+), it's nice to try to make minor
version numbers support it.  You would build the dockerfile and
test using something likepushddocker-build
dockerbuild-tdarglint2-34-fDockerfile.test34.popddockerrun-it--rm-v$(pwd):/codedarglint2-34pytestContributionIf you would like to tackle an issue or feature, email me or comment on the
issue to make sure it isn't already being worked on.  Contributions will
be accepted through pull requests.  New features should include unit tests,
and, of course, properly formatted documentation.Also, check out the wiki prior to updating the grammar.  It includes a
description of darglint2's parsing pipline.