Code Monkey home page Code Monkey logo

docformatter's People

Contributors

actions-user avatar akbiggs avatar alecmerdler avatar antoined avatar asherf avatar asottile avatar benjaminschubert avatar dabauxi avatar eford36 avatar github-actions[bot] avatar hayd avatar howeaj avatar humitos avatar icp1994 avatar jonashaag avatar kapsh avatar kianmeng avatar korverdev avatar kotlinisland avatar lli-fincad avatar mcflugen avatar myint avatar oliversieweke avatar pacu2 avatar photonios avatar serhiy-yevtushenko avatar weibullguy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docformatter's Issues

Bug: Multi-line summary has closing quotes on the same line

Docformatter's readme states that it follows the following PEP 257 item:

Unless the entire docstring fits on a line, place the closing quotes on a line by themselves.

But it doesn't; it only places the closing quotes on a line by themselves if there is a description (or if the option --make-summary-multi-line is specified, but then it puts the opening quotes on a separate line too)

i.e. with default arguments it formats this:

"""Loooooooooooooooooooooooooooooooooong summary line that will get wrapped to multiple lines."""

to this:

"""Loooooooooooooooooooooooooooooooooong summary line that will get
wrapped to multiple lines."""

when it should instead format to this:

"""Loooooooooooooooooooooooooooooooooong summary line that will get
wrapped to multiple lines.
"""

I have problem

Hello,

When I want to use I get an error:
The Python path set in the "python.pythonPath" setting is invalid or points to Python 2. Check the value or clear the setting to use the global Python installation. The extension is not compatible with Python 2.

settings.json:
"python.jediEnabled": false,
"[python]": {
"editor.defaultFormatter": "iansan5653.format-python-docstrings"
}
System: Ubuntu 19.10

Breaks on RST XML code blocks

Hi, thanks for this tool.

I've run across what looks like a bug.

Given the docstring:

    """
    .. code-block:: XML

        <xs:element name="regulation.group" substitutionGroup="abstract.record">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="regulation.group.id" type="RegulationGroupId"/>
                    <xs:element name="validity.start.date" type="Date"/>
                    <xs:element name="validity.end.date" type="Date" minOccurs="0"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    """

Docformatter formats this to:

    """
    .. code-block:: XML.

    <xs:element name="regulation.group" substitutionGroup="abstract.record">
    <xs:complexType>         <xs:sequence>             <xs:element
    name="regulation.group.id" type="RegulationGroupId"/>
    <xs:element name="validity.start.date" type="Date"/>             <xs:element
    name="validity.end.date" type="Date" minOccurs="0"/>         </xs:sequence>
    </xs:complexType> </xs:element>
    """

Which is obviously wrong. I don't see any issues with my documentation (https://www.sphinx-doc.org/en/1.5/markup/code.html#directive-code-block). Is there a suggested fix for this? Or does it need some work.

Do not add period if the summary is formatted as titles in markdown

Currently, if a summary is formatted using markdown as a title such as "# This is a title", it will be formatted as "# This is a title." with a period added at the end of the sentence. It would be nice that a period won't be added if the summary is started with "#"

""" Leading summary whitespace (as in this issue title)."""

For better readability, some people prefer inserting a space between the triple quotes """ and the summary text:

def is_ascii(text):
    """ Checks if contains only ASCII characters."""
    return all(ord(letter) < 128 for letter in text)

The leading whitespace:

       🡇
    """ Checks if contains only ASCII characters."""

Without that whitespace:

    """Checks if contains only ASCII characters."""

We may add an option --leading-summary-space or --pre-summary-space or --space-before-summary or --space-after-triple-quotes... What option name do you prefer?

Attention, this option has no effect on multi-lines docstring when --pre-summary-newline is used.

Thanks

Document the ability to turn off wrapping

I couldn't understand why there wasn't an option to turn off wrapping: it was making a mess of the code I'm working with. It seems like an obvious thing to have. I had to dig into the code to figure out that --wrap-summaries 0 and --wrap-descriptions 0 accomplish this. Maybe it'd be good to document this functionality?

Handle raw docstrings

I often write math formulas in my docstrings via LaTeX, which makes heavy use of backslashes. In such docstrings, in order to avoid escaping my backslashes, I use the r prefix to declare a raw string. For example,

def example():
    r"""The integral of :math:`x` is :math:`\int x\, dx`."""
    pass

Such docstrings are unfortunately not currently supported by the docformatter parsing logic. Would it be possible to add support? Thanks!

Bug: `--wrap-summaries 0` doesn't disable summaries wrapping

Rather than disabling wrapping of summaries, --wrap-summaries 0 has the same behaviour as --wrap-summaries 999, which is to unwrap the summary to be on one line.

This conflicts with the documentation of --wrap-summaries and the behaviour of --wrap-descriptions 0, which correctly leaves the wrapping of descriptions alone completely.

Fixing this would make this package usable for people who don't want the autoformatter to touch their wrapping, while the original behaviour is still available using --wrap-summaries 999

Collaboration

Hi, I made http://github.com/halst/pep257 project and as my next step I planned, to make an "autopep257" project. However, as I can see, you already way ahead of me ;-). You have a solid ground—what is your plan?

I'm interested to help with docs, code and API design.

Automatic wrapping and force wrapping issues

Long descriptions are not being wrapped as expected.

When I use the --force-wrap option the entire docstring is properly wrapped but a Sphinx param is also wrapped which is undesirable.

Usage:

  • docformatter v1.4 inside PyCharm
  • invoked as an external tool with the following command line
  • docformatter --force-wrap --wrap-descriptions 72 --wrap-summaries 79 --in-place --range 1014 1019 myfile.py

Here's a screenshot of the before:
image

Here's a screenshot after running docformatter:
image
Note that the description was not line-wrapped.

Here's a screenshot after running docformatter with the --force-wrap option:
image
Note that the description was line-wrapped but the Sphinx param was also wrapped.

add a line range argument

Thought I'd ask! ;)

Happy to help put something together (at some point)...

(ps I totally hadn't realised about PEP257 until you commented on my autopep8 PR! I thought the standard was """\n...)

Add a `--exit` flag to see if files changed

I'd like to use docformatter in my pre-commit hooks, and i want it to format my docstring when pre commit hook called, so i use -i flag in my config.

(If --check flag, I have to manually format it again after hooks failure, seems unnecessary)

But i found that exit code is always 0 even it has changed file content, and --check flag can't be used with -i flag.

Is there any possibility to add a --exit flag or something to let docformatter exit with not 0 when docformatter changed file content?

Publish a tag

I was wondering if a tag could be created for a commit at 88b3a19 (or later). I'm using docformatter with pre-commit and I can point my config to use docformatter at 88b3a19, but if I could instead point to a tag, then pre-commit autoupdate would be able to pull in new updates as new releases/tags are published. Thanks!

Remove whitespaces in blank lines to be compliant with PEP 8

If a docstring contains a blank line with whitspaces docformatter does not remove them. This does violate the a PEP 8 rule and pycodestyle.py raises "W293 blank line contains whitspaces".

FYI: I'm using YAPF first and then docformatter. Since YAPF leaves docstrings as they are, it's up to docformatter to fix it.

Add a `--check` flag to see if changes would be made.

I'd find it useful if this had a --check-like flag which doesn't modify the code but simply returns whether or not changes would be made (and returns an appropriate error code).

The motivation here is that the return code can be hooked up to test integration.

Other popular python formatters have some form of this kind of flag:
https://github.com/ambv/black

  --check                     Don't write the files back, just return the
                              status.  Return code 0 means nothing would
                              change.  Return code 1 means some files would be
                              reformatted.  Return code 123 means there was an
                              internal error.

https://github.com/timothycrosley/isort

Using isort to verify code
The --check-only option
isort can also be used to used to verify that code is correctly formatted by running it with -c. Any files that contain incorrectly sorted and/or formatted imports will be outputted to stderr.

isort **/*.py -c -vb

SUCCESS: /home/timothy/Projects/Open_Source/isort/isort_kate_plugin.py Everything Looks Good!
ERROR: /home/timothy/Projects/Open_Source/isort/isort/isort.py Imports are incorrectly sorted.
One great place this can be used is with a pre-commit git hook, such as this one by @acdha:

https://gist.github.com/acdha/8717683

This can help to ensure a certain level of code quality throughout a project

Thanks!

--exclude flag

Hello,
I'm quite new to Github and all so forgive me if this is not the right section for this kind of problem.

I want to use docformatter for my project, I installed it with pip and everything works fine.
My only problem is that I can't use the --exclude/-e flag, I saw that it was commited to this repository but I have no clue how to access it from here. Would love if somebody could help me out with this.

With kind regards,
Can

""" getting placed at end of comment line instead of its own line

docformatter is resulting in this diff:

-    """
-    return a map mapping appliance_ids for a house back to themselves
-    except for multiphase appliances
-    """
+    """return a map mapping appliance_ids for a house back to themselves except
+    for multiphase appliances."""

I'm ok with putting the word return immediately after the triple quotes, but shouldn't the final set of triple quotes be on their own line?

Doc formatter reformats correct docstring

with docformatter 1.4, command docformatter --wrap-summaries 100 --wrap-descriptions 100
the following docstring

"""hello yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeet -v
"""

gets transformed to

"""hello yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeet
-v."""

which is fine (correct), but then if I run docformatter again, the correct string incorrectly becomes

"""hello yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeet.

-v.
"""

Readme example does not produce the expected result

In the readme, an example using the syntax docformatter --in-place example.py is used, and suggests that

def launch_rocket():
    """Launch
the
rocket. Go colonize space."""

is autoformatted to

def launch_rocket():
    """Launch the rocket.

    Go colonize space.
    """

. This is not the case unless one runs docformatter --in-place --force-wrap example.py (this function is unchanged). As far as I can tell this happens due to the use heuristic ratio detection in is_some_sort_of_list

This isn't exactly a problem as one can just enable the flag, but may be worth making that explicit in the example. Not sure if there could be a better solution (maybe the first line of a docstring shouldn't be parsed as a list?) but I'm a new user so not sure what the desired behaviour should be.

New Release of Docformatter - no support of -c (--check) in release 1.1

Although documentation on site shows, that docformater supports check flag, the latest release of the docformatter (v 1.1. does not suppport this flag.) This makes it imposible for me to use docformatter on CI to check, whether some file need to be reformatted by docformatter, although such functionality is supported according to documentation.

Therefore, having a new version /release with support of this functionality would be of great help

New release

First of all thanks a lot! docformatter is a great tool.

Can the new version of docformatter be released, I'm particularly very interested in #44.

Thanks!

Bug: Docformatter incorrectly detects first line as a docstring

Consider this unfortunate construction:

def _send_notification(line):
    'email' in line and send_notification(line['email'])

docformatter changes it to:

 def _send_notification(line):
    """email.""" in line and send_notification(line['email'])

I think it should remain unchanged.

Docformatter breaks lines inside RST cross-references

Docformatter breaks lines inside RST cross-references. For example, it will format

    """
    This class contains tests of the
    `:py:class:~aaa.bbb.cccc.dddddddddd.eeeeeeeeeeeeeeeee.Fffffffffffffffffffffffff`
    class.
    """

into

    """
    This class contains tests of the `:py:class:~ska.low.mccs.controller
    .controller_device.ControllerResourceManager` class.

which is invalid RST.

Class attributes docstrings aren't formatted

Hi there,

I noticed that when declaring a class attribute with a docstring docformatter doesn't seem to take in account and reformat it.

An example:

class MyClass:
  my_attribute: str
  """This is a very, very, very long docstring that should really be reformatted nicely by docformatter. But it is currently ignored and will stay on a very, very, very long line!"""

While I don't believe that class attribute docstrings are explicitly mentioned in an active PEP they are very common, and are for example supported by Sphinx, Numpydoc, mkdocstrings, and Pylance.

Thank you!

I’m adding Black to a large-ish project that previously had no Python
autoformatting. I found this project from the Black docstrings thread:
psf/black#144 (comment)

I installed it and ran docformatter -i -r ., and it worked perfectly,
and the output still passes black --check. You’ve saved me quite a bit
of time determining how to effect this 7K-line diff myself. Thank you!

License file

I am trying to package docformatter for openSUSE. However, there is no license file I can find, either in the github or tarball. In order for people to know how they can use your code it is really important to have a license file. Would it be possible to add one? Thank you.

docformatter does not work as intended on windows

I have installed docformatter on windows 7 using:
python.exe setup.py install
I am currently using python 2.7.

When trying to call the docformat script on the commandline in windows
(docformat -h) I get the following error:
"'docformatter' is not recognized as an internal or external command, operable program or batch file."

However, I have managed to run it by renaming the script "docformatter.py" to "docformatter-script.py" and moving it from "site-packages/docformater-0.5.6-py2.7.egg/EGG-INFO/scripts" to "c:\python27\scripts".

Breaking long line does not preserve links

Hi, first, for this nice tool!
We crossed some difficulty with long links which are split into multiple lines (when a line is over 120 chars) but then it is not valid link anymore, for example this one:

`Area Under the Receiver Operating Characteristic Curve (ROC AUC)
    <https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Further_interpretations>`_.

is there some solution for such a case? for example, do when the link is too long start automatically on a new line and even the line is too long, do not break it...

docformatter removes blank line after last section in docstrings

Issue Summary

If a docstring has a summary and a description that consists of at least one section, then there should be a blank line between the last line of the section and the the final """ of the docstring.

Example

Given the class SomeClass below, docformatter will remove the blank line at the end of the class dosctring, after the "Methods" section. In contrast, pydocstyle will throw a D413 error if that blank line is removed: D413: Missing blank line after last section ('Methods').

Is it possible to setup docformatter to respect D413?

class SomeClass:
    """Summary.

    Methods:
        method_1
        method_2
        method_3

    """

    def __init__(self):
        """Summary.

        Details about this thing that does nothing.
        """
        pass

Allow one sentence on each line

Is it possible to allow one sentence on each line and avoid this re-formatting?

docformatter documentation3.py 
--- before/documentation3.py
+++ after/documentation3.py
@@ -1,12 +1,8 @@
 class Release(object):
     """Parse a release name.
 
-    Example:
-      release-1.1/
-      release-1.2/
-      release-1.3/
-      release-1.4/
-      release-1.4.1/
-      release-1.5/
+    Example:   release-1.1/   release-1.2/   release-1.3/   release-1.4/
+    release-1.4.1/   release-1.5/
+
     """
     pass

Can't wrap description

OS:Windows 8.1 x64
Python: 2.7.6

def gds_for_ols_linear_regression(X, y, alpha, num_iterations):
    """
    Gradient descent search for OLS linear regression.
    alpha is the learning rate.
    num_iterations is the numer of updates - instead of a better definition of convergence.
    It returns parameters beta and also a numpy array of size num_iterations, containing
    the value of the loss function, J, after each iteration - so you can plot it.
    """

    Jvals = np.zeros(num_iterations)
    m, n = X.shape
    beta = np.zeros(n)

    for iter in range(num_iterations):
        beta -= (1.0 * alpha / m) * (X.dot(beta) - y).dot(X)
        Jvals[iter] = J(beta, X, y)

    return beta, Jvals

Run following command under windows 8.1, docstring won't be wraped.

docformatter  --wrap-descriptions 30 .\test.py
 def gds_for_ols_linear_regression(X, y, alpha, num_iterations):
-    """
-    Gradient descent search for OLS linear regression.
-    alpha is the learning rate.
+    """Gradient descent search for OLS linear regression. alpha is the learning
+    rate.
+
     num_iterations is the numer of updates - instead of a better definition of convergence.
     It returns parameters beta and also a numpy array of size num_iterations, containing
     the value of the loss function, J, after each iteration - so you can plot it.
+
     """

     Jvals = np.zeros(num_iterations)

Any advice?

docformat sometimes produces output which it changes further on rerunning

Consider the following code:

class HealthCheck():
    """Classes of health check
    for use in :attr:`~hypothesis.settings.suppress_health_check`

    """

When run on this code, docformat produces the following:

class HealthCheck():
    """Classes of health check for use in
    :attr:`~hypothesis.settings.suppress_health_check`"""

Running docformat on this again produces the following:

class HealthCheck():
    """Classes of health check for use in.

    :attr:`~hypothesis.settings.suppress_health_check`

    """

Generally I would expect formatting tools to format to fixed points - i.e. once you've run them once, running them again should produce zero changes. Is it intentional that this is not the case here?

Inconsistent formatting of docstring with and without `Returns` statement

Have an issue running the command

$ docformatter -i doc.py --wrap-summaries=100 --wrap-descriptions=100 --blank

on the file with the following content:

class BinaryIOBase(object):
    def __init__(self, stream):
        """Initializes an instance of Binary IO class using the supplied output stream.

        Args:     
            stream (BinaryIO): Binary stream (usually a file object).

        """
        self.stream = stream
        
class BinaryIOBase(object):
    def __init__(self, stream):
        """Initializes an instance of Binary IO class using the supplied output stream.

        Args:
            stream (BinaryIO): Binary stream (usually a file object).

        Returns:
            str: result

        """
        self.stream = stream

The result:

--- before/doc.py
+++ after/doc.py
@@ -2,8 +2,7 @@
     def __init__(self, stream):
         """Initializes an instance of Binary IO class using the supplied output stream.

-        Args:
-            stream (BinaryIO): Binary stream (usually a file object).
+        Args:     stream (BinaryIO): Binary stream (usually a file object).

         """
         self.stream = stream

As you can see, it moves the stream argument to the previous line, however, the program does not touch the second class which has Returns in its docstring. Without having something on the next line after an empty line, the program reformats the Args section incorrectly.

Any workarounds?

$ docformatter --version
docformatter 1.0

Ignoring specific line

In my project doctstrings, I have some sphinx style notes. In consequence, I have a line break just after .. note:: as shown hereafter:

def foo():
  """
  Fancy doc
  
  More details.

  .. note::
    Some notes.
  """
  pass

However, when I run docformatter with these options r -i --pre-summary-newline --make-summary-multi-line --wrap-summaries 90 --wrap-descriptions 90 it outputs:

def foo():
  """
  Fancy doc
  
  More details.

  .. note::  Some notes.
  """
  pass

even when I exclude the affected files.

Is there a way to ignore specific lines?

Handle "line too long"

It would be nice for docformatter to also handle lines that are too long in docstrings

Feature: Add option to reformat docstrings of given length

Backstory: I'm working on the big project where coding style evolved over years.
I would like to reformat all single line docstrings in a separate pull request, as they probably won't need much attention, and then I'd reformat the rest of the project.

Let me know if adding a new flag --docstring-length [min_length] [max_length] would be beneficial, I can handle that.

Start sentence with capital letter

Hi, I have noticed that the docstring puts "." at the summary end but does not make the first letter capital...
I think that it could be quite simple to edit this, what do you think?
For example this original:

"""set minimal torch version"""

is converted to:

"""set minimal torch version."""

Adds windows-style line endings to unix style file

In Windows, when running docformatter on a file with unix-style line endings, it replaces all line endings with Windows-style endings. I assume it picks the type of line endings based on the OS, rather than the file, which is a pretty bad assumption. Other tools like autopep8 and yapf don't seem to have this issue.

Improvement

Make a wildcard like --sep that separates docstrings from """ by one spacebar.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.