pycqa / docformatter Goto Github PK
View Code? Open in Web Editor NEWFormats docstrings to follow PEP 257
Home Page: https://pypi.python.org/pypi/docformatter
License: MIT License
Formats docstrings to follow PEP 257
Home Page: https://pypi.python.org/pypi/docformatter
License: MIT License
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?
The documentation page for 1.4 https://pypi.org/project/docformatter/1.4/ seems to contain a screenshot in the PyCharm section. The file doesn't exist (image URL returns 404 Not Found).
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.
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.
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.
"""
Are there any plans to do this? Is this already implemented?
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.
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!
It would be great to have a docformatterrc
like many other commands similar to this (flake8, autopep8, etc)
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:
Here's a screenshot of the before:
Here's a screenshot after running docformatter:
Note that the description was not line-wrapped.
Here's a screenshot after running docformatter with the --force-wrap option:
Note that the description was line-wrapped but the Sphinx param was also wrapped.
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
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.
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".
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?
If there is a blank line between function definition and the docstring, it should be removed:
def my_func():
"""Summary of my function"""
should be modified to:
def my_func():
"""Summary of my function"""
Make a wildcard like --sep that separates docstrings from """ by one spacebar.
Currently docformatter adds a blank line before closing quotes in docstring by default. But this is not conform to actual version of pep-257.
Commentary about this in format_docstring
function refers to paragraph which was removed in 2014: https://hg.python.org/peps/rev/a7b2b2d5b1d4
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.
The last release on pypi is from 2015, it would be great if you can give it a bump.
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.
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?
hi, docformatter edits this seemingly correct format, is there something we're missing?
Lightning-AI/pytorch-lightning@6d12d69
Adding an extra line (Lightning-AI/pytorch-lightning#9422 (comment)) seems to make docformatter happy, was there something off with the original though? Thank you!
docstring lines beginning with :param
or :return
aren't wrapped by default
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...
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.
"""
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 "#"
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.
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
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!
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!
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
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!
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.
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!
docformatter
can remove trailing whitespaces from the following script:
"""
A docstring with some invisible whitespace.
More description with some invisible trailing whitespaces.
"""
but does nothing to sphinx-gallery style header docstrings:
"""
A docstring with some invisible whitespace.
=================================================
More description with some invisible trailing whitespaces.
"""
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.
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."""
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...
)
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.
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
This recommendation of the PEP257 does not really make sense.
See also: https://lists.launchpad.net/openstack/msg04953.html
IMHO a proposal to amend PEP 257 should be proposed on http://bugs.python.org/
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
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
I've not had time to triage pull requests in the last couple years. I'm planning to move this and other related repositories to https://github.com/orgs/PyCQA.
It would be nice for docformatter to also handle lines that are too long in docstrings
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.
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
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
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?
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?
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.