Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)

Takayuki Shimizukawa
Takayuki ShimizukawaWeb Developer at BePROUD Inc.
Takayuki Shimizukawa
Sphinx co-maintainer
Sphinx-users.jp
1
Who am I
@shimizukawa
1. Sphinx co-maintainer
2. Sphinx-users.jp
3. PyCon JP committee
 BePROUD co, ltd.
2
http://pycon.jp/
3
Early Bird Registration: 210 tickets.
Speaker Call for Proposals: until July 15th.
4
180 tickets gone
5
Do you know
the docstring?
6
1. def dumps(obj, ensure_ascii=True):
2. """Serialize ``obj`` to a JSON formatted
``str``.
3. """
4.
5. ...
6. return ...
Line 2,3 is a docstring
You can see the string by "help(dumps)"
Docstring
7
Have you written
API docs
using docstrings?
8
What is the reason you do not write docstrings.
 I don't know what/where should I write.
 Are there some docstring format spec?
 It's not beneficial.
I'll tell you a good way to write the docstrings.
9
Goal of this session
 How to generate a doc from Python source
code.
 re-discovering the meaning of docstrings.
10
11
What is Sphinx?
 Sphinx is a Open Source documentation generator.
 Sphinx was created to generate Python official
library's document.
 Sphinx generates doc as several output formats
from the reST text markup.
Sphinx
reSTreSTreStructuredText
(reST) reST Parser
HTML Builder
ePub Builder
LaTeX Builder texlive
HTML
theme
Favorite Editor
12
Many docs are written by Sphinx
For examples
 Python libraries/tools:
Python, Sphinx, Flask, Jinja2, Django, Pyramid,
SQLAlchemy, Numpy, SciPy, scikit-learn,
pandas, fabric, ansible, awscli, …
 Non python libraries/tools:
Chef, CakePHP(2.x), MathJax, Selenium,
Varnish
13
Relation between Sphinx and Docutils
 Sphinx based upon Docutils library
 Docutils/Sphinx supports reStructuredText
it called reST, it's an extensible markup
(PEP287 / accepted at 2002)
Sphinx
reST
Parser
HTML Builder
ePub Builder
LaTeX Builder
HTML
theme
docutils
14
Comparing Docutils and Sphinx
Docutils Sphinx
1. Single page
2. Link to others with full name
3. Cross reference in a page
4. Writers: html, latex, man,
xml, ...
5. Standard reST markup specs
1. Multiple Pages
2. toctree to connect all pages
under single tree structure
3. Cross reference over each other
pages
4. Additional writers: html(w/
themes), pdf(latex), texinfo,
epub, …
5. Additional markup specs:
autodoc directive and so on
15
1. Sphinx introduction & Setup for i18n
Sphinx extensions (built-in)
Sphinx extensions extend reST markup and
provide extra writers.
Sphinx provides these extensions to support
automated API documentation.
 sphinx.ext.autodoc
 sphinx.ext.autosummary
 sphinx.ext.doctest
 sphinx.ext.coverage
Sphinx
reST Parser
HTML Builder
ePub Builder
LaTeX Builder
docutils
autosummary
autodoc
doctest
coverage
16
library code example
1. "utility functions"
2.
3. def dumps(obj, ensure_ascii=True):
4. """Serialize ``obj`` to a JSON formatted ``str``.
5. """
6. ...
deep_thought/utils.py
$ tree /path/to/your-code
+- deep_thought
| +- __init__.py
| +- api.py
| +- calc.py
| +- utils.py
+- setup.py
17
$ pip install sphinx
 Your code and sphinx should be in single
python environment.
 Python version is also important.
How to install Sphinx
18
$ cd /path/to/your-code
$ sphinx-quickstart doc -m
...
Project name: Deep thought
Author name(s): Mice
Project version: 0.7.5
...
...
Finished
 "-m" to generate minimal Makefile/make.bat
 -m is important to introduce this session easily.
How to start a Sphinx project
Keep pressing ENTER key
19
Create a doc directory
$ cd doc
$ make html
...
Build finished. The HTML pages are in _build/html.
"make html" command
generates html files into
_build/html.
make html once
20
Current files structure
$ tree /path/to/your-code
+- deep_thought
| +- __init__.py
| +- api.py
| +- calc.py
| +- utils.py
+- doc
| +- _build/
| | +- html/
| +- _static/
| +- _template/
| +- conf.py
| +- index.rst
| +- make.bat
| +- Makefile
+- setup.py
Scaffold files
Build output
Library files
21
22
$ tree /path/to/your-code
+- deep_thought
| +- __init__.py
| +- api.py
| +- calc.py
| +- utils.py
+- doc
| +- _build/
| | +- html/
| +- _static/
| +- _template/
| +- conf.py
| +- index.rst
| +- make.bat
| +- Makefile
+- setup.py
1. import os
2. import sys
3. sys.path.insert(0, os.path.abspath('..'))
4. extensions = [
5. 'sphinx.ext.autodoc',
6. ]
setup autodoc extension
doc/conf.py
23
Line-3: add your library path to
import them from Sphinx autodoc.
Line-5: add 'sphinx.ext.autodoc' to
use the extension.
Add automodule directive to your doc
1. Deep thought API
2. ================
3.
4. .. automodule:: deep_thought.utils
5. :members:
6.
1. "utility functions"
2.
3. def dumps(obj, ensure_ascii=True):
4. """Serialize ``obj`` to a JSON formatted ``str``.
5. """
6. ...
doc/index.rst
24
deep_thought/utils.py
Line-4: automodule directive import specified
module and inspect the module.
Line-5: :members: option will inspects all members
of module not only module docstring.
$ cd doc
$ make html
...
Build finished. The HTML pages are in _build/html.
make html
25
How does it work?
autodoc directive generates intermediate reST
internally:
1. Deep thought API
2. ================
3.
4. .. py:module:: deep_thought.utils
5.
6. utility functions
7.
8. .. py:function:: dumps(obj, ensure_ascii=True)
9. :module: deep_thought.utils
10.
11. Serialize ``obj`` to a JSON formatted :class:`str`.
doc/index.rst
Intermediate
reST
26
$ make html SPHINXOPTS=-vvv
...
...
[autodoc] output:
.. py:module:: deep_thought.utils
utility functions
.. py:function:: dumps(obj, ensure_ascii=True)
:module: deep_thought.utils
Serialize ``obj`` to a JSON formatted :class:`str`.
You can see the reST with -vvv option
27
Take care!
Sphinx autodoc import your code
to get docstrings.
It means autodoc will execute code
at module global level.
28
Danger code
1. import os
2.
3. def delete_world():
4. os.system('sudo rm -Rf /')
5.
6. delete_world() # will be executed at "make html"
danger.py
29
execution guard on import
1. import os
2.
3. def delete_world():
4. os.system('sudo rm -Rf /')
5.
6. delete_world() # will be executed at "make html"
danger.py
1. import os
2.
3. def delete_world():
4. os.system('sudo rm -Rf /')
5.
6. if __name__ == '__main__':
7. delete_world() # doesn't execute at "make html"
safer.py
Execution guard
30
execution guard on import
1. import os
2.
3. def delete_world():
4. os.system('sudo rm -Rf /')
5.
6. delete_world() # will be executed at "make html"
danger.py
1. import os
2.
3. def delete_world():
4. os.system('sudo rm -Rf /')
5.
6. if __name__ == '__main__':
7. delete_world() # doesn't execute at "make html"
safer.py
Execution guard
31
"Oh, I can't understand the type of arguments
and meanings even reading this!"
32
Lacking necessary information
1. def dumps(obj, ensure_ascii=True):
2. """Serialize ``obj`` to a JSON formatted
3. :class:`str`.
4.
5. :param dict obj: dict type object to serialize.
6. :param bool ensure_ascii: Default is True. If
7. False, all non-ASCII characters are not ...
8. :return: JSON formatted string
9. :rtype: str
10. """
 http://sphinx-doc.org/domains.html#info-field-lists
"info field lists" for arguments
deep_thought/utils.py
33
def dumps(obj, ensure_ascii=True):
"""Serialize ``obj`` to a JSON formatted :class:`str`.
:param dict obj: dict type object to serialize.
:param bool ensure_ascii: Default is True. If
False, all non-ASCII characters are not ...
:return: JSON formatted string
:rtype: str
"""
...
"info field lists" for arguments
deep_thought/utils.py
34
Cross-reference to functions
1. Examples
2. ==========
3.
4. This is a usage of :func:`deep_thought.utils.dumps`
blah blah blah. ...
examples.py
reference
(hyper link)
35
36
Code example in a docstring
1. def dumps(obj, ensure_ascii=True):
2. """Serialize ``obj`` to a JSON formatted
3. :class:`str`.
4.
5. For example:
6.
7. >>> from deep_thought.utils import dumps
8. >>> data = dict(spam=1, ham='egg')
9. >>> dumps(data)
10. '{spam: 1, ham: "egg"}'
11.
12. :param dict obj: dict type object to serialize.
13. :param bool ensure_ascii: Default is True. If
14. False, all non-ASCII characters are not ...
deep_thought/utils.py
37
doctest
block
You can copy & paste the red lines
from python interactive shell.
Syntax highlighted output
$ make html
...
rendered
doctest
block
38
 You can expect that developers will update code
examples when the interface is changed.
We expect ...
1. def dumps(obj, ensure_ascii=True):
2. """Serialize ``obj`` to a JSON formatted
3. :class:`str`.
4.
5. For example:
6.
7. >>> from deep_thought.utils import dumps
8. >>> data = dict(spam=1, ham='egg')
9. >>> dumps(data)
10. '{spam: 1, ham: "egg"}'
The code example is
very close from
implementation!!
deep_thought/utils.py
39
 ̄\_(ツ)_/ ̄
40
doctest builder
41
1. ...
2.
3. extensions = [
4. 'sphinx.ext.autodoc',
5. 'sphinx.ext.doctest',
6. ]
7.
 Line-5: add 'sphinx.ext.doctest' extension.
setup doctest extension
doc/conf.py
append
42
$ make doctest
...
Document: api
-------------
********************************************************
File "api.rst", line 11, in default
Failed example:
dumps(data)
Expected:
'{spam: 1, ham: "egg"}'
Got:
'to-be-implemented'
...
make: *** [doctest] Error 1
Result of "make doctest"
43
Result of doctest
44
Individual pages for each modules
api.html
calc.html
utils.html
45
1. deep_thought.utils
2. ===================
3. .. automodule:: deep_thought.utils
4. :members:
doc/deep_thought.utils.rst
1. deep_thought.utils
2. ===================
3. .. automodule:: deep_thought.utils
4. :members:
Add automodule directive to your doc
doc/deep_thought.utils.rst
1. deep_thought.calc
2. ==================
3. .. automodule:: deep_thought.calc
4. :members:
1. deep_thought.api
2. ==================
3. .. automodule:: deep_thought.api
4. :members:
doc/deep_thought.calc.rst
doc/deep_thought.api.rst
And many many reST files ... 46
 ̄\_(ツ)_/ ̄
47
autosummary extension
48
1. ...
2.
3. extensions = [
4. 'sphinx.ext.autodoc',
5. 'sphinx.ext.doctest',
6. 'sphinx.ext.autosummary',
7. ]
8. autodoc_default_flags = ['members']
9. autosummary_generate = True
10.
 Line-9: autosummary_generate = True
generates reST files what you will specify with
using autosummary directive.
setup autosummary extension
doc/conf.py
append
append
append
49
1. Deep thought API
2. ================
3.
4. .. autosummary::
5. :toctree: generated
6.
7. deep_thought.api
8. deep_thought.calc
9. deep_thought.utils
10.
Replace automodule with autosummary
doc/index.rst
$ make html
...
50
Output of autosummary
autosummary directive
become TOC for each
module pages.
51
52
1. def spam():
2. ...
3. return res
4.
5. def ham():
6. ...
7. return res
8.
9. def egg():
10. ...
11. return res
How to find undocumented funcs?
doc/nodoc.py
53
coverage extension
54
1. ...
2.
3. extensions = [
4. 'sphinx.ext.autodoc',
5. 'sphinx.ext.doctest',
6. 'sphinx.ext.autosummary',
7. 'sphinx.ext.coverage',
8. ]
9. autodoc_default_flags = ['members']
10. autosummary_generate = True
setup coverage extension
doc/conf.py
append
 Line-7: add 'sphinx.ext.coverage' extension.
55
make coverage and check the result
$ make coverage
...
Testing of coverage in the sources finished, look at the
results in _buildcoverage.
$ ls _build/coverage
c.txt python.txt undoc.pickle
1. Undocumented Python objects
2. ===========================
3. deep_thought.utils
4. ------------------
5. Functions:
6. * egg
_build/coverage/python.txt
This function doesn't have a doc!
56
CAUTION!
1. Undocumented Python objects
2. ===========================
3. deep_thought.utils
4. ------------------
5. Functions:
6. * egg
python.txt
$ make coverage
...
Testing of coverage in the sources finished, look at the
results in _buildcoverage.
$ ls _build/coverage
c.txt python.txt undoc.pickle
The command always return ZERO
coverage.xml is not exist
reST format for whom?
57
Let's make Pull-Request!
We are waiting for your contribution
to solve the problem.
(bow)
58
59
Why don't you write docstrings?
 I don't know what/where should I write.
 Let's write a description, arguments and doctest blocks
at the next line of function signature.
 Are there some docstring format spec?
 Yes, you can use "info field list" for argument spec and
you can use doctest block for code example.
 It's not beneficial.
 You can use autodoc, autosummary, doctest and
coverage to make it beneficial.
60
61
1. Options
62
Options for autodoc
 :members: blah
 To document just specified members. Empty is ALL.
 :undoc-members: ...
 To document members which doesn't have docstring.
 :private-members: ...
 To document private members which name starts with
underscore.
 :special-members: ...
 To document starts with underscore underscore.
 :inherited-members: ...
 To document inherited from super class.
63
2. Directives for Web API
64
sphinxcontrib-httpdomain 3rd-party ext
http domain's get directive
render
page
render routing table (index)
http highlighter
It also contains sphinxcontrib.autohttp.flask, .bottle, .tornado extensions
Listing
New Index
65
3. Document translation
66
Translation into other languages
$ make gettext
...
Build finished. The message catalogs are in
_build/gettext.
$ sphinx-intl update -p _build/gettext -l zh_tw
#: ../../../deep_thought/utils.pydocstring of
deep_thought.utils.dumps:1
msgid "Serialize ``obj`` to a JSON formatted :class:`str`."
msgstr "序列化 ``obj`` 要JSON格式 :class:`str`."
msgid "For example:"
msgstr "例如:"
locale/zh_tw/LC_MESSAGES/generated.po
language = 'zh_tw'
locale_dirs = ['locale']
conf.py
$ make html
...
Build finished. The HTML pages are in _build/html.
67
Questions?
@shimizukawa
68
Thanks :)
69
1 of 69

Recommended

Easy contributable internationalization process with Sphinx (PyCon APAC 2015 ... by
Easy contributable internationalization process with Sphinx (PyCon APAC 2015 ...Easy contributable internationalization process with Sphinx (PyCon APAC 2015 ...
Easy contributable internationalization process with Sphinx (PyCon APAC 2015 ...Takayuki Shimizukawa
2.3K views55 slides
Sphinx autodoc - automated api documentation - PyCon.MY 2015 by
Sphinx autodoc - automated api documentation - PyCon.MY 2015Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Takayuki Shimizukawa
2.4K views73 slides
Easy contributable internationalization process with Sphinx @ pyconmy2015 by
Easy contributable internationalization process with Sphinx @ pyconmy2015Easy contributable internationalization process with Sphinx @ pyconmy2015
Easy contributable internationalization process with Sphinx @ pyconmy2015Takayuki Shimizukawa
1.9K views62 slides
Sphinx autodoc - automated api documentation - PyCon.KR 2015 by
Sphinx autodoc - automated api documentation - PyCon.KR 2015Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015Takayuki Shimizukawa
2.5K views76 slides
Learning Python from Data by
Learning Python from DataLearning Python from Data
Learning Python from DataMosky Liu
2.4K views115 slides
Oktavia Search Engine - pyconjp2014 by
Oktavia Search Engine - pyconjp2014Oktavia Search Engine - pyconjp2014
Oktavia Search Engine - pyconjp2014Yoshiki Shibukawa
3.9K views37 slides

More Related Content

What's hot

pyconjp2015_talk_Translation of Python Program__ by
pyconjp2015_talk_Translation of Python Program__pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__Renyuan Lyu
4.2K views44 slides
Programming with Python - Adv. by
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.Mosky Liu
2.5K views61 slides
Introduction to Programming in Go by
Introduction to Programming in GoIntroduction to Programming in Go
Introduction to Programming in GoAmr Hassan
579 views105 slides
Php’s guts by
Php’s gutsPhp’s guts
Php’s gutsElizabeth Smith
1.2K views41 slides
Happy Go Programming Part 1 by
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1Lin Yo-An
5.1K views92 slides
Fighting API Compatibility On Fluentd Using "Black Magic" by
Fighting API Compatibility On Fluentd Using "Black Magic"Fighting API Compatibility On Fluentd Using "Black Magic"
Fighting API Compatibility On Fluentd Using "Black Magic"SATOSHI TAGOMORI
7.4K views71 slides

What's hot(20)

pyconjp2015_talk_Translation of Python Program__ by Renyuan Lyu
pyconjp2015_talk_Translation of Python Program__pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__
Renyuan Lyu4.2K views
Programming with Python - Adv. by Mosky Liu
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu2.5K views
Introduction to Programming in Go by Amr Hassan
Introduction to Programming in GoIntroduction to Programming in Go
Introduction to Programming in Go
Amr Hassan579 views
Happy Go Programming Part 1 by Lin Yo-An
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
Lin Yo-An5.1K views
Fighting API Compatibility On Fluentd Using "Black Magic" by SATOSHI TAGOMORI
Fighting API Compatibility On Fluentd Using "Black Magic"Fighting API Compatibility On Fluentd Using "Black Magic"
Fighting API Compatibility On Fluentd Using "Black Magic"
SATOSHI TAGOMORI7.4K views
Programming with Python - Basic by Mosky Liu
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
Mosky Liu8.2K views
pa-pe-pi-po-pure Python Text Processing by Rodrigo Senra
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
Rodrigo Senra2.5K views
Introduction to Clime by Mosky Liu
Introduction to ClimeIntroduction to Clime
Introduction to Clime
Mosky Liu6.9K views
Python Intro by Tim Penhey
Python IntroPython Intro
Python Intro
Tim Penhey3.4K views
Reversing the dropbox client on windows by extremecoders
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
extremecoders28.4K views
Why Python (for Statisticians) by Matt Harrison
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
Matt Harrison2.8K views
PyCon 2013 : Scripting to PyPi to GitHub and More by Matt Harrison
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison5.7K views
Memory Management In Python The Basics by Nina Zakharenko
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
Nina Zakharenko32.5K views

Similar to Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)

Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao) by
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Takayuki Shimizukawa
7.7K views69 slides
Intro by
IntroIntro
IntroDaniel Greenfeld
1.6K views61 slides
Flask jwt authentication tutorial by
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
361 views38 slides
Intro to Python by
Intro to PythonIntro to Python
Intro to PythonDaniel Greenfeld
5.2K views61 slides
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202... by
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...amit kuraria
61 views20 slides
Boost.Python: C++ and Python Integration by
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
3.3K views23 slides

Similar to Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)(20)

Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao) by Takayuki Shimizukawa
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Flask jwt authentication tutorial by Katy Slemon
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
Katy Slemon361 views
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202... by amit kuraria
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
amit kuraria61 views
Presentation of Python, Django, DockerStack by David Sanchez
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
David Sanchez827 views
Easy contributable internationalization process with Sphinx @ PyCon APAC 2016 by Takayuki Shimizukawa
Easy contributable internationalization process with Sphinx @ PyCon APAC 2016Easy contributable internationalization process with Sphinx @ PyCon APAC 2016
Easy contributable internationalization process with Sphinx @ PyCon APAC 2016
descriptive programming by Anand Dhana
descriptive programmingdescriptive programming
descriptive programming
Anand Dhana819 views
Don't Be Afraid of Abstract Syntax Trees by Jamund Ferguson
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
Jamund Ferguson3.3K views
Python introduction by Roger Xia
Python introductionPython introduction
Python introduction
Roger Xia1.1K views
嵌入式Linux課程-GNU Toolchain by 艾鍗科技
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
艾鍗科技2.4K views
Ts archiving by Confiz
Ts   archivingTs   archiving
Ts archiving
Confiz603 views
An Overview Of Python With Functional Programming by Adam Getchell
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell656 views
Python: an introduction for PHP webdevelopers by Glenn De Backer
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopers
Glenn De Backer1.5K views
node.js, javascript and the future by Jeff Miccolis
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the future
Jeff Miccolis4.8K views
2018 cosup-delete unused python code safely - english by Jen Yee Hong
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
Jen Yee Hong1.7K views
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder by Andrey Karpov
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
Andrey Karpov505 views

More from Takayuki Shimizukawa

IKEv2-VPN PyHackCon2023 by
IKEv2-VPN PyHackCon2023IKEv2-VPN PyHackCon2023
IKEv2-VPN PyHackCon2023Takayuki Shimizukawa
20 views23 slides
Django ORM道場:クエリの基本を押さえ,より良い形を身に付けよう by
Django ORM道場:クエリの基本を押さえ,より良い形を身に付けようDjango ORM道場:クエリの基本を押さえ,より良い形を身に付けよう
Django ORM道場:クエリの基本を押さえ,より良い形を身に付けようTakayuki Shimizukawa
190 views52 slides
OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022 by
OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022
OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022Takayuki Shimizukawa
1.5K views46 slides
Webアプリを並行開発する際のマイグレーション戦略 by
Webアプリを並行開発する際のマイグレーション戦略Webアプリを並行開発する際のマイグレーション戦略
Webアプリを並行開発する際のマイグレーション戦略Takayuki Shimizukawa
4.8K views49 slides
『自走プログラマー』 が我々に必要だった理由 by
『自走プログラマー』 が我々に必要だった理由『自走プログラマー』 が我々に必要だった理由
『自走プログラマー』 が我々に必要だった理由Takayuki Shimizukawa
740 views22 slides
エキスパートPythonプログラミング改訂3版の読みどころ by
エキスパートPythonプログラミング改訂3版の読みどころエキスパートPythonプログラミング改訂3版の読みどころ
エキスパートPythonプログラミング改訂3版の読みどころTakayuki Shimizukawa
1.8K views23 slides

More from Takayuki Shimizukawa(20)

Django ORM道場:クエリの基本を押さえ,より良い形を身に付けよう by Takayuki Shimizukawa
Django ORM道場:クエリの基本を押さえ,より良い形を身に付けようDjango ORM道場:クエリの基本を押さえ,より良い形を身に付けよう
Django ORM道場:クエリの基本を押さえ,より良い形を身に付けよう
OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022 by Takayuki Shimizukawa
OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022
OpenTelemetryでWebシステムの処理を追跡しよう - DjangoCongress JP 2022
Webアプリを並行開発する際のマイグレーション戦略 by Takayuki Shimizukawa
Webアプリを並行開発する際のマイグレーション戦略Webアプリを並行開発する際のマイグレーション戦略
Webアプリを並行開発する際のマイグレーション戦略
『自走プログラマー』 が我々に必要だった理由 by Takayuki Shimizukawa
『自走プログラマー』 が我々に必要だった理由『自走プログラマー』 が我々に必要だった理由
『自走プログラマー』 が我々に必要だった理由
エキスパートPythonプログラミング改訂3版の読みどころ by Takayuki Shimizukawa
エキスパートPythonプログラミング改訂3版の読みどころエキスパートPythonプログラミング改訂3版の読みどころ
エキスパートPythonプログラミング改訂3版の読みどころ
RLSを用いたマルチテナント実装 for Django by Takayuki Shimizukawa
RLSを用いたマルチテナント実装 for DjangoRLSを用いたマルチテナント実装 for Django
RLSを用いたマルチテナント実装 for Django
【修正版】Django + SQLAlchemy: シンプルWay by Takayuki Shimizukawa
【修正版】Django + SQLAlchemy: シンプルWay【修正版】Django + SQLAlchemy: シンプルWay
【修正版】Django + SQLAlchemy: シンプルWay
Takayuki Shimizukawa11.2K views
Sphinx customization for OGP support at SphinxCon JP 2018 by Takayuki Shimizukawa
Sphinx customization for OGP support at SphinxCon JP 2018Sphinx customization for OGP support at SphinxCon JP 2018
Sphinx customization for OGP support at SphinxCon JP 2018
Pythonはどうやってlen関数で長さを手にいれているの? by Takayuki Shimizukawa
Pythonはどうやってlen関数で長さを手にいれているの?Pythonはどうやってlen関数で長さを手にいれているの?
Pythonはどうやってlen関数で長さを手にいれているの?
Takayuki Shimizukawa38.1K views
仕事で使うちょっとしたコードをOSSとして開発メンテしていく - Django Redshift Backend の開発 - PyCon JP 2016 by Takayuki Shimizukawa
仕事で使うちょっとしたコードをOSSとして開発メンテしていく- Django Redshift Backend の開発 - PyCon JP 2016仕事で使うちょっとしたコードをOSSとして開発メンテしていく- Django Redshift Backend の開発 - PyCon JP 2016
仕事で使うちょっとしたコードをOSSとして開発メンテしていく - Django Redshift Backend の開発 - PyCon JP 2016
素振りのススメ at Python入門者の集い by Takayuki Shimizukawa
素振りのススメ at Python入門者の集い素振りのススメ at Python入門者の集い
素振りのススメ at Python入門者の集い
JUS関西 Sphinxワークショップ@関西 Sphinx紹介 by Takayuki Shimizukawa
JUS関西 Sphinxワークショップ@関西 Sphinx紹介JUS関西 Sphinxワークショップ@関西 Sphinx紹介
JUS関西 Sphinxワークショップ@関西 Sphinx紹介
Sphinxで作る貢献しやすい ドキュメント翻訳の仕組み by Takayuki Shimizukawa
Sphinxで作る貢献しやすいドキュメント翻訳の仕組みSphinxで作る貢献しやすいドキュメント翻訳の仕組み
Sphinxで作る貢献しやすい ドキュメント翻訳の仕組み
Takayuki Shimizukawa28.1K views
Easy contributable internationalization process with Sphinx @ pyconsg2015 by Takayuki Shimizukawa
Easy contributable internationalization process with Sphinx @ pyconsg2015Easy contributable internationalization process with Sphinx @ pyconsg2015
Easy contributable internationalization process with Sphinx @ pyconsg2015
PyPro2の読みどころ紹介:Python開発の過去と現在 - BPStudy93 by Takayuki Shimizukawa
PyPro2の読みどころ紹介:Python開発の過去と現在 - BPStudy93PyPro2の読みどころ紹介:Python開発の過去と現在 - BPStudy93
PyPro2の読みどころ紹介:Python開発の過去と現在 - BPStudy93
PyPro2の読みどころ紹介:Python開発の過去と現在 by Takayuki Shimizukawa
PyPro2の読みどころ紹介:Python開発の過去と現在PyPro2の読みどころ紹介:Python開発の過去と現在
PyPro2の読みどころ紹介:Python開発の過去と現在
Takayuki Shimizukawa11.9K views

Recently uploaded

Mini-Track: Challenges to Network Automation Adoption by
Mini-Track: Challenges to Network Automation AdoptionMini-Track: Challenges to Network Automation Adoption
Mini-Track: Challenges to Network Automation AdoptionNetwork Automation Forum
13 views27 slides
Design Driven Network Assurance by
Design Driven Network AssuranceDesign Driven Network Assurance
Design Driven Network AssuranceNetwork Automation Forum
15 views42 slides
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdfDr. Jimmy Schwarzkopf
20 views29 slides
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensorssugiuralab
21 views15 slides
Serverless computing with Google Cloud (2023-24) by
Serverless computing with Google Cloud (2023-24)Serverless computing with Google Cloud (2023-24)
Serverless computing with Google Cloud (2023-24)wesley chun
11 views33 slides
Powerful Google developer tools for immediate impact! (2023-24) by
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)wesley chun
10 views38 slides

Recently uploaded(20)

STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab21 views
Serverless computing with Google Cloud (2023-24) by wesley chun
Serverless computing with Google Cloud (2023-24)Serverless computing with Google Cloud (2023-24)
Serverless computing with Google Cloud (2023-24)
wesley chun11 views
Powerful Google developer tools for immediate impact! (2023-24) by wesley chun
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)
wesley chun10 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
Future of AR - Facebook Presentation by ssuserb54b561
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
ssuserb54b56115 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely25 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman36 views
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
6g - REPORT.pdf by Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex10 views
"Running students' code in isolation. The hard way", Yurii Holiuk by Fwdays
"Running students' code in isolation. The hard way", Yurii Holiuk "Running students' code in isolation. The hard way", Yurii Holiuk
"Running students' code in isolation. The hard way", Yurii Holiuk
Fwdays17 views

Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)

  • 2. Who am I @shimizukawa 1. Sphinx co-maintainer 2. Sphinx-users.jp 3. PyCon JP committee  BePROUD co, ltd. 2
  • 4. Early Bird Registration: 210 tickets. Speaker Call for Proposals: until July 15th. 4 180 tickets gone
  • 5. 5
  • 6. Do you know the docstring? 6
  • 7. 1. def dumps(obj, ensure_ascii=True): 2. """Serialize ``obj`` to a JSON formatted ``str``. 3. """ 4. 5. ... 6. return ... Line 2,3 is a docstring You can see the string by "help(dumps)" Docstring 7
  • 8. Have you written API docs using docstrings? 8
  • 9. What is the reason you do not write docstrings.  I don't know what/where should I write.  Are there some docstring format spec?  It's not beneficial. I'll tell you a good way to write the docstrings. 9
  • 10. Goal of this session  How to generate a doc from Python source code.  re-discovering the meaning of docstrings. 10
  • 11. 11
  • 12. What is Sphinx?  Sphinx is a Open Source documentation generator.  Sphinx was created to generate Python official library's document.  Sphinx generates doc as several output formats from the reST text markup. Sphinx reSTreSTreStructuredText (reST) reST Parser HTML Builder ePub Builder LaTeX Builder texlive HTML theme Favorite Editor 12
  • 13. Many docs are written by Sphinx For examples  Python libraries/tools: Python, Sphinx, Flask, Jinja2, Django, Pyramid, SQLAlchemy, Numpy, SciPy, scikit-learn, pandas, fabric, ansible, awscli, …  Non python libraries/tools: Chef, CakePHP(2.x), MathJax, Selenium, Varnish 13
  • 14. Relation between Sphinx and Docutils  Sphinx based upon Docutils library  Docutils/Sphinx supports reStructuredText it called reST, it's an extensible markup (PEP287 / accepted at 2002) Sphinx reST Parser HTML Builder ePub Builder LaTeX Builder HTML theme docutils 14
  • 15. Comparing Docutils and Sphinx Docutils Sphinx 1. Single page 2. Link to others with full name 3. Cross reference in a page 4. Writers: html, latex, man, xml, ... 5. Standard reST markup specs 1. Multiple Pages 2. toctree to connect all pages under single tree structure 3. Cross reference over each other pages 4. Additional writers: html(w/ themes), pdf(latex), texinfo, epub, … 5. Additional markup specs: autodoc directive and so on 15 1. Sphinx introduction & Setup for i18n
  • 16. Sphinx extensions (built-in) Sphinx extensions extend reST markup and provide extra writers. Sphinx provides these extensions to support automated API documentation.  sphinx.ext.autodoc  sphinx.ext.autosummary  sphinx.ext.doctest  sphinx.ext.coverage Sphinx reST Parser HTML Builder ePub Builder LaTeX Builder docutils autosummary autodoc doctest coverage 16
  • 17. library code example 1. "utility functions" 2. 3. def dumps(obj, ensure_ascii=True): 4. """Serialize ``obj`` to a JSON formatted ``str``. 5. """ 6. ... deep_thought/utils.py $ tree /path/to/your-code +- deep_thought | +- __init__.py | +- api.py | +- calc.py | +- utils.py +- setup.py 17
  • 18. $ pip install sphinx  Your code and sphinx should be in single python environment.  Python version is also important. How to install Sphinx 18
  • 19. $ cd /path/to/your-code $ sphinx-quickstart doc -m ... Project name: Deep thought Author name(s): Mice Project version: 0.7.5 ... ... Finished  "-m" to generate minimal Makefile/make.bat  -m is important to introduce this session easily. How to start a Sphinx project Keep pressing ENTER key 19 Create a doc directory
  • 20. $ cd doc $ make html ... Build finished. The HTML pages are in _build/html. "make html" command generates html files into _build/html. make html once 20
  • 21. Current files structure $ tree /path/to/your-code +- deep_thought | +- __init__.py | +- api.py | +- calc.py | +- utils.py +- doc | +- _build/ | | +- html/ | +- _static/ | +- _template/ | +- conf.py | +- index.rst | +- make.bat | +- Makefile +- setup.py Scaffold files Build output Library files 21
  • 22. 22
  • 23. $ tree /path/to/your-code +- deep_thought | +- __init__.py | +- api.py | +- calc.py | +- utils.py +- doc | +- _build/ | | +- html/ | +- _static/ | +- _template/ | +- conf.py | +- index.rst | +- make.bat | +- Makefile +- setup.py 1. import os 2. import sys 3. sys.path.insert(0, os.path.abspath('..')) 4. extensions = [ 5. 'sphinx.ext.autodoc', 6. ] setup autodoc extension doc/conf.py 23 Line-3: add your library path to import them from Sphinx autodoc. Line-5: add 'sphinx.ext.autodoc' to use the extension.
  • 24. Add automodule directive to your doc 1. Deep thought API 2. ================ 3. 4. .. automodule:: deep_thought.utils 5. :members: 6. 1. "utility functions" 2. 3. def dumps(obj, ensure_ascii=True): 4. """Serialize ``obj`` to a JSON formatted ``str``. 5. """ 6. ... doc/index.rst 24 deep_thought/utils.py Line-4: automodule directive import specified module and inspect the module. Line-5: :members: option will inspects all members of module not only module docstring.
  • 25. $ cd doc $ make html ... Build finished. The HTML pages are in _build/html. make html 25
  • 26. How does it work? autodoc directive generates intermediate reST internally: 1. Deep thought API 2. ================ 3. 4. .. py:module:: deep_thought.utils 5. 6. utility functions 7. 8. .. py:function:: dumps(obj, ensure_ascii=True) 9. :module: deep_thought.utils 10. 11. Serialize ``obj`` to a JSON formatted :class:`str`. doc/index.rst Intermediate reST 26
  • 27. $ make html SPHINXOPTS=-vvv ... ... [autodoc] output: .. py:module:: deep_thought.utils utility functions .. py:function:: dumps(obj, ensure_ascii=True) :module: deep_thought.utils Serialize ``obj`` to a JSON formatted :class:`str`. You can see the reST with -vvv option 27
  • 28. Take care! Sphinx autodoc import your code to get docstrings. It means autodoc will execute code at module global level. 28
  • 29. Danger code 1. import os 2. 3. def delete_world(): 4. os.system('sudo rm -Rf /') 5. 6. delete_world() # will be executed at "make html" danger.py 29
  • 30. execution guard on import 1. import os 2. 3. def delete_world(): 4. os.system('sudo rm -Rf /') 5. 6. delete_world() # will be executed at "make html" danger.py 1. import os 2. 3. def delete_world(): 4. os.system('sudo rm -Rf /') 5. 6. if __name__ == '__main__': 7. delete_world() # doesn't execute at "make html" safer.py Execution guard 30
  • 31. execution guard on import 1. import os 2. 3. def delete_world(): 4. os.system('sudo rm -Rf /') 5. 6. delete_world() # will be executed at "make html" danger.py 1. import os 2. 3. def delete_world(): 4. os.system('sudo rm -Rf /') 5. 6. if __name__ == '__main__': 7. delete_world() # doesn't execute at "make html" safer.py Execution guard 31
  • 32. "Oh, I can't understand the type of arguments and meanings even reading this!" 32 Lacking necessary information
  • 33. 1. def dumps(obj, ensure_ascii=True): 2. """Serialize ``obj`` to a JSON formatted 3. :class:`str`. 4. 5. :param dict obj: dict type object to serialize. 6. :param bool ensure_ascii: Default is True. If 7. False, all non-ASCII characters are not ... 8. :return: JSON formatted string 9. :rtype: str 10. """  http://sphinx-doc.org/domains.html#info-field-lists "info field lists" for arguments deep_thought/utils.py 33
  • 34. def dumps(obj, ensure_ascii=True): """Serialize ``obj`` to a JSON formatted :class:`str`. :param dict obj: dict type object to serialize. :param bool ensure_ascii: Default is True. If False, all non-ASCII characters are not ... :return: JSON formatted string :rtype: str """ ... "info field lists" for arguments deep_thought/utils.py 34
  • 35. Cross-reference to functions 1. Examples 2. ========== 3. 4. This is a usage of :func:`deep_thought.utils.dumps` blah blah blah. ... examples.py reference (hyper link) 35
  • 36. 36
  • 37. Code example in a docstring 1. def dumps(obj, ensure_ascii=True): 2. """Serialize ``obj`` to a JSON formatted 3. :class:`str`. 4. 5. For example: 6. 7. >>> from deep_thought.utils import dumps 8. >>> data = dict(spam=1, ham='egg') 9. >>> dumps(data) 10. '{spam: 1, ham: "egg"}' 11. 12. :param dict obj: dict type object to serialize. 13. :param bool ensure_ascii: Default is True. If 14. False, all non-ASCII characters are not ... deep_thought/utils.py 37 doctest block You can copy & paste the red lines from python interactive shell.
  • 38. Syntax highlighted output $ make html ... rendered doctest block 38
  • 39.  You can expect that developers will update code examples when the interface is changed. We expect ... 1. def dumps(obj, ensure_ascii=True): 2. """Serialize ``obj`` to a JSON formatted 3. :class:`str`. 4. 5. For example: 6. 7. >>> from deep_thought.utils import dumps 8. >>> data = dict(spam=1, ham='egg') 9. >>> dumps(data) 10. '{spam: 1, ham: "egg"}' The code example is very close from implementation!! deep_thought/utils.py 39
  • 42. 1. ... 2. 3. extensions = [ 4. 'sphinx.ext.autodoc', 5. 'sphinx.ext.doctest', 6. ] 7.  Line-5: add 'sphinx.ext.doctest' extension. setup doctest extension doc/conf.py append 42
  • 43. $ make doctest ... Document: api ------------- ******************************************************** File "api.rst", line 11, in default Failed example: dumps(data) Expected: '{spam: 1, ham: "egg"}' Got: 'to-be-implemented' ... make: *** [doctest] Error 1 Result of "make doctest" 43 Result of doctest
  • 44. 44
  • 45. Individual pages for each modules api.html calc.html utils.html 45 1. deep_thought.utils 2. =================== 3. .. automodule:: deep_thought.utils 4. :members: doc/deep_thought.utils.rst
  • 46. 1. deep_thought.utils 2. =================== 3. .. automodule:: deep_thought.utils 4. :members: Add automodule directive to your doc doc/deep_thought.utils.rst 1. deep_thought.calc 2. ================== 3. .. automodule:: deep_thought.calc 4. :members: 1. deep_thought.api 2. ================== 3. .. automodule:: deep_thought.api 4. :members: doc/deep_thought.calc.rst doc/deep_thought.api.rst And many many reST files ... 46
  • 49. 1. ... 2. 3. extensions = [ 4. 'sphinx.ext.autodoc', 5. 'sphinx.ext.doctest', 6. 'sphinx.ext.autosummary', 7. ] 8. autodoc_default_flags = ['members'] 9. autosummary_generate = True 10.  Line-9: autosummary_generate = True generates reST files what you will specify with using autosummary directive. setup autosummary extension doc/conf.py append append append 49
  • 50. 1. Deep thought API 2. ================ 3. 4. .. autosummary:: 5. :toctree: generated 6. 7. deep_thought.api 8. deep_thought.calc 9. deep_thought.utils 10. Replace automodule with autosummary doc/index.rst $ make html ... 50
  • 51. Output of autosummary autosummary directive become TOC for each module pages. 51
  • 52. 52
  • 53. 1. def spam(): 2. ... 3. return res 4. 5. def ham(): 6. ... 7. return res 8. 9. def egg(): 10. ... 11. return res How to find undocumented funcs? doc/nodoc.py 53
  • 55. 1. ... 2. 3. extensions = [ 4. 'sphinx.ext.autodoc', 5. 'sphinx.ext.doctest', 6. 'sphinx.ext.autosummary', 7. 'sphinx.ext.coverage', 8. ] 9. autodoc_default_flags = ['members'] 10. autosummary_generate = True setup coverage extension doc/conf.py append  Line-7: add 'sphinx.ext.coverage' extension. 55
  • 56. make coverage and check the result $ make coverage ... Testing of coverage in the sources finished, look at the results in _buildcoverage. $ ls _build/coverage c.txt python.txt undoc.pickle 1. Undocumented Python objects 2. =========================== 3. deep_thought.utils 4. ------------------ 5. Functions: 6. * egg _build/coverage/python.txt This function doesn't have a doc! 56
  • 57. CAUTION! 1. Undocumented Python objects 2. =========================== 3. deep_thought.utils 4. ------------------ 5. Functions: 6. * egg python.txt $ make coverage ... Testing of coverage in the sources finished, look at the results in _buildcoverage. $ ls _build/coverage c.txt python.txt undoc.pickle The command always return ZERO coverage.xml is not exist reST format for whom? 57
  • 58. Let's make Pull-Request! We are waiting for your contribution to solve the problem. (bow) 58
  • 59. 59
  • 60. Why don't you write docstrings?  I don't know what/where should I write.  Let's write a description, arguments and doctest blocks at the next line of function signature.  Are there some docstring format spec?  Yes, you can use "info field list" for argument spec and you can use doctest block for code example.  It's not beneficial.  You can use autodoc, autosummary, doctest and coverage to make it beneficial. 60
  • 61. 61
  • 63. Options for autodoc  :members: blah  To document just specified members. Empty is ALL.  :undoc-members: ...  To document members which doesn't have docstring.  :private-members: ...  To document private members which name starts with underscore.  :special-members: ...  To document starts with underscore underscore.  :inherited-members: ...  To document inherited from super class. 63
  • 64. 2. Directives for Web API 64
  • 65. sphinxcontrib-httpdomain 3rd-party ext http domain's get directive render page render routing table (index) http highlighter It also contains sphinxcontrib.autohttp.flask, .bottle, .tornado extensions Listing New Index 65
  • 67. Translation into other languages $ make gettext ... Build finished. The message catalogs are in _build/gettext. $ sphinx-intl update -p _build/gettext -l zh_tw #: ../../../deep_thought/utils.pydocstring of deep_thought.utils.dumps:1 msgid "Serialize ``obj`` to a JSON formatted :class:`str`." msgstr "序列化 ``obj`` 要JSON格式 :class:`str`." msgid "For example:" msgstr "例如:" locale/zh_tw/LC_MESSAGES/generated.po language = 'zh_tw' locale_dirs = ['locale'] conf.py $ make html ... Build finished. The HTML pages are in _build/html. 67

Editor's Notes

  1. Hi everyone. Thank you for coming my session. This session title is: Sphinx autodoc – automated API documentation
  2. At first, Let me introduce myself. My name is Takayuki Shimizukawa came from Japan. I do 3 opensource works. 1. Sphinx co-maintainer since the end of 2011. 2. organize Sphinx-users.jp users group in Japan. 3. member of PyCon JP Committee. And I'm working for BePROUD. Our company develop web applications for business customers.
  3. Before my main presentation, I'd like to introduce "PyCon JP 2015" in Tokyo Japan. We will held the event in this October.
  4. Registration is opened. Early bird ticket is on sale its up to 210 sheet. And We're looking for session speakers. The CfP is opened until July 15th. Please join us and/or please apply for your proposal. Anyway.
  5. Sphinx autodoc. This is a main topic of this session. Autodoc is a feature that is automatic document generation from source code. Autodoc uses the function definitions and also uses docstring of the such functions. Before we jump in the main topic, I want to know how many people know the docstring, and how many people writing the docstring.
  6. Docstring is a feature of Python. Do you know the docstring? How many people know that? Please raise your hand. 10, 20, 30.. 55 hands. Thanks. Hum, It might be a minor feature of Python.
  7. OK, This red lines is a docstring. Docstring describe a way of using the function that is written at the first line of the function body. When you type "help(dumps)" in a Python interactive shell, you will get the docstring.
  8. Have you written API docs as docstrings? Please raise again. 10, 20.. 22.5 hands. Thanks. It's very small number of hands. But some people write a docstrings.
  9. So, what is the reason you do not write them? Someone would say, * I don't know what/where should I write them. * Are there some specific docstring formats? * It's not beneficial. For example, sometimes docstrings are not updated even the function's behavior is changed. Those opinions are understandable So then, I'll explain you how to write the docstrings.
  10. Goal of this session. First one is, * How to generate a doc from Python source code. Second one is, * re-discovering the meaning of docstrings. OK, let's move forward.
  11. First, I'll introduce a basic of sphinx. I'll try to introduce the basic of sphinx.
  12. What is Sphinx? Sphinx is a Open Source documentation generator. Sphinx was created to generate Python official library's document. Sphinx generates doc as several output formats from text markup
  13. Many docs are written by Sphinx. For examples, these libraries and tools are using it. Especially, Python official document and tools are generating document form source code by using Sphinx. And Non python library/tools also using Sphinx for them docs.
  14. Relation between Sphinx and Docutils. Sphinx is created in 2007 based upon Docutils library. The purpose is; generating Python official document for the python standard libraries. Docutils and Sphinx supports reStructuredText it called reST, it's an extensible markup.
  15. Comparing Docutils and Sphinx. OK, I'll read it. 1. D: handle Single page. 1. S: can handle multiple pages. 2. D: can link to others with full name include ext as like as '.html'. 2. S: can connect all pages under single tree structure by using toctree. 3. D: can make Cross reference in a page 3. S: can make cross reference over each other pages (without a extension). 4. D: provides writers: html, latex, man, xml, ... 4. S: will provide additional writers: html(w/ themes), pdf(latex), texinfo, epub, … 5. D: can handle standard reST markup specs 5. S: will provide additional markup specs: autodoc directive and so on
  16. Sphinx extensions extend reST markup and provide extra writers. Sphinx provides these extensions to support automated API documentation. sphinx.ext.autodoc sphinx.ext.autosummary sphinx.ext.doctest sphinx.ext.coverage Autodoc is the most important feature of sphinx. Almost python related libraries are using the autodoc feature.
  17. OK, let's setup a sphinx project for this code, for example. This library will be used in place of your code to explain autodoc feature. The library name is "Deep Thought". This is a structure of the library. The library has three modules: api.py, calc.py and utils.py. Second box is a first lines of program code in utils.py.
  18. If you don’t have sphinx installation in your environment, you need to install the Sphinx by this command. pip install sphinx Please note that your source code and sphinx should be installed in single python environment. Python version is also important. If you install Sphinx into Python3 environment in spite of your code is written in Python2, autodoc will emit exception to import your Python2 source code.
  19. Once you installed the sphinx, you can generate your documentation scaffold by using "sphinx-quickstart" command. Then interactive wizard is invoked and it requires Project name, Author name and Project version. The wizard also ask you many questions, but, DON'T PANIC, Usually, all you need is keep pressing Enter key. Note that, -m option is important. If you invoke without the option, you will get a "hard-coded make targets" Makefile, that will annoy you. And my presentation slide stand on this option. This option is introduced since Sphinx-1.3. And -m option will become default from Spihnx-1.5.
  20. So, type "make html" in doc directory to generate html output. You can see the output in _build/html directory.
  21. Now you can see the directories/files structure, like this. Library files under deep_thought directory. Build output under doc directory. Scaffold files under doc directory. In particular, you will see well utils.py, conf.py and index.rst in this session.
  22. Now we ready to go. Generate API docs from your python source code.
  23. Setup sphinx autodoc extension. This is a conf.py file in your sphinx scaffold. What is important is the third and fifth lines. Line-3rd: add your library path to import them from Sphinx autodoc. Line-5th: add 'sphinx.ext.autodoc' to use the extension. Next, let's specify the modules you want to document.
  24. Add automodule directive to your doc. First box is a utils.py file that is a part of deep_thought example library. Second box is a reST file. You can see the automodule usage in this box. automodule is a sphinx directive syntax that is provided by autodoc extension to generate document. Let's see the second box. (クリック) Line-4th: automodule directive imports specified module and inspect it. In this case, deepthought.utils module will be imported and be inspected. Line-5th: :members: option will inspects all members of module not only just module docstring. OK, we are now all ready. Let's invoke "make html" again.
  25. So, as a result of "make html", you can get a automatically generated document from .py file. Internally, automodule directive inspects your module and render the function signature, arguments and docstring.
  26. How does it work? autodoc directive generates intermediate reST, like this. Actually intermediate file is not generated in your filesystem, just created it on memory.
  27. If you want to see the intermediate reST lines, you can use -vvv option, like this. As you see, automodule directive is replaced with concrete documentation contents.
  28. But, please take care. Sphinx autodoc import your code to get docstrings. It means autodoc will execute code at module global level. Let me introduce a bad case related to this.
  29. This module will remove all your files. danger.py was designed as command-line script instead of "import from other module". If you tried to document with using autodoc, delete_world function will be called. Consequence of this, "make html" will destroy all your files.
  30. On the other hand, safer.py (lower block) using execution guard. It's very famous python's idiom.
  31. Because of the execution guard, your files will not be removed by make html. As a practical matter, you shouldn't try to document your setup.py for your package with using autodoc.
  32. Now let's return to the docstring and its output. This output lacks necessary information. It is the information of the argument. If you are looking for the API reference, and you find it, you will say; "Oh, I can't understand the type of arguments and meanings even reading this!"
  33. In this case, you can use "info field list" syntax for describing arguments. A real docstring should have descriptions for each function arguments like this. These red parts are special version of "field list" that called "info field lists". The specification of info field lists is described at the URL page.
  34. Info field lists is rendered as this. The output is quite nice. So, you will say; "Oh, I can understand it!", maybe.
  35. Cross-reference to functions. You can easily make cross-reference from other location to the dumps function. Of course, the cross-references beyond the pages.
  36. So far, I introduced the basics of autodoc. Following subject is: Detect deviations of the implementation and document. By using doctest.
  37. I think good API has a good document that illustrate usages of the API by using code example. If doc has code example, you can grasp the API usage quickly and exactly. I add a code example, such 4 red lines to docstring earlier. (クリック) It's called "doctest block". Obviously, this look is an interactive content of the python interactive shell. Actually, you can copy & paste the red lines from python interactive shell.
  38. After make html, You can get a syntax highlighted doctest block, like this. Library users can grasp the API usage quickly and exactly. And also users can try out it easily.
  39. And the point of view from library developers, code example is very close from implementation! We can expect that library developers will update code examples when the interface is changed by themselves. ... Really?
  40. Sorry, I don't believe it.
  41. OK, let's use the doctest builder to detect deviations of the implementation and documentation.
  42. To use doctest builder, you need to add sphinx doctest extension to conf.py, like this. Line-5: add 'sphinx.ext.doctest' With only this, you are ready to use the doctest builder. OK, Let's invoke "make doctest" command.
  43. (OK, Let's invoke "make doctest" command.) After that, you can see the dumps function will provide us different result from the expected one. Expected one is: '{spam: 1, ham: "egg"}' Actual one is: 'to-be-implemented' it is not implemented properly yet. Anyway, by using the doctest builder, it show us differences in implementation and sample code in the documentation. Actually, if your UnitTest also contains doctests, you don't need to do this by Sphinx. However, if you don't write the UnitTest, "make doctest" would be a good place to start.
  44. Listing APIs automatically with using autosummary. As already noted, autodoc is very useful. However, if you have a lot of function of a lot of modules, ...
  45. And You want to have individual pages for each modules, you need to prepare many reST files for each modules. (クリック) This box is for utils.py. In this case you should also prepare such .rst files for api module and calc module. If you have 100 modules, you should prepare 100 .rst files.
  46. As you see, each reST files have just 4 lines. You can get them by repeating copy & paste & modify bit. However ... I believe that you don't want to repeat that, like this.
  47. Don't Repeat Yourself.
  48. OK, let's use the autosummary extension to avoid such a boring tasks.
  49. Setup sphinx autosummary extension. This is your conf.py again. Line-6th: to add 'sphinx.ext.autosummary' to use the extension. Line-8th: to use 'members' option for each autodoc related directives. Line-9th: to generate reST files what you will specify with using autosummary directive. //メモ: 9th to invoke 'sphinx-apidoc' internally. Default is False, in that case, you need to invoke 'sphinx-apidoc' by hand.
  50. You can use autosummary directive in your reST files as you see. This sample uses autosummary directive and toctree option. The :toctree: option is a directory location of intermediate files that will be generated by autosummary. And contents of autosummary directive, deep_thought.api, calc and utils, are module names you want to document. Thereby the autosummary, you will get 100 intermediate .rst files if you have 100 modules.
  51. After run "make html" command again. Finally, you can get each documented pages without forcing troublesome simple operations. Additionally, "autosummary" directive you wrote was generating table of contents that linking each module pages.
  52. Discovering undocumented APIs by using coverage extension.
  53. So far, we've automated the autodoc by using autosummary. In addition, now you can also find deviation of documents and implementation by using the doctest. But, how do you find a function that is not writing a docstring, at all?
  54. For such situation, we can use coverage extension to find undocumented functions, classes, methods.
  55. To use coverage extension, you should setup coverage extension to conf.py. This is your conf.py again. Line-7th: to add 'sphinx.ext.coverage' to use the extension. That's all!
  56. Let's invoke "make coverage" command. After that, you can get a result of coverage measurement. The coverage report is recorded in "_build/coverage/python.txt" that contains undocumented functions, classes and modules. As you see, you can get the undocumented function name.
  57. However, please take care that; Command always return 0 Then you can't distinguish the presence or absence of the undocumented function by the return code. IMO, it's fair enough because coverage command shouldn't fail regardless whether coverage is perfect or not. However, unfortunately, "make coverage" also unsupported to generate coverage.xml for Jenkins or some CI tools. As conclusion of this, you can discover the undocumented functions, but you can't integrate the information to a CI tools.
  58. Sorry for inconvenience. And we are waiting for your contribution to solve the problem.(bow)
  59. Let's review the reasons for not writing a docstring that was introduced at the beginning. I don't know what/where should I write. Let's write a description, arguments and doctest blocks at the next line of function signature. Are there some docstring format spec? Yes, you can use "info field list" for argument spec and you can use doctest block for code example. It's not beneficial. You can use autodoc, autosummary, doctest and coverage to make it beneficial. I think these reasons are resolved by using sphinx autodoc features, aren't you? Let's write docstrings, and use autodoc!
  60. At the end, I'd like to introduce some of the tips.
  61. First one is, Options.
  62. Options for autodo. :members: blah To document just specified members. If you specify the option without parameter, it means ALL. :undoc-members: ... To document members which doesn't have docstring. If you specify the option without parameter, all undocumented members are rendered. :private-members: ... To document private members which name starts with underscore. :special-members: ... To document starts with underscore underscore. :inherited-members: ... To document inherited from super class. Please refer to sphinx reference for the detail of options.
  63. Second one is Directives for Web API.
  64. sphinxcontrib-httpdomain 3rd-party extension provides http domain to generate WebAPI doc. As you see, you can use get directive. Httpdomain also provides: Other http related directives "http" syntax highlighter It generates nice WebAPI reference page and well organized WebAPI index page. Httpdmain also contains sphinxcontrib.autohttp extension that support Flask, Bottle and Tornado WAF to document WebAPI methods automatically by using reflection.
  65. The last one is Document translation.
  66. You can get translated output w/o editing reST and python code. For that, you can use "make gettext" command that generates gettext style pot files. "make gettext" extract text from reST file and python source file that referenced by autodoc. It means, you can translate them into any language without rewriting the original reST files and python source files. If you are interested, please refer my yesterdays' session slide.