GithubHelp home page GithubHelp logo

pdoc3 / pdoc Goto Github PK

View Code? Open in Web Editor NEW
1.1K 9.0 143.0 1.7 MB

: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

Python 82.20% Mako 17.80%
documentation generator documentation-generator documentation-tool documentation-dumper api-documentation python python3 docs docs-generator

pdoc's Introduction

pdoc

Build Status Code Coverage pdoc3 on PyPI package downloads GitHub Sponsors

Auto-generate API documentation for Python 3+ projects.

Project website

Documentation

Installation

$ pip install pdoc3

Usage

Pdoc will accept a Python module file, package directory or an import path.

$ pdoc your_project

See pdoc --help for more command-line switches and the documentation for more usage examples.

Features

The above features are explained in more detail in pdoc's documentation (generated with pdoc).

Development

Check CONTRIBUTING.md for hacking details.

pdoc's People

Contributors

aomader avatar burntsushi avatar butterflybug avatar catern avatar cortesi avatar davfsa avatar dhimmel avatar epogrebnyak avatar hibou57 avatar ialwaysbecoding avatar jasonb-vbt avatar jvantuyl avatar kchmck avatar kernc avatar knadh avatar kyleking avatar lluissalord avatar mbustosorg avatar mhils avatar nicolaskruchten avatar nosewings avatar pieterb avatar pkazmier avatar poke1024 avatar postlund avatar radug avatar rkaminsk avatar stdrc avatar timothycrosley avatar wq2012 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

pdoc's Issues

Module loaded more than once?

Expected Behavior

Module is not loaded more than once (?)

Actual Behavior

Module seems to be loaded multiple times, thus throwing an error due to libraries used.

Steps to Reproduce

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"}

Additional info

  • pdoc version: 0.5.3

Running using the cli, (e.g. pdoc --html app.py)
Running the app is protected withing a if __name__ .... block.

Cyclic dependency when class derived from namedtuple

Expected Behavior

Generate documentation.

Actual Behavior

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'>}}

Steps to Reproduce

  1. Create a.py:
from collections import namedtuple

class Location(namedtuple('Location', ['lat', 'lon'])):
    """Geo-location, GPS position."""
  1. Run pdoc3 --html a.py

Additional info

  • pdoc version: 0.6.3
  • Python 3.7.3

Make identifiers sorting optional

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

Can module argument be optional with `--http`?

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:

  1. Could pdoc3 have the same behavior as pdoc3 to render the documentation for all available modules if no argument provided?
  2. Could pdoc3 use the default localhost:8000 if no arguments are provided to --http?
  3. If a module name is always required, could pdoc3 return the full URL to the specified module (see below)
(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/"

how to add a getting started quide

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!

pdoc cli ignoring virtual environment

Expected Behavior

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.

Actual Behavior

ModuleNotFoundError and ImportError raised for any modules/packages imported by foo that are not present in the system Python directory.

Steps to Reproduce

  1. Activate virtual environment.
  2. run pdoc cli for module that imports resources that are in the virtual environment but are not in the system environment.

Additional info

  • pdoc version:0.5.3
  • platform: Windows 10

Favicon Errors

Description

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))

Error Message

(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

Steps to Reproduce

  1. Run pdoc csv --http localhost:8000

Additional info

  • pdoc version: 0.5.2
  • OS: Mac OS Mojave 10.14.3
  • Python 3.7.2 (Anaconda)

search functionality?

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?

Sub-Module Link Error Only on Windows

Issue

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

On Windows:

linkissue

Links to http://localhost:8080/diagnose.html (..\diagnose.html)

badlink

When it should link to http://localhost:8080/bs4/diagnose.html (./diagnose.html)

On Mac

Works as expected:

MacInspect

Steps to Reproduce

# # Setup
# git clone ...
# pip install -e .
# pip install beautifulsoup4

# Demo
pdoc bs4 --http :
# or: pdoc bs4 --html

Additional info

  • pdoc version: latest as of 01Mar2019: 1e0608f
  • OS: (Windows 7, Mac OS Mojave)

I'm planning on working on a PR/bug fix for this, but wanted to document what I'm seeing first

Bug: It seems the `Returns` section does not support multiple lines for single object

Expected Behavior

Like Args, I expect Returns and Raises to support multiple lines to describe a single object.

Actual Behavior

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

This is what I got:
screenshot from 2019-01-24 11-33-04

The should not be a new paragraph between "sampled" and "block-preserving".

Steps to Reproduce

N/A

Additional info

  • pdoc version:
    0.5.1

bash: pdoc: command not found

Expected Behavior

On a Mac or Linux machine,

$ pip3 install pdoc3
$ pdoc --html pdoc

produces documentation.

Actual Behavior

Second command yields:

$ bash: pdoc: command not found

Steps to Reproduce

  1. On a Linux or Mac machine, open terminal
  2. Type the commands
  3. Read the results

Additional info

  • pdoc version:
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

Suggestion

Add __main__.py file such that users can at least do:

$ python3 -m pdoc ...

BUG: `Args` section issue when variable name is single upper case character

Expected Behavior

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.

Actual Behavior

This is what has been generated:
screenshot from 2019-01-28 11-00-05

Not sure if this is a bug or intentional...

Steps to Reproduce

N/A

Additional info

  • pdoc version:
    master of this repo

Feature Request: Specify hljs Style

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/

Shorten long object names in type hint

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.

Expected Behavior

def add(self, from_component: Component, to_component)

Actual Behavior

def add(self, from_component: components.stdlib.component.Component, to_component)

Steps to Reproduce

  1. Nest an object's definition deeply
  2. Use it in a typehint

Additional info

  • pdoc version: pdoc3 0.6.3

Ignore sub-modules

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

Support PEP 484 type hints

Expected Behavior

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`

Actual Behavior

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.

Steps to Reproduce

Generate documentation for a module that uses type hints

Additional info

  • pdoc version: 0.5.1
  • Python version: 3.7.2 (default, Jan 3 2019, 02:55:40)

numpydoc: Return types without description not displayed correctly

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.

Bug: It seems the `Args` section does not support code blocks very well

Expected Behavior

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.

Actual Behavior

Here is what has been rendered:
screenshot from 2019-01-24 11-53-00

It did not insert new lines for the multiline code block.

Steps to Reproduce

N/A

Additional info

  • pdoc version:
    0.5.1

add custom homepage intro

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

Splitting the intro page into multiple pages

Hi,
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?

how to get pdoc3 to work with packages in nested namespaces?

Thank you for such amazing project!

I've similar hierarchy

namespaceroot
   namespace1
       pkg1/
          __init__.py
   namespace2
      pkg2/
          __init__.py

Expected Behavior

Generating documentation for 2 nested namespaces and the packages inside them

Actual Behavior


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

Steps to Reproduce

  1. create the hierarchy
  2. export PYTHONPATH=PYTHONPATH:rootnamespace
  3. run pdoc rootnamespace

Additional info

  • pdoc version: pdoc3 0.6.3

Treat __init__ differently than other methods

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

pdoc3 --version crashes for version 0.5.2

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

expected behavior

No crash

pdoc3 version

0.5.2

Documentation for C Extensions

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.

  • pdoc version: 0.5.1

PDF generation

Expected Behavior

A generated pdf document after pdoc3 --pdf time.

Actual Behavior

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

Steps to Reproduce

  1. Read homepage https://pdoc3.github.io/pdoc/
  2. Execute command above

Additional info

  • pdoc version: 0.5.1

best practices for GitHub pages?

GitHub pages are a common way to host documentation for sites. They require one of the following to host in source code:

  • master branch /docs folder
  • master branch
  • gh-pages branch

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.

Incorrect syntax highlighting

Expected Behavior

Syntax highlighting in code snipets in docstring

Actual Behavior

Syntax highlighted beautifully in some cases, partially in others (only some keywords, etc.), not at all in yet others.

Steps to Reproduce

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.

Additional info

  • pdoc version: current

Support for read-only value descriptors

Expected Behavior

Detect if read-only descriptor is data or method descriptor.

Generate documentation.

Actual Behavior

 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.

Steps to Reproduce

  1. Use read-only value descriptor, for example (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
  1. Run pdoc --html foo.py

Additional info

  • 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))

Feature suggestion: Getting index.html contents from a markdown file

Expected Behavior

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.

Actual Behavior

N/A

Steps to Reproduce

N/A

Additional info

  • pdoc version:
    0.5.1

How to document global variables

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?

Conda package

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!

Mathematics in docstrings ?

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.

live reload when serving locally

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.

Feature Request: allow syntax highlighting without showing source code

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.

Feature request: consider supporting 2-spaces-indentation

Expected Behavior

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.

Actual Behavior

Currently no argument seems to support that.

And by default it will generate badly formatted documentation for such libraries.

Steps to Reproduce

N/A

Additional info

  • pdoc version:
    0.5.1

--html works but --http doesn't

Expected Behavior

Static and live generation should work the same way.

Actual Behavior

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'

Steps to Reproduce

  1. git clone [email protected]:plotly/plotly_express.git (maybe install some deps)
  2. pdoc plotly_express --html vs pdoc plotly_express --http localhost:8080

latex support

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.

Inherited class with overwritten method is not working as advertised in the doc

Expected Behavior

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.

Actual Behavior

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.

Steps to Reproduce

  1. Create this file main.py :
class A:
    def test(self):
        """Docstring for A."""
        print("From A")


class B(A):
    def test(self):
        print("From B")
  1. Run pdoc --html
  2. Open the generated doc and remark that B.test is not listed in the method, as pdoc thinks it is inherited, which it is not.

Additional info

  • pdoc version: 0.5.0, 0.6.0, 0.6.1, 0.6.2

support for google parameters extras (typehint, optional/required)

Expected Behavior

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

Actual Behavior

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.

Steps to Reproduce

see expected vs actual :)

Additional info

  • pdoc version: 0.5.1

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.

please remove my name from this project

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:

pdoc-swastika

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.

Text files generation

Expected Behavior

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

Actual Behavior

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

Additional info

  • pdoc version: pdoc3 0.5.3

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.