pdoc3 / pdoc Goto Github PK
View Code? Open in Web Editor NEW:snake: :arrow_right: :scroll: Auto-generate API documentation for Python projects
Home Page: https://pdoc3.github.io/pdoc/
License: GNU Affero General Public License v3.0
:snake: :arrow_right: :scroll: Auto-generate API documentation for Python projects
Home Page: https://pdoc3.github.io/pdoc/
License: GNU Affero General Public License v3.0
First of all I want to say I absolutely LOVE how easy it is to install and run pdoc. So thank you!
The feature I am requesting is the ability to ignore certain sub-modules. For example, on my docs (https://cs01.github.io/pygdbmi/), I don't want pygdbmi.StringStream
or pygdbmi.printcolor
to appear in generated documentation.
Maybe something like:
pdoc3 --ignoreRegex "StringStream|printcolor" --html mypackage
Clicking on a class
in the class list on the left brings me to the definition of the class.
Instead, it sometimes brings me to the inherited/super class. I could not verify which circumstance triggers this issue.
For example, in a definitions.py
file, I might have:
"""Definitions: Create Global Reference Variables."""
import math
from pathlib import Path
# Base directory path
PTH_PROJ = Path.home() / 'Program Files (x86)/FooBar'
# Some Dictionary
COUNT_MAP = {
'one': 1,
'eleven': 11,
'septendecillion': math.pow(10, 54),
}
Is there a way to show these public global variables (PTH_PROJ
and COUNT_MAP
) in the generated pdoc documentation?
Runing pdoc3 cli inside active venv shell session:
(venv) C:\Users\me\dev\fooproject>pdoc --html foo
Documentation should be generated based on modules active in the virtual environment.
ModuleNotFoundError and ImportError raised for any modules/packages imported by foo that are not present in the system Python directory.
In pdoc, pdoc --http
would create a summary of all modules in that environment.
However, in pdoc3, the same command pdoc3 --http
returns an error that no module was specified (and no argument no http), so you launch with something like pdoc3 csv --http localhost:8000
and have to navigate to http://localhost:8000/csv/
Three questions:
localhost:8000
if no arguments are provided to --http?(base) 05:20 [PDOC] ¿ pdoc csv --http localhost:8000
Starting pdoc server on localhost:8000
pdoc server ready at http://localhost:8000/csv/
# ^ instead of "pdoc server ready at http://localhost:8000/"
Thank you for such amazing project!
I've similar hierarchy
namespaceroot
namespace1
pkg1/
__init__.py
namespace2
pkg2/
__init__.py
Generating documentation for 2 nested namespaces and the packages inside them
ipdb> print(doc_obj.obj)
<module 'rootnamespace.namespace1.pkg1' from '/proj/rootnamespace/namespace1/pkg1/__init__.py'>
ipdb> doc_obj.obj
<module 'rootnamespace.namespace1.pkg1' from '/proj/rootnamespace/namespace1/pkg1/__init__.py'>
ipdb> inspect.getsource(doc_obj.obj)
*** OSError: could not get source code
PYTHONPATH=PYTHONPATH:rootnamespace
pdoc rootnamespace
pdoc3 0.6.3
We (@underworldcode) recently adopted pdoc3 for some of our pure python projects and we were wondering about the status of mathematical equations in the generated documentation.
We often include snippets of latex in our docstrings for cases where we are implementing something overtly mathematical that needs explaining and where an explanation that tries to skirt the equations is horribly convoluted.
An example here: http://www.underworldcode.org/stripy/cartesian.html#stripy.cartesian.Triangulation.interpolate_cubic. The docs in this case are from pdoc3 with a tweak to add mathjax headers and include the markdown mathematics extensions.
We'd be interested to know if this is a benign addition to pdoc3 that could ultimately be useful / optionally supported or if it is a niche case of little interest in real life.
When generating doc for a package that is annotated with PEP 484 type hints, I would expect the type hints to be present in the documentation.
For example, the following definition
def foo(x: Bar, repeat : int = 1):
"""Foo-cate a Bar a number of times (default: 1)."""
...
results in the type hints being available in the REPL's help()
:
>>> help(foo)
foo(x: __main__.Bar, repeat: int = 1)
Foo-cate a Bar a number of times (default: 1).
and it should well as be present in the pdoc-generated documents:
$ pdoc example.py
Module example
==============
Functions
---------
`foo(x: Bar, repeat: int = 1)`
: Foo-cate a Bar a number of times (default: 1).
Classes
-------
`Bar`
pdoc
ignores the type-hints:
$ pdoc example.py
Module example
==============
Functions
---------
`foo(x, repeat=1)`
: Foo-cate a Bar a number of times (default: 1).
Classes
-------
`Bar`
Type hints document the expected types of parameters and return values. As such, they convey a lot of information for the documentation's user, when present.
See PEP 484 for a discussion of type hints.
Generate documentation for a module that uses type hints
hi all,
i really love the new view of pdoc3 and i'd love to upgrade, but i was wondering how it might be possible to add things like a "getting started guide" to the documentation page. at the moment i love how all the docstrings are properly converted into documentation but i can't find out how to add things like "examples" or "caveat" pages to my documentation. is this possible with pdoc3?
either way, thanks for making this!
For the module I'm working on, this defensive line is actually breaking things because a dependency of a dependency is checking if stdin
is open: https://github.com/pdoc3/pdoc/blob/master/pdoc/cli.py#L285
Would it be possible to allow this behaviour to be turned off via a flag or environment variable? If you'd accept such a PR I'd be happy to contribute it :)
Really loving pdoc, it has everything I would expected in a doc generation tool except for Search.
An example of a tool that does it really well is mkdocs with the mkdocs-material theme. Example docs: https://www.starlette.io/.
Any chance of something like this coming to pdoc?
Some python libraries use 2-spaces-indentation instead of 4 spaces or single tab.
The user would expect being able to use an argument to support that.
Currently no argument seems to support that.
And by default it will generate badly formatted documentation for such libraries.
N/A
When I install pdoc3 0.5.2 via pip3 install pydoc3 on ubuntu 18.04 it installs ok, but running it gives the following error:
> pdoc3 --version
...
AttributeError: module 'pdoc' has no attribute '__version__'
The command works fine after installing pdoc 0.5.1
No crash
0.5.2
Module is not loaded more than once (?)
Module seems to be loaded multiple times, thus throwing an error due to libraries used.
I have a Plotly/Dash application that works fine on its own but when I try to use pdoc it raises a Dash exception that only occurs when you attempt to output to the same component multiple times:
You have already assigned a callback to the output
with ID "login_form" and property "style". An output can only have
a single callback function. Try combining your inputs and
callback functions together into one function.
I know this is not the case because normally the application works. This particular element isn't tampered with anyhere else in the project, so the file I'm trying to output docs for must be loaded twice.
Edit: Functions are usually wrapped with decorators that reference the top-level app (in a separate file, as per the Dash docs).
Example callback:
@app.callback(Output("login_form", "style"),
[Input("login_choice", "value")])
def show_login_input(value):
if value == "yes":
return {"display": "inline"}
else:
return {"display": "none"}
Running using the cli, (e.g. pdoc --html app.py
)
Running the app is protected withing a if __name__ ....
block.
I use Google's docstring style by documenting Class.__init__(self)
methods in the Class
docstring. Which means, I always have an __init__
method rendered without any documentation but the parameters and the default values. On the flip side, I have a large Class
docstring rendered which contains explanations for all these parameters. Basically, everything is split up.
What about an option to tackle this case including proper output?
For example, the one from sklearn
where the __init__
signature is included in the Class
:
Static and live generation should work the same way.
In my project I can run pdoc my_module --html
and it runs fine, generating HTML etc but while pdoc my_module --http localhost:8080
starts the web server, the page fails to render with ModuleNotFoundError: No module named 'my_module'
git clone [email protected]:plotly/plotly_express.git
(maybe install some deps)pdoc plotly_express --html
vs pdoc plotly_express --http localhost:8080
I was trying to use pdoc to create the documentation of a C extensions. The generated documentation does not include the documentation for class methods.
You can see this for example when generating the documentation for python's parser
module, which is a C extension.
pdoc --html parser
The class methods of ST class are missing. With pydoc, they are included.
Generate documentation.
Traceback (most recent call last):
File "/tmp/zz-7EQ2Br1/.venv/bin/pdoc", line 11, in <module>
load_entry_point('pdoc3==0.6.3', 'console_scripts', 'pdoc')()
File "/tmp/zz-7EQ2Br1/.venv/lib/python3.7/site-packages/pdoc/cli.py", line 443, in main
pdoc.link_inheritance()
File "/tmp/zz-7EQ2Br1/.venv/lib/python3.7/site-packages/pdoc/__init__.py", line 354, in link_inheritance
for cls in _toposort(graph):
File "/tmp/zz-7EQ2Br1/.venv/lib/python3.7/site-packages/pdoc/__init__.py", line 336, in _toposort
assert not graph, "A cyclic dependency exists amongst %r" % graph
AssertionError: A cyclic dependency exists amongst {<Class 'a.Location'>: {<Class 'a.Location'>}}
a.py
:from collections import namedtuple
class Location(namedtuple('Location', ['lat', 'lon'])):
"""Geo-location, GPS position."""
pdoc3 --html a.py
Should pdoc handle plain links like http://crummy.com/software/BeautifulSoup/
and format them as clickable links: http://crummy.com/software/BeautifulSoup/? Right now the colon is tricks pdoc into formatting the link as reST.
For example, in the BS4 docs generated by pdoc the link is split on the colon making it unclickable:
pip install beautifulsoup4
pdoc3 bs4 --html
For working with Highlight.js outside of Node, how do people typically import the CSS files? Do you download the file and import locally or are they hosted on an online CDN?
For the default template, would you consider setting the default style to one of Foundation
, Github Gist
, Atom One Light
, or A 11 Y Light
that provide better highlighting of variables and built-ins?
Try the hljs demo: https://highlightjs.org/static/demo/
At the home page of the project it is stated that library has an ability of "Plain text, HTML, or PDF output". It is expected to have such command:
pdoc3 --text --text-dir ./documentation_dir module_name
pdoc3 help says that there is no such option like text and it does't provide a name of this option: pdoc3: error: unrecognized arguments: --text
I am using numpydoc style docstrings. But when undocumented return types are used, then the type is displayed as normal text. For example in:
"""
Returns
-------
None
"""
When adding a description, then it is rendered correctly:
"""
Returns
-------
None
Nothing to return.
"""
I am using pdoc 0.5.4.
pdoc3 throws errors that a favicon.ico
file can't be found.
Is it up to the user to provide a favicon? If not, maybe there should be a default favicon.ico included with pdoc3? Or the error could be circumvented like in pdoc where they intentionally return None: mitmproxy/pdoc/master/pdoc/web.py#L91-L93
def html(self):
"""
Retrieves and sends the HTML belonging to the path given in
URL. This method is smart and will look for HTML files already
generated and account for whether they are stale compared to
the source code.
"""
# Deny favico shortcut early.
if self.path == "/favicon.ico":
return None
return pdoc.render.html_module(pdoc.extract.extract_module(self.import_path))
(base) 05:20 [PDOC] ¿ pdoc csv --http localhost:8000
Starting pdoc server on localhost:8000
pdoc server ready at http://localhost:8000
127.0.0.1 - - [24/Feb/2019 05:21:01] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 05:21:03] "GET /favicon.ico HTTP/1.1" 302 -
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 50040)
Traceback (most recent call last):
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 720, in __init__
self.handle()
File "/Users/kyleking/anaconda3/lib/python3.7/http/server.py", line 426, in handle
self.handle_one_request()
File "/Users/kyleking/anaconda3/lib/python3.7/http/server.py", line 414, in handle_one_request
method()
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/cli.py", line 175, in do_GET
out = self.html()
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/cli.py", line 205, in html
return pdoc.html(self.import_path_from_req_url, http_server=True)
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/__init__.py", line 471, in html
mod = Module(import_module(module_name), docfilter=docfilter)
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/__init__.py", line 526, in import_module
raise ValueError('File or module {!r} not found'.format(module))
ValueError: File or module 'favicon.ico' not found
----------------------------------------
127.0.0.1 - - [24/Feb/2019 05:21:07] "GET /csv HTTP/1.1" 302 -
/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/__init__.py:585: UserWarning: Couldn't get/parse source of '<Class 'csv.Error'>'
warn("Couldn't get/parse source of '{!r}'".format(doc_obj))
127.0.0.1 - - [24/Feb/2019 05:21:07] "GET /csv/ HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 05:21:07] "GET /favicon.ico HTTP/1.1" 302 -
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 50102)
Traceback (most recent call last):
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Users/kyleking/anaconda3/lib/python3.7/socketserver.py", line 720, in __init__
self.handle()
File "/Users/kyleking/anaconda3/lib/python3.7/http/server.py", line 426, in handle
self.handle_one_request()
File "/Users/kyleking/anaconda3/lib/python3.7/http/server.py", line 414, in handle_one_request
method()
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/cli.py", line 175, in do_GET
out = self.html()
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/cli.py", line 205, in html
return pdoc.html(self.import_path_from_req_url, http_server=True)
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/__init__.py", line 471, in html
mod = Module(import_module(module_name), docfilter=docfilter)
File "/Users/kyleking/anaconda3/lib/python3.7/site-packages/pdoc/__init__.py", line 526, in import_module
raise ValueError('File or module {!r} not found'.format(module))
ValueError: File or module 'favicon.ico' not found
pdoc csv --http localhost:8000
Does pdoc3
offer mathematical rendering via something like MathJax
? I wouldn't know how to implement it but I'd be willing to investigate if people are open to this feature.
It would be nice if the homepage allowed some more context to be written. For example, passing the path to an arbitrary markdown file, such as the README.md, or any other arbitrary content.
Example call:
pdoc --index README.md --html mypackage
The title basically says it all.
running
pdoc --http :8001 PACKAGE
serves the docs locally, but if any changes are made, the server needs to be manually killed and restarted, and the webpage needs to be reloaded.
The PyPI package livereload is built to watch files and reload the web client if a source file changes. This is common in other popular tools such as mkdocs and create-react-app. mkdocs implementation can be used as a guide: https://github.com/mkdocs/mkdocs/blob/master/mkdocs/commands/serve.py.
In my source, I have object that are defined very deep into the hierarchy. In Sphinx, I can use ~ to just output the name of the class, not the entire path.
def add(self, from_component: Component, to_component
)
def add(self, from_component: components.stdlib.component.Component, to_component)
GitHub pages are a common way to host documentation for sites. They require one of the following to host in source code:
Right now I'm using master branch /docs for pygdbmi, and I have what I would assume is a very common project structure, yet my workflow has a little hack in it. I generate my docs with the following make recipe:
docs:
pdoc --html --force --output-dir docs pygdbmi
mv docs/pygdbmi/* docs
rmdir docs/pygdbmi
Is there a way to generate docs directly to the --output-dir? By namespacing it with the package name, it breaks it for GitHub pages.
There's a quote at the bottom of the Github pages site:
There is nothing in the programming field more despicable than an undocumented program. — Ed Young
Do you have a citation for it?
Would you accept a PR to make sorting optional in the documentation (new CLI arg, defaulting to current behaviour)? I rather like the order in which the functions/methods are declared in my module and I'd rather the documentation follow that order rather than a strictly alphabetical one :)
A generated pdf document after pdoc3 --pdf time
.
usage: pdoc3 [-h] [--version] [--filter STRING] [--html] [--html-dir DIR]
[--html-no-source] [--overwrite] [--external-links]
[--template-dir DIR] [--link-prefix STRING] [--http HOST:PORT]
MODULE [MODULE ...]
pdoc3: error: unrecognized arguments: --pdf
I was expecting to be able to use code blocks for Args
section.
For example, this is my docstring:
def predict(self, test_sequence, args):
"""Predict test sequence labels using UISRNN model.
Args:
test_sequence: 2-dim numpy array of real numbers, size: N * D
- the test observation sequence.
N - length of one test utterance
D - observation dimension
For example:
```
test_sequence =
[[2.2 -1.0 3.0 5.6] --> 1st entry of utterance 'iccc'
[0.5 1.8 -3.2 0.4] --> 2nd entry of utterance 'iccc'
[-2.2 5.0 1.8 3.7] --> 3rd entry of utterance 'iccc'
[-3.8 0.1 1.4 3.3] --> 4th entry of utterance 'iccc'
[0.1 2.7 3.5 -1.7]] --> 5th entry of utterance 'iccc'
```
Here N=5, D=4.
args: Inference configurations. See arguments.py for details.
Here is what has been rendered:
It did not insert new lines for the multiline code block.
N/A
The Sub-Modules links on the left sidebar should link to the file; however, on Windows the links are incorrect. On Windows, the path has an incorrect relative (../
), which isn't present on Mac (I don't have Linux to check, but probably only an issue on Windows).
Links to http://localhost:8080/diagnose.html (..\diagnose.html
)
When it should link to http://localhost:8080/bs4/diagnose.html (./diagnose.html
)
Works as expected:
# # Setup
# git clone ...
# pip install -e .
# pip install beautifulsoup4
# Demo
pdoc bs4 --http :
# or: pdoc bs4 --html
I'm planning on working on a PR/bug fix for this, but wanted to document what I'm seeing first
I'm pretty disgusted that someone has taken a project I built, relicensed it, attempted to erase its entry on the Python Wiki, released it under effectively the same name and, worst of all, associated it with Nazi symbols. This is from the footer of your web site:
Please remove my name from this project. I do not wish to be associated with it. For example:
https://github.com/mitmproxy/pdoc/blob/69ce6240df227b50c799073587d6358c368788a9/setup.py#L15-L16
Please also remove any commit in which I'm listed as an author and otherwise expunge my name from this project.
I have this docstring:
def compute_intersection_length(A, B):
"""Compute the intersection length of two tuples.
Args:
A: a (speaker, start, end) tuple of type (string, float, float)
B: a (speaker, start, end) tuple of type (string, float, float)
Returns:
a float number of the intersection between `A` and `B`
"""
I expect the generated docs separate A and B in different paragraphs.
This is what has been generated:
Not sure if this is a bug or intentional...
N/A
Like Args
, I expect Returns
and Raises
to support multiple lines to describe a single object.
The second line is treated as a new paragraph.
This is my code:
Returns:
sampled_index_sequences: (a list of numpy arrays) - a list of subsampled
block-preserving permuted sequences. For example,
```
sampled_index_sequences =
[[10,11,12,1,2,6],
[6,1,2,10,11,12],
[1,2,10,11,12,6],
[6,1,2,10,11,12],
[1,2,6,10,11,12]]
```
The length of "sampled_index_sequences" is "number_samples".
The should not be a new paragraph between "sampled" and "block-preserving".
N/A
Variable names (e.g. class methods or members) that aren't "too long" should be displayed on one line
Variable names above 10 characters or so are split over two lines
instance_variables
in Class
is cut in half unless the window is extremely wideHi,
Is there any functionality such that all the contents are not shown on the same page.
For example on the pdocs documentation website, if each of the subsections had its own page?
Is this already implemented?
I use python in a conda environment and would like to know if you're going to make pdoc3 available there.
I know this is not exactly an "issue" but I couldn't find your contact anywhere and I'd really appreciate your help.
Thank you!
Is there a way to add a logo like the pdoc3 docs have?
Make CLI API more friendly such that it defaults to using localhost:8000 if no host/port is specified.
On a Mac or Linux machine,
$ pip3 install pdoc3
$ pdoc --html pdoc
produces documentation.
Second command yields:
$ bash: pdoc: command not found
Python 3.5.4rc1 (default, Jul 25 2017, 08:53:34)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdoc
>>> print(pdoc.__version__)
0.5.1
Add __main__.py
file such that users can at least do:
$ python3 -m pdoc ...
Well, it's not something important, but a nice-to-have feature.
Currently the <article>
part of index.html
comes of the docstring of __init__.py
. However, some authors prefer to leave the details of the package/module in a markdown file like README.md
, for easier access to the audience, instead of __init__.py
.
It might be a nice feature if pdoc
has an argument that supports converting a markdown file to HTML and injecting the converted HTML part into the <article>
part of index.html
.
N/A
N/A
Want to be able to have args such as:
Args:
no_extra: no extra parameters
one_extra(one): one extra parameter contained in the ()
multi_extra(one, two, three): three extra parameters contained in the ()
no_extra: no extra parameters, but this line does span
multiple lines, so there's that
one_extra(one): one extra parameter contained in the (), but this line does span
multiple lines, so there's that
multi_extra(one, two, three): three extra parameters contained in the (), but this line does span
multiple lines, so there's that
Which should be supported by google-style docs:
https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
you can only have the variable name before the ":", no extra descriptions before (in parens). if you do have some, the args will get unformatted.
you can do it after the ":" of course -- but that's an ugly workaround (IMO) and doesn't follow spec.
see expected vs actual :)
This is just a regex update; in google (def google) in the file html_helpers, the lamda-regex should be:
_googledoc_sections=partial(
re.compile(r'(?<=\n\n)(\w+):$\n((?:\n?(?: {4}.*|$))+)', re.MULTILINE).sub,
lambda m, _params=partial(
re.compile(r'^([\w*]+\s*(?:\(.*\))?)(?: \(([\w. ]+)\))?: '
r'((?:.*)(?:\n(?: {4}.*|$))*)', re.MULTILINE).sub,
lambda m: _ToMarkdown._deflist(*m.groups())): (
'\n{}\n-----\n{}'.format(
m.group(1), _params(inspect.cleandoc(m.group(2))))))):
though i haven't completely tested to see if this works (worked for the above expected behavior examples) in every possible situation. i am having a slight issue getting the test to run.
Detect if read-only descriptor is data or method descriptor.
Generate documentation.
File "/HOME/.local/lib/python3.7/site-packages/pdoc/__init__.py", line 1020, in __init__
assert callable(obj)
in Class.__init__
(L822) inspect.isroutine(obj)
is checked and in Function.__init__
(L1020) callable(obj)
is asserted.
Problem is when obj
is read-only value descriptor (has __get__
, no __set__
and __get__()
returns non-callable value).
From inspect.py
(Python 3.7):
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object))
Follow documentation inspect.ismethoddescriptor(object)
:
An object passing this test has a
__get__()
method but not a__set__()
method...
From inspect.py
(Python 3.7):
def ismethoddescriptor(object):
if isclass(object) or ismethod(object) or isfunction(object):
# mutual exclusion
return False
tp = type(object)
return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
Then assert failed on read-only value descriptors (like peewee.BackrefAccessor
) and documentation is not generated.
foo.py
):class Power:
def __get__(self, instance, instance_type=None):
if instance is not None:
return instance.value ** 2
return self
class Value:
power = Power()
def __init__(self, value):
self.value = value
pdoc --html foo.py
pdoc version: 0.6.3
minimal workaround I've found, change Class.__init__()
(L822):
--- pdoc-0.6.3/__init__.py 2019-07-04 07:34:53.857974401 +0200
+++ pdoc/__init__.py 2019-07-04 07:34:33.366110353 +0200
@@ -819,7 +819,7 @@
for name, obj in public_objs:
if name in self.doc and self.doc[name].docstring:
continue
- if inspect.isroutine(obj):
+ if inspect.isroutine(obj) and callable(obj):
self.doc[name] = Function(
name, self.module, obj, cls=self,
method=not self._method_type(self.obj, name))
The highlight.js
styles are only included if show_source_code
is true, which means that syntax highlighting in doc-strings is only available when show_source_code
is true. This can be solved by editing the html.mako
template, but it would be easier if there was a flag (eg enable_syntax_highlighting
) which did specifically included the highlight.js
styles.
The doc says :
pdoc considers methods' docstrings inherited from superclass methods', following the normal class inheritance patterns. Consider the following code example:
>>> class A:
... def test(self):
... """Docstring for A."""
... pass
...
>>> class B(A):
... def test(self):
... pass
...
>>> A.test.__doc__
'Docstring for A.'
>>> B.test.__doc__
None
In Python, the docstring for B.test doesn't exist, even though a docstring was defined for A.test. When pdoc generates documentation for the code such as above, it will automatically attach the docstring for A.test to B.test if B.test does not define its own docstring. In the default HTML template, such inherited docstrings are greyed out.
So I expect to see "test" in the methods of B, documented with the docstring of A.
In my tests with pdoc3 v0.5.0 to v0.6.2, I don't see "test" in the methods of B. It says it is inherited. It is in reality not the case as it is overwritten.
When I add a docstring to B.test, it reappears in the methods of B.
class A:
def test(self):
"""Docstring for A."""
print("From A")
class B(A):
def test(self):
print("From B")
Syntax highlighting in code snipets in docstring
Syntax highlighted beautifully in some cases, partially in others (only some keywords, etc.), not at all in yet others.
Here is an example function where the resulting HTML has the code all in grey:
def tw2pw(thrusttoweight, speed, etap):
"""Converts thrust to weight to power to weight (propeller-driven aircraft)
`PARAMETERS`
------------
`thrusttoweight` : thrust to weight ratio (non-dimensional)
`speed`: speed (in m/s if output in Watts / Newton is required)
`etap`: propeller efficiency (non-dimensional)
`RETURNS`
-----------
power to weight ratio (in W/N if speed is in m/s)
`SEE ALSO`
------------
``powerrequired``
`NOTES`
---------
A note on units. If the input speed is in m/s, the other two inputs being
non-dimensional, the output product is also in m/s, which is equal to W/N
(W / N = (J/s) / N = (Nm/s) / N = m/s).
`EXAMPLE`
---------
------------
#!python
import constraintanalysis as ca
import atmospheres as at
import unitconversions as co
designbrief = {'stloadfactor': 2, 'turnalt_m': 3050, 'turnspeed_ktas': 140}
etap = {'turn': 0.85}
designperformance = {'CLmaxclean': 1.45, 'CDminclean': 0.02541,
'etaprop': etap}
designdef = {'aspectratio': 10, 'sweep_le_deg': 2,
'sweep_mt_deg': 0, 'bpr': -1}
TOW_kg = 1500
designatm = at.Atmosphere()
concept = ca.AircraftConcept(designbrief, designdef,
designperformance, designatm)
wingloading_pa = 1000
twreq, _, _ = concept.twrequired_trn(wingloading_pa)
turnspeed_mpstas = co.kts2mps(designbrief['turnspeed_ktas'])
pw_trn_wpn = ca.tw2pw(twreq, turnspeed_mpstas, etap['turn'])
pw_trn_hpkg = co.wn2hpkg(pw_trn_wpn)
p_trn_hp = pw_trn_hpkg * TOW_kg
print(p_trn_hp)
---
#!python
318.691213406
"""
return thrusttoweight * speed / etap
Other, seemingly very similar docstrings in the same .py file are highlighted very nicely, for example:
def twrequired_trn(self, wingloading_pa):
"""Calculates the T/W required for turning for a range of wing loadings
`PARAMETERS`
------------
`wingloading_pa` : float or numpy array, list of wing loading values in Pa.
`RETURNS`
-----------
`twratio` : array, thrust to weight ratio required for the given wing loadings.
`clrequired` : array, lift coefficient values required for the turn (see notes).
`feasibletw`: as twratio, but contains NaNs in lieu of unachievable (CLmax exceeded) values.
`SEE ALSO`
------------
``twrequired``
`NOTES`
---------
1. Use `twrequired` if a full constraint analysis is desired, as this integrates
the take-off, turn, climb, cruise, and service ceiling constraints, as well as
computing the combined constraint boundary.
2. At the higher end of the wing loading range (low wing area values) the CL required
to achieve the required turn rate may exceed the maximum clean CL (as specified in the
`CLmaxclean` entry in the `performance` dictionary argument of the `AircraftConcept`
class object being used). This means that, whatever the T/W ratio, the wings will stall
at this point. The basic T/W value will still be returned in `twratio`, but there is
another output, `feasibletw`, which is an array of the same T/W values, with those
values blanked out (replaced with NaN) that cannot be achieved due to CL exceeding
the maximum clean lift coefficient.
`EXAMPLE`
Given a load factor, an altitude (in a given atmosphere) and a true airspeed, as well as
a set of basic geometrical and aerodynamic performance parameters, compute the necessary
T/W ratio to hold that load factor in the turn.
------------
#!python
import atmospheres as at
import constraintanalysis as ca
import unitconversions as co
designbrief = {'stloadfactor': 2, 'turnalt_m': co.feet2m(10000), 'turnspeed_ktas': 140}
etap = {'turn': 0.85}
designperformance = {'CLmaxclean': 1.45, 'CDminclean':0.02541, 'etaprop': etap}
designdef = {'aspectratio': 10.12, 'sweep_le_deg': 2, 'sweep_mt_deg': 0, 'bpr': -1}
designatm = at.Atmosphere()
concept = ca.AircraftConcept(designbrief, designdef,
designperformance, designatm)
wingloadinglist_pa = [1250, 1500, 1750]
twratio, clrequired, feasibletw = concept.twrequired_trn(wingloadinglist_pa)
print('T/W: ', twratio)
print('Only feasible T/Ws:', feasibletw)
print('CL required: ', clrequired)
print('CLmax clean: ', designperformance['CLmaxclean'])
---
#!python
T/W: [ 0.19920641 0.21420513 0.23243016]
Only feasible T/Ws: [ 0.19920641 0.21420513 nan]
CL required: [ 1.06552292 1.2786275 1.49173209]
CLmax clean: 1.45
"""
if self.turnspeed_ktas == -1:
turnmsg = "Turn speed not specified in the designbrief dictionary."
raise ValueError(turnmsg)
if self.stloadfactor == -1:
turnmsg = "Turn load factor not specified in the designbrief dictionary."
raise ValueError(turnmsg)
wingloading_pa = actools.recastasnpfloatarray(wingloading_pa)
# W/S at the start of the specified turn test may be less than MTOW/S
wingloading_pa = wingloading_pa * self.turn_weight_fraction
twratio, clrequired = self.thrusttoweight_sustainedturn(wingloading_pa)
# What SL T/W will yield the required T/W at the actual altitude?
temp_c = self.designatm.airtemp_c(self.turnalt_m)
pressure_pa = self.designatm.airpress_pa(self.turnalt_m)
density_kgpm3 = self.designatm.airdens_kgpm3(self.turnalt_m)
turnspeed_mps = co.kts2mps(self.turnspeed_ktas)
mach = self.designatm.mach(turnspeed_mps, self.turnalt_m)
corr = self._altcorr(temp_c, pressure_pa, mach, density_kgpm3)
twratio = twratio / corr
# Map back to T/MTOW if turn start weight is less than MTOW
twratio = twratio * self.turn_weight_fraction
# Which of these points is actually reachable given the clean CLmax?
feasibletw = np.copy(twratio)
for idx, val in enumerate(clrequired):
if val > self.clmaxclean:
feasibletw[idx] = np.nan
if len(twratio) == 1:
return twratio[0], clrequired[0], feasibletw[0]
return twratio, clrequired, feasibletw
I cannot figure what I'm doing right in one but not in the other...
Many thanks for the great tool.
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.