A python documentation linter which checks that the docstring description matches the definition.

Related tags

linter documentation-tool
Overview

Build Status

Darglint

A functional docstring linter which checks whether a docstring's description matches the actual function/method implementation. Darglint expects docstrings to be formatted using the Google Python Style Guide, or Sphinx Style Guide, or Numpy Style Guide.

Feel free to submit an issue/pull request if you spot a problem or would like a feature in darglint.

Table of Contents:

Installation

To install darglint, use pip.

pip install darglint

Or, clone the repository, cd to the directory, and

pip install .

Configuration

darglint can be configured using a configuration file. The configuration file must be named either .darglint, setup.cfg, or tox.ini. It must also have a section starting with the section header, [darglint]. Finally, the configuration file must be located either in the directory darglint is 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 Configuration

If we would like to ignore ExcessRaiseErrors (because we know that an underlying function will raise an exception), then we would add its error code to a file named .darglint:

[darglint]
ignore=DAR402

We can ignore multiple errors by using a comma-separated list:

[darglint]
ignore=DAR402,DAR103

Instead 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.

[darglint]
ignore_regex=^_(.*)

Message Template Configuration

If we would like to specify a message template, we may do so as follows:

[darglint]
message_template={msg_id}@{path}:{line}

Which will produce a message such as [email protected]:72.

Finally, we can specify the docstring style type using docstring_style ("google" by default):

[darglint]
docstring_style=sphinx

Strictness Configuration

Strictness determines how lax darglint 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:

def double(x):
    # <docstring>
    return x * 2

Then 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

[darglint]
strictness=short

In your configuration file.

Ignoring common exceptions

We can specify a list of exceptions that don't need to be documented in the raises section of a docstring. For example,

[darglint]
ignore_raise=ValueError,MyCustomError

Logging

When darglint fails unexpectedly, you can try to gather more information when submitting a bug by running with logging. For example,

darglint --log-level=INFO unexpected_failures.py

Darglint accepts the levels, DEBUG, INFO, WARNING, ERROR, and CRITICAL.

Usage

Command Line use

Given a python source file, serializers.py, you would check the docstrings as follows:

darglint serializers.py

You can give an optional verbosity setting to darglint. For example,

darglint -v 2 *.py

Would 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 template

darglint -m "{path}:{line} -> {msg_id}" darglint/driver.py

Then we would get back error messages like

darglint/driver.py :61 -> DAR101

The 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 value message_template.

darglint is 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 invoke darglint as follows:

find . -name "*.py" | xargs darglint

Where I'm searching all files ending in ".py" recursively from the current directory, and calling darglint on each one in turn.

Ignoring Errors in a Docstring

You can ignore specific errors in a particular docstring. The syntax is much like that of pycodestyle, etc. It generally takes the from of:

# noqa: <error> <argument>

Where <error> is the particular error to ignore (DAR402, or DAR201 for 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:

def we_dont_want_a_returns_section():
  """Return the value, 3.

  # noqa: DAR201

  """
  return 3

We put the noqa anywhere 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 bound celery task.) Then we would do something like:

def a_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 a ZeroDivisionError. We could do the following:

def always_raises_exception(x):
    """Raise a zero division error or type error.o

    Args:
      x: The argument which could be a number or could not be.

    Raises:
      ZeroDivisionError: If x is a number.  # noqa: DAR402
      TypeError: If x is not a number.  # noqa: DAR402

    """
    x / 0

So, in this case, the argument for noqa is 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 Annotations

Darglint 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, Darglint only accepts types accepted by Python (see PEP 484.) That is, it does not accept parentheses in type signatures. (If parentheses are used in the type signature, Darglint will mark that argument as missing. See Issue #90.)

Error Codes

  • DAR001: The docstring was not parsed correctly due to a syntax error.
  • DAR002: An argument/exception lacks a description
  • DAR003: 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 specified
  • DAR105: 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 style
  • 100: Args section
  • 200: Returns section
  • 300: Yields section
  • 400: Raises section
  • 500: Variables section

You can enable disabled-by-default exceptions in the configuration file using the enable option. It accepts a comma-separated list of error codes.

[darglint]
enable=DAR104

Scope

Darglint'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. Darglint does not check stylistic preferences expressed by tools in the Python Code Quality Authority (through tools such as pydocstyle). So when using Darglint, it may be a good idea to also use pydocstyle, if you want to enforce style. (For example, pydocstyle requires the short summary to be separated from other sections by a line break. Darglint makes no such check.)

Sphinx

Darglint 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:

darglint -s sphinx example.py
darglint --docstring-style sphinx example.py

Alternatively, you can specify the style in the configuration file using the setting, "docstring_style":

[darglint]
docstring_style=sphinx

Numpy

Darglint now has an initial implementation for Numpy-style docstrings. Similarly to Sphinx-style docstrings, you can pass a style flag to the command:

darglint -s numpy example.py
darglint --docstring-style numpy example.py

Or set it in a configuration file:

[darglint]
docstring_style=numpy

The numpy parser and error reporter are not yet fully stabilized. Add issues or suggestions to the tracking bug, Issue #69.

Integrations

Flake8

Darglint can be used in conjunction with Flake8 as a plugin. The only setup necessary is to install Flake8 and Darglint in the same environment. Darglint will pull its configuration from Flake8. So, if you would like to lint Sphinx-style comments, then you should have docstring_style=sphinx in a Flake8 configuration file in the project directory. The settings would be entered under the flake8 configuration, not a separate configuration for Darglint. E.g.:

[flake8]
strictness=short
docstring_style=sphinx

To see which options are exposed through Flake8, you can check the Flake8 tool:

flake8 --help | grep --before-context=2 Darglint

SublimeLinter

A plugin for SublimeLinter can be found here

Pre-commit

Download pre-commit and install it. Once it is installed, add this to .pre-commit-config.yaml in your repository:

repos:
-   repo: https://github.com/terrencepreilly/darglint
    rev: master
    hooks:
    - id: darglint

Then run pre-commit install and you're ready to go. Before commiting, darglint will 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 .darglint, setup.cfg or tox.ini.

Roadmap

Below are some of the current features or efforts. Where a milestone or issue is associated with the idea, it will be mentioned. Some of these ideas are moonshots and may not get implemented. They are ordered roughly according to current priority/feasibility.

  • Expose command-line options through sphinx.
  • Robust logging for errors caused/encountered by darglint.
  • Check class docstrings (See Issue #25).
  • Autoformatting docstrings. (See 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 Contributions

Development Setup

Install darglint. First, clone the repository:

git clone https://github.com/terrencepreilly/darglint.git

cd into the directory, create a virtual environment (optional), then setup:

cd darglint/
virtualenv -p python3.6 .env
source .env/bin/activate
pip install -e .

You can install dependencies using

pip install poetry
poetry install

You can run the tests using

python setup.py test

Or, install pytest manually, cd to the project's root directory, and run

pytest

This project tries to conform by the styles imposed by pycodestyle and pydocstyle, as well as by darglint itself.

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 like

pushd docker-build
docker build -t darglint-34 -f Dockerfile.test34 .
popd
docker run -it --rm -v $(pwd):/code darglint-34 pytest

Contribution

If 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 darglint's parsing pipline.

Issues
  • Consistency with flake8-docstrings and flake8-rst-docstrings

    Consistency with flake8-docstrings and flake8-rst-docstrings

    There are quite popular tools to lint existing docstrings:

    • flake8-docstrings
    • flake8-rst-docstrings

    It would be awesome to have a note in the README if this project is compatible with them or not.

    It would be also awesome to include a test of some kind if they should be compatible.

    documentation 
    opened by sobolevn 12
  • Ignore return, yield and raises checks in abstractmethods

    Ignore return, yield and raises checks in abstractmethods

    Ignore some checks in abstract methods to avoid false positives.

    A function is considered abstract if it is decorated with @abstractmethod,
    and considered pure if it has "no implementation".
    
    Since Python does not have entirely empty functions, all functions which contain
    one of the following (and possibly a docstring) are considered empty
    
     - ... (Ellipsis)
     - pass
     - raise NotImplementedException
     - return NotImplementedException
     - only a docstring
    

    Closes #54

    opened by maltevesper 12
  • pre-commit hook is broken

    pre-commit hook is broken

    Support for pre-commit was merged in #43. However, I can't get it to work.

    When running pre-commit run --all-files (and not having darglint installed, yet), it fetches the darglint repository and installs it, but then errors out with:

    Executable darglint not found

    The requirements on the pre-commit project say:

    The hook repository must be installable via pip install . (usually by either setup.py or pyproject.toml). The installed package will provide an executable that will match the entry – usually through console_scripts or scripts in setup.py.

    I'm not really familiar with publishing a package, but indeed when I do pip install . in a clone of this repository, it does not install any darglint binary. Is there something wrong with how the project gets installed through pip?

    On a side-note: pre-commit reports the used version as 1.0.0a1, I guess it fetches this from pyproject.toml where it is specified as 1.0.0-alpha.1. Also, pre-commit says that darglint requires Python 3.7, which it probably also picks up from the dependencies in pyproject.toml. These should be corrected to match Python 3.5 as in setup.py, correct?

    All these issues are fixed when I delete the pyproject.toml file, which makes pip fall back to setup.py, which sets the correct version information and installs the darglint binary. Is the pyproject.toml file maybe not used anymore by this project?

    bug 
    opened by nioncode 10
  • Usage question: short docstring vs full-docstring

    Usage question: short docstring vs full-docstring

    Hi, thanks for this project! It is awesome!

    My question is about two different modes of docstrings that I use in my apps. I can either write a short one like:

    class SimpleViolation(BaseViolation):
        """Violation for cases where there's no associated nodes."""
    
        _node: None
    
        def __init__(self, node=None, text: Optional[str] = None) -> None:
            """Creates new instance of simple style violation."""
            super().__init__(node, text=text)
    

    Or full one like here:

    class BaseViolation(object):
        """
        Abstract base class for all style violations.
    
        It basically just defines how to create any error and how to format
        this error later on.
    
        Each subclass must define ``error_template`` and ``code`` fields.
    
        Attributes:
            error_template: message that will be shown to user after formatting.
            code: violation unique number. Used to identify the violation.
    
        """
    
        error_template: ClassVar[str]
        code: ClassVar[int]
    
        def __init__(self, node: ErrorNode, text: Optional[str] = None) -> None:
            """
            Creates new instance of abstract violation.
    
            Parameters:
                node: violation was raised by this node. If applied.
                text: extra text to format the final message. If applied.
    
            """
            self._node = node
            self._text = text
    

    Full source here: https://github.com/wemake-services/wemake-python-styleguide/blob/master/wemake_python_styleguide/violations/base.py

    The problem is that I get an error from the short version:

    ./wemake_python_styleguide/violations/base.py:168:1: I101 Missing parameter(s) in Docstring: - text
    ./wemake_python_styleguide/violations/base.py:168:1: I101 Missing parameter(s) in Docstring: - node
    

    What do I suggest? Allow short docstring (= docstrings without ANY arguments/returns/raises/etc declarations) or require to write a full one (in case ANY formatters are found). It might be a configuration option turned off by default.

    How does it sound to you?

    enhancement 
    opened by sobolevn 9
  • `darglint` overlaps with `flake8-pep3101` in some error codes

    `darglint` overlaps with `flake8-pep3101` in some error codes

    darglint overlaps with flake8-pep3101 in some error codes: https://github.com/gforcada/flake8-pep3101

    S001: Describes that something went wrong in parsing the docstring.
    S002: An argument/exception lacks a description.
    

    I suggest to use DAL, ARG, or any other three letter codes for issues. flake8 supports it and the overlap chance is minimal.

    bug 
    opened by sobolevn 8
  • Wrong expected type in numpy format

    Wrong expected type in numpy format

    In the following signature (using numpy mode), I get the error src/edges_cal/cal_coefficients.py:from_load_name:609: DAR103: ~load_name: expected str but was int

    Is this an instability in the numpy format?

    @classmethod
        def from_load_name(
            cls,
            load_name: str,
            direc: [str, Path],
            run_num: Optional[int] = None,
            filetype: Optional[str] = None,
            **kwargs,
        ):
            """Instantiate the class from a given load name and directory.
    
            Parameters
            ----------
            load_name : str
                The load name (one of 'ambient', 'hot_load', 'open' or 'short').
            direc : str or Path
                The top-level calibration observation directory.
            run_num : int
                The run number to use for the spectra.
            filetype : str
                The filetype to look for (acq or h5).
            kwargs :
                All other arguments to :class:`LoadSpectrum`.
    
            Returns
            -------
            :class:`LoadSpectrum`.
            """
    
    bug 
    opened by steven-murray 8
  • DAR402 wrongly reported on bare raise

    DAR402 wrongly reported on bare raise

    With this code, I get Excess exception(s) in Raises section: +r TypeErrorflake8(DAR402) with darglint 1.5.5 via flake8:

    """Test."""
    
    from somewhere import y, z
    
    
    def x():
        """Do stuff.
    
        Raises:
            TypeError: wrong type
        """
        try:
            y()
        except TypeError as err:
            z(err)
            raise
    

    I feel this is wrong, as I am inside of x() indeed re-raising TypeError.

    Related:

    • https://github.com/terrencepreilly/darglint/issues/102
    • https://github.com/terrencepreilly/darglint/commit/4c615c9d054f6f17ba75f210fc72c0e7490b7d9e
    bug 
    opened by fredrikaverpil 8
  • [BUG] Broken flake8 integration in v1.5.0

    [BUG] Broken flake8 integration in v1.5.0

    After upgrading, flake8 started reporting a lot of violations that are not reported when running it directly. It seems that it no longer respects its own config location when used with flake8

    bug 
    opened by webknjaz 7
  • DAR401 false positive

    DAR401 false positive

    
    
    def false_positive() -> None:
        """summary
    
        :raises ValueError: description
        """
        try:
            raise ValueError("233")
        except ValueError as e:
            raise e from None
    
    
    DAR401 Missing exception(s) in Raises section: -r e
    
    bug 
    opened by Trim21 7
  • Linting on functions with many arguments is unexpectedly slow

    Linting on functions with many arguments is unexpectedly slow

    Hi, I use darglint for pre-commits. I noticed that the pre-commit takes a lot of time when files containing function(s) with many arguments are staged.

    Seems to be the case that darglint spends a surprisingly long time when there are many arguments. On my own benchmarks, if the function has 3 arguments it takes 0.1 second to process it, whereas if it has 14 arguments it spends 4 seconds.

    Here's a (ugly) code snippet that reproduces the behaviour.

    import pathlib
    import time
    import subprocess
    
    
    def compile_function(n, filename):
        L = "".join([f"a{i}, " for i in range(n)])
        args = "\n        ".join([f"a{i}: some_type" for i in range(n)])
    
        s = f"""
    def f({L}):
        '''
        Args:
            {args}
    
        Returns:
            an int
        '''
        return 123"""
    
        pathlib.Path(filename).write_text(s)
    
    
    ####
    filename = "/tmp/def.py"
    for i in range(1, 25):
        compile_function(i, filename)
        t0 = time.time()
        subprocess.check_output(f"darglint {filename}", shell=True)
        t1 = time.time()
    
        print(f"Num arguments: {i:<2}     Time taken: {t1 - t0:.1f}")
    

    And then running python <the-snippet>, I get the following output:

    Num arguments: 1      Time taken: 0.1
    Num arguments: 2      Time taken: 0.1
    Num arguments: 3      Time taken: 0.1
    Num arguments: 4      Time taken: 0.2
    Num arguments: 5      Time taken: 0.3
    Num arguments: 6      Time taken: 0.4
    Num arguments: 7      Time taken: 0.7
    Num arguments: 8      Time taken: 0.9
    Num arguments: 9      Time taken: 1.2
    Num arguments: 10     Time taken: 1.6
    Num arguments: 11     Time taken: 2.0
    Num arguments: 12     Time taken: 2.6
    Num arguments: 13     Time taken: 3.2
    Num arguments: 14     Time taken: 4.0
    Num arguments: 15     Time taken: 4.8
    Num arguments: 16     Time taken: 5.8
    Num arguments: 17     Time taken: 6.9
    Num arguments: 18     Time taken: 8.1
    Num arguments: 19     Time taken: 9.5
    Num arguments: 20     Time taken: 10.8
    Num arguments: 21     Time taken: 12.6
    Num arguments: 22     Time taken: 14.3
    Num arguments: 23     Time taken: 16.1
    Num arguments: 24     Time taken: 18.5
    

    The function itself is super simple; it just adds a docstring where each argument is a some_type, and the function returns the number 123. I would expect this to run very fast (~0.1 seconds), for any number of arguments. However, with 20 arguments the processing time is a whooping 10 seconds.

    Is this behaviour expected? For reference, I use version 1.4.1 on darglint.

    question 
    opened by kvalv 6
  • Ignore methods and functions by decorator

    Ignore methods and functions by decorator

    We'd like the option to ignore functions marked with certain decorators. This is mostly useful for services and frameworks, where certain decorators can mark a function as a route or option, and the docstring has special meanings.

    enhancement 
    opened by bentheiii 1
  • DAR202, 302, and 402: Excess Return/Yield/Exception in protocol method

    DAR202, 302, and 402: Excess Return/Yield/Exception in protocol method

    I'm opening a new issue specifically for Protocols. A similar issue was made for abstract method, see #54, and has been fixed (though it's still open).

    A similar situation occurs when subclassing typing.Protocol. Typically, the method body of a protocol will be empty (or ...). Our team likes to document protocol methods since there are usually more references to protocols than to actual concrete classes in our code. This leads to a lot of false positives on DAR202 (Excess Returns), DAR302 (Excess Yield), and DAR402 (Excess exception) on these methods.

    I expect the fix would be similar to the one applied to abstract methods from #54. I haven't yet looked at the code, but I may be able to create a PR myself if it's not too complex ;)

    Edit: it also affects yield.

    opened by PhilMacKay 0
  • Question: What does darglint do that pylint.extensions.docparams does not?

    Question: What does darglint do that pylint.extensions.docparams does not?

    The README gives a useful overview of how darglint compares with pydocstyle and how it can be a complimentary part of a lint suite.

    I am curious whether the author/maintainers are aware of https://pylint.pycqa.org/en/latest/technical_reference/extensions.html#pylint-extensions-docparams and whether there are specific deficiencies/omissions that darglint seeks to address?

    opened by adamcunnington-gdt 0
  • Multiple returns

    Multiple returns

    When a function features multiple Returns/Yields they cannot be individually mentioned in the docstring like Parameters would (see code example below).

    def multiple_returns(a, b):
      """Multiple returns example.
    
      Parameters
      ----------
      a : int
          First integer
      b : int
          Second integer
    
      Returns
      -------
      diff : int
          b subtracted from a
      summation : int
          b added to a
      """
      diff = a - b
      summation = a + b
      return diff, summation
    

    Instead darglint raises an error DAR000: Unexpected exception in darglint: Multiple types should be combined into a Union. The error message indicates that the Returns docstring should be structured something like:

      Returns
      -------
      Union[int, int]
        Tuple containing:
          diff : int
              b subtracted from a
          summation : int
              b added to a
      """
    

    I don't think this is the neatest solution. Eventhough the return is a tuple, I would expect to be able to write a docstring for each individual returned variable. Can this functionality, like in the first example, be added (as an option) to darglint?

    enhancement 
    opened by kvanhespen 1
  • Add support for `pyproject.toml` for configuration

    Add support for `pyproject.toml` for configuration

    Add support for configuration using pyproject.toml, as specified in PEP 518.

    Inspired by both isort and mypy, I have resorted to the tomli package for parsing TOML files. As such, this PR introduces the first non-dev dependency to darglint.

    Closes #130.

    opened by sgraaf 1
  • Stray `DAR003` issue when using sphinx type docstring

    Stray `DAR003` issue when using sphinx type docstring

    Similar to #117, on darglint 1.8.0 I am getting a DAR003 issue on a docstring that does not look like has anything strange going for it and I am wondering what I am doing wrong with that. The code fragment is as follows:

    
    @pytest.fixture(scope="session")
    def ssh_output_path() -> Path:
        """Return the common path for output files created from tests.
    
        :returns: the output directory.
        :raise FileNotFoundError: if the found path does not exist.
        :raise NotADirectoryError: if the found path is not a directory.
        """
    
        path = Path("testoutput") / "test"
        check_directory_path(path)
        return path
    

    and I also checked that there isn't any other spurious whitespace lingering around:

    Screenshot 2021-07-23 at 01 17 16

    The darglint configuration is set to default except for the docstring style being sphinx and strictness being set to full.

    Interestingly the error message occurs on the first :raise line, with the same description as #117, "Incorrect indentation: ~<":

    
       205:   1 DAR003 Incorrect indentation: ~< [flake8-darglint]
      """Return the common path for output files created from tests.
    
        :returns: the output directory.
        :raise FileNotFoundError: if the found path does not exist.
        :raise NotADirectoryError: if the found path is not a directory.
        """
      ^
    

    Is there anything else I can try to see if this can be sorted out?

    Thanks!

    opened by agatti 0
  • Typo in docstring section name leads to confusing DAR101 errors

    Typo in docstring section name leads to confusing DAR101 errors

    Not sure if this is actually something that should be addressed by darglint, but I just ran into a very confusing issue where I had a typo in for the name of the "Parameters" section of my docstring (numpy docstring format). This made it so that darglint reported missing parameters (DAR101), which was very confusing, since my typo was not obvious ("Paramaters"), and the error made me focus on the parameter names themselves. I was wondering if maybe it would make sense to have darglint check for missing section headings to help clarify such scenarios?

    opened by taranlu-houzz 1
  • Support backticks for arguments in Sphinx style

    Support backticks for arguments in Sphinx style

    Given the following function:

    def key_if_required(key: str, required: bool = True) -> dict:
        """
        Check if key is required and return a dictionary.
    
        :param `key`: The name of the key to check
        :param `required`: Whether the key is required or not
        :returns: Dictionary
        """
        if key not in ["dogs", "cats"]:
            return {"default": key}
        return {"required": required}
    

    darglint will report these errors when using Sphinx formatting:

    test_me.py:key_if_required:4: DAR102: + `key`
    test_me.py:key_if_required:4: DAR102: + `required`
    test_me.py:key_if_required:4: DAR101: - key
    test_me.py:key_if_required:4: DAR101: - required
    

    The backticks are nice because they allow highlighting in editors. If there were an option to ignore backticks for arguments that would be great.

    image

    opened by kalibyrn 0
  • Bump py from 1.8.0 to 1.10.0 in /bin/bnf_to_cnf

    Bump py from 1.8.0 to 1.10.0 in /bin/bnf_to_cnf

    Bumps py from 1.8.0 to 1.10.0.

    Changelog

    Sourced from py's changelog.

    1.10.0 (2020-12-12)

    • Fix a regular expression DoS vulnerability in the py.path.svnwc SVN blame functionality (CVE-2020-29651)
    • Update vendored apipkg: 1.4 => 1.5
    • Update vendored iniconfig: 1.0.0 => 1.1.1

    1.9.0 (2020-06-24)

    • Add type annotation stubs for the following modules:

      • py.error
      • py.iniconfig
      • py.path (not including SVN paths)
      • py.io
      • py.xml

      There are no plans to type other modules at this time.

      The type annotations are provided in external .pyi files, not inline in the code, and may therefore contain small errors or omissions. If you use py in conjunction with a type checker, and encounter any type errors you believe should be accepted, please report it in an issue.

    1.8.2 (2020-06-15)

    • On Windows, py.path.locals which differ only in case now have the same Python hash value. Previously, such paths were considered equal but had different hashes, which is not allowed and breaks the assumptions made by dicts, sets and other users of hashes.

    1.8.1 (2019-12-27)

    • Handle FileNotFoundError when trying to import pathlib in path.common on Python 3.4 (#207).

    • py.path.local.samefile now works correctly in Python 3 on Windows when dealing with symlinks.

    Commits
    • e5ff378 Update CHANGELOG for 1.10.0
    • 94cf44f Update vendored libs
    • 5e8ded5 testing: comment out an assert which fails on Python 3.9 for now
    • afdffcc Rename HOWTORELEASE.rst to RELEASING.rst
    • 2de53a6 Merge pull request #266 from nicoddemus/gh-actions
    • fa1b32e Merge pull request #264 from hugovk/patch-2
    • 887d6b8 Skip test_samefile_symlink on pypy3 on Windows
    • e94e670 Fix test_comments() in test_source
    • fef9a32 Adapt test
    • 4a694b0 Add GitHub Actions badge to README
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • False-positive DAR301 for yielding function/method when using Sphinx-style docstrings

    False-positive DAR301 for yielding function/method when using Sphinx-style docstrings

    When a function/method uses yield, Darglint outputs an error as follows:

    DAR301: foo_function: Missing "Yields" in Docstring: - yield

    Though this is correct for e.g. Google-style docstrings, Sphinx itself doesn't support yields as a field name:

    https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#python-signatures

    The field names must consist of one of these keywords

    (Emphasis mine.)

    For Sphinx-style docstrings, the correct format for a yielding function/method AFAICS is:

    :returns: (description of returned iterator)

    And optionally (if type hints aren't being used):

    :rtype: Iterator

    opened by smithfred 1
Owner
Terrence Reilly
Terrence Reilly
OpenStack Hacking Style Checks. Mirror of code maintained at opendev.org.

Introduction hacking is a set of flake8 plugins that test and enforce the OpenStack StyleGuide Hacking pins its dependencies, as a new release of some

Mirrors of opendev.org/openstack 220 Oct 7, 2021
Unbearably fast O(1) runtime type-checking in pure Python.

Look for the bare necessities, the simple bare necessities. Forget about your worries and your strife. — The Jungle Book.

beartype 461 Oct 20, 2021
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 612 Oct 14, 2021
docstring style checker

pydocstyle - docstring style checker pydocstyle is a static analysis tool for checking compliance with Python docstring conventions. pydocstyle suppor

Python Code Quality Authority 823 Oct 14, 2021
A plugin for flake8 integrating Mypy.

flake8-mypy NOTE: THIS PROJECT IS DEAD It was created in early 2017 when Mypy performance was often insufficient for in-editor linting. The Flake8 plu

Łukasz Langa 103 Apr 27, 2021
A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

Jacob Deppen 108 Sep 26, 2021
Flake8 extension for checking quotes in python

Flake8 Extension to lint for quotes. Major update in 2.0.0 We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no

Zachary Heller 132 Oct 15, 2021
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 11.6k Oct 23, 2021
A static-analysis bot for Github

Imhotep, the peaceful builder. What is it? Imhotep is a tool which will comment on commits coming into your repository and check for syntactic errors

Justin Abrahms 217 Oct 11, 2021
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 1.7k Oct 23, 2021
Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 245 Sep 17, 2021
It's not just a linter that annoys you!

README for Pylint - https://pylint.pycqa.org/ Professional support for pylint is available as part of the Tidelift Subscription. Tidelift gives softwa

Python Code Quality Authority 3.6k Oct 23, 2021
A simple program which checks Python source files for errors

Pyflakes A simple program which checks Python source files for errors. Pyflakes analyzes programs and detects various errors. It works by parsing the

Python Code Quality Authority 1.1k Oct 18, 2021
Simple Python style checker in one Python file

pycodestyle (formerly called pep8) - Python style guide checker pycodestyle is a tool to check your Python code against some of the style conventions

Python Code Quality Authority 4.4k Oct 16, 2021
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 1.6k Oct 21, 2021
Flake8 plugin to find commented out or dead code

flake8-eradicate flake8 plugin to find commented out (or so called "dead") code. This is quite important for the project in a long run. Based on eradi

wemake.services 198 Oct 13, 2021
Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Predictive Analytics Lab 186 Sep 2, 2021
Naming Convention checker for Python

PEP 8 Naming Conventions Check your code against PEP 8 naming conventions. This module provides a plugin for flake8, the Python code checker. (It repl

Python Code Quality Authority 336 Oct 12, 2021
A static type analyzer for Python code

pytype - ?? ✔ Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 3.5k Oct 20, 2021