Mastering Python Second Edition Release Code

This commit is contained in:
Rick van Hattem
2022-05-05 18:25:55 +02:00
commit 3223a43fe3
454 changed files with 20230 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
Chapter 9, Documentation
##############################################################################
| reStructuredText, Napoleon and How to Use Sphinx shows how you can make Sphinx automatically document your code with very little effort. Additionally, it shows how the Napoleon syntax can be used to document function arguments in a way that is legible both in the code and the documentation.
+125
View File
@@ -0,0 +1,125 @@
>>> a = 123
>>> b = 'test'
>>> c = True
------------------------------------------------------------------
>>> def pow(base: int, exponent: int) -> int:
... return base ** exponent
>>> help(pow)
Help on function pow in module __main__:
<BLANKLINE>
pow(base: int, exponent: int) -> int
<BLANKLINE>
>>> pow.__annotations__
{'base': <class 'int'>,
'exponent': <class 'int'>,
'return': <class 'int'>}
>>> pow(2, 10)
1024
>>> pow(pow(9, 2) + pow(19, 2) / 22, 0.25)
3.1415926525826463
------------------------------------------------------------------
>>> import typing
>>> int_or_float = typing.Union[int, float]
>>> def pow(base: int, exponent: int) -> int_or_float:
... return base ** exponent
>>> help(pow)
Help on function pow in module __main__:
<BLANKLINE>
pow(base: int, exponent: int) -> Union[int, float]
<BLANKLINE>
------------------------------------------------------------------
>>> class Sandwich:
... pass
>>> def get_sandwich() -> Sandwich:
... return Sandwich()
------------------------------------------------------------------
>>> class A:
... @staticmethod
... def get_b() -> B:
... return B()
Traceback (most recent call last):
...
NameError: name 'B' is not defined
>>> class B:
... @staticmethod
... def get_a() -> A:
... return A()
Traceback (most recent call last):
...
NameError: name 'A' is not defined
------------------------------------------------------------------
>>> class A:
... @staticmethod
... def get_b() -> 'B':
... return B()
>>> class B:
... @staticmethod
... def get_a() -> A:
... return A()
------------------------------------------------------------------
# Works without an issue
>>> some_variable: 'some_non_existing_type'
# Error as expected
>>> some_variable: some_non_existing_type
Traceback (most recent call last):
...
NameError: name 'some_non_existing_type' is not defined
>>> if typing.TYPE_CHECKING:
... # Add your import for some_non_existing_type here
... ...
------------------------------------------------------------------
>>> import typing
>>> Username = typing.NewType('Username', str)
>>> rick = Username('Rick')
>>> type(rick)
<class 'str'>
------------------------------------------------------------------
>>> import typing
>>> T = typing.TypeVar('T', int, str)
>>> def add(a: T, b: T) -> T:
... return a + b
>>> add(1, 2)
3
>>> add('a', 'b')
'ab'
+33
View File
@@ -0,0 +1,33 @@
import typing
def pow(base: int, exponent: int) -> int:
return base ** exponent
pow(2.5, 10)
################################################################
Username = typing.NewType('Username', str)
rick = Username('Rick')
def print_username(username: Username):
print(f'Username: {username}')
print_username(rick)
print_username(str(rick))
################################################################
T = typing.TypeVar('T')
def to_string(value: T) -> T:
return str(value)
to_string(1)
@@ -0,0 +1,21 @@
Documentation, how to use Sphinx and reStructuredText
##################################################################
Documenting code can be both fun and useful! ...
Additionally, adding ...
... So that typing `Spam.eggs.` will automatically ...
Topics covered in this chapter are as follows:
- The reStructuredText syntax
- Setting up documentation using Sphinx
- Sphinx style docstrings
- Google style docstrings
- NumPy style docstrings
The reStructuredText syntax
******************************************************************
The reStructuredText format (also known as ...
+48
View File
@@ -0,0 +1,48 @@
Part
################################################################
Chapter
****************************************************************
Section
================================================================
Subsection
----------------------------------------------------------------
Subsubsection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Paragraph
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Content
------------------------------------------------------------------------------
################################################################
Part
################################################################
****************************************************************
Chapter
****************************************************************
================================================================
Section
================================================================
----------------------------------------------------------------
Subsection
----------------------------------------------------------------
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Subsubsection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Paragraph
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Content
+48
View File
@@ -0,0 +1,48 @@
1. With
2. Numbers
a. With
#. letters
i. Roman
#. numerals
(1) With
(2) Parenthesis
------------------------------------------------------------------------------
- dashes
- and more dashes
* asterisk
* stars
+ plus
+ and plus
------------------------------------------------------------------------------
-s, --spam This is the spam option
--eggs This is the eggs option
------------------------------------------------------------------------------
spam
Spam is a canned pork meat product
eggs
Is, similar to spam, also food
------------------------------------------------------------------------------
1. With
2. Numbers
(food) food
spam
Spam is a canned pork meat product
eggs
Is, similar to spam, also food
(other) non-food stuff
+43
View File
@@ -0,0 +1,43 @@
The switch to reStructuredText and Sphinx was made with the
`Python 2.6 <https://docs.python.org/whatsnew/2.6.html>`_
release.
------------------------------------------------------------------------------
The switch to reStructuredText and Sphinx was made with the
`python 2.6`_ release.
.. _`Python 2.6`: https://docs.python.org/whatsnew/2.6.html
------------------------------------------------------------------------------
The introduction section
================================================================
This section contains:
- `chapter 1`_
- :ref:`chapter2`
1. my_label_
2. `And a label link with a custom title <my_label>`_
Chapter 1
----------------------------------------------------------------
Jumping back to the beginning of `chapter 1`_ is also possible.
Or jumping to :ref:`Chapter 2 <chapter2>`
.. _chapter2:
Chapter 2 With a longer title
----------------------------------------------------------------
The next chapter.
.. _my_label:
The label points here.
Back to `the introduction section`_
+13
View File
@@ -0,0 +1,13 @@
.. image:: python.png
:width: 150
:height: 100
.. image:: python.png
:scale: 10
------------------------------------------------------------------------------
.. figure:: python.png
:scale: 10
The Python logo
@@ -0,0 +1,10 @@
.. |python| image:: python.png
:scale: 2
The Python programming language uses the logo: |python|
------------------------------------------------------------------------------
.. |author| replace:: Rick van Hattem
This book was written by |author|
+31
View File
@@ -0,0 +1,31 @@
.. code:: python
def spam(*args):
print('spam got args', args)
------------------------------------------------------------------------------
.. math::
\int_a^b f(x)\,dx = F(b) - F(a)
------------------------------------------------------------------------------
Before comments
.. Everything here will be commented
And this as well
.. code:: python
def even_this_code_sample():
pass # Will be commented
After comments
------------------------------------------------------------------------------
Normal text
Quoted text
+27
View File
@@ -0,0 +1,27 @@
.. toctree::
:maxdepth: 2
------------------------------------------------------------------------------
.. toctree::
:maxdepth: 2
module.a
module.b
module.c
------------------------------------------------------------------------------
.. toctree::
:maxdepth: 2
:glob:
module.*
------------------------------------------------------------------------------
.. toctree::
:maxdepth: 2
The A module <module.a>
+47
View File
@@ -0,0 +1,47 @@
eggs module
===========
.. automodule:: eggs
:members:
:undoc-members:
:show-inheritance:
------------------------------------------------------------------------------
eggs module
===========
.. automodule:: eggs
:members:
:undoc-members:
:show-inheritance:
:inherited-members:
------------------------------------------------------------------------------
eggs module
===========
.. automodule:: eggs
:members:
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members:
------------------------------------------------------------------------------
eggs module
===========
.. automodule:: eggs
:members:
:undoc-members:
:show-inheritance:
.. class:: NonExistingClass
This class doesn't actually exist, but it's in the documentation now.
.. method:: non_existing_function()
And this function does not exist either.
+5
View File
@@ -0,0 +1,5 @@
Spam: :class:`spam.Spam`
------------------------------------------------------------------------------
Link to the intersphinx module: :mod:`sphinx.ext.intersphinx`
+33
View File
@@ -0,0 +1,33 @@
class Eggs:
pass
class Spam(object):
'''
The Spam object contains lots of spam
:param arg: The arg is used for ...
:type arg: str
:param `*args`: The variable arguments are used for ...
:param `**kwargs`: The keyword arguments are used for ...
:ivar arg: This is where we store arg
:vartype arg: str
'''
def __init__(self, arg: str, *args, **kwargs):
self.arg: str = arg
def eggs(self, number: int, cooked: bool) -> Eggs:
'''We can't have spam without eggs, so here are the eggs
:param number: The number of eggs to return
:type number: int
:param bool cooked: Should the eggs be cooked?
:raises: :class:`RuntimeError`: Out of eggs
:returns: A bunch of eggs
:rtype: Eggs
'''
pass
+36
View File
@@ -0,0 +1,36 @@
class Eggs:
pass
class Spam(object):
r'''
The Spam object contains lots of spam
Args:
arg: The arg is used for ...
\*args: The variable arguments are used for ...
\*\*kwargs: The keyword arguments are used for ...
Attributes:
arg: This is where we store arg,
'''
def __init__(self, arg: str, *args, **kwargs):
self.arg: str = arg
def eggs(self, number: int, cooked: bool) -> Eggs:
'''We can't have spam without eggs, so here are the eggs
Args:
number: The number of eggs to return
cooked: Should the eggs be cooked?
Raises:
RuntimeError: Out of eggs
Returns:
Eggs: A bunch of eggs
'''
pass
+49
View File
@@ -0,0 +1,49 @@
class Eggs:
pass
class Spam(object):
r'''
The Spam object contains lots of spam
Parameters
----------
arg : str
The arg is used for ...
\*args
The variable arguments are used for ...
\*\*kwargs
The keyword arguments are used for ...
Attributes
----------
arg : str
This is where we store arg,
'''
def __init__(self, arg, *args, **kwargs):
self.arg = arg
def eggs(self, number, cooked):
'''We can't have spam without eggs, so here are the eggs
Parameters
----------
number : int
The number of eggs to return
cooked : bool
Should the eggs be cooked?
Raises
------
RuntimeError
Out of eggs
Returns
-------
Eggs
A bunch of eggs
'''
pass
View File
+15
View File
@@ -0,0 +1,15 @@
class A(object):
def __init__(self, arg, *args, **kwargs):
pass
def regular_method(self, arg):
pass
@classmethod
def decorated_method(self, arg):
pass
def _hidden_method(self):
pass
+11
View File
@@ -0,0 +1,11 @@
from . import a
class B(a.A):
def regular_method(self):
'''This regular method overrides
:meth:`a.A.regular_method`
'''
pass
+20
View File
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
@@ -0,0 +1,38 @@
apidoc\_example package
=======================
Submodules
----------
apidoc\_example.a module
------------------------
.. automodule:: apidoc_example.a
:members:
:undoc-members:
:show-inheritance:
:private-members:
:special-members:
:inherited-members:
apidoc\_example.b module
------------------------
.. automodule:: apidoc_example.b
:members:
:undoc-members:
:show-inheritance:
:private-members:
:special-members:
:inherited-members:
Module contents
---------------
.. automodule:: apidoc_example
:members:
:undoc-members:
:show-inheritance:
:private-members:
:special-members:
:inherited-members:
+62
View File
@@ -0,0 +1,62 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
# -- Project information -----------------------------------------------------
project = 'Mastering Python'
copyright = '2020, Rick van Hattem'
author = 'Rick van Hattem'
autodoc_typehints = 'description'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
intersphinx_mapping = {
'python': ('https://docs.python.org/', None),
'sphinx': ('https://www.sphinx-doc.org/', None),
}
+38
View File
@@ -0,0 +1,38 @@
.. Mastering Python documentation master file, created by
sphinx-quickstart on Mon Sep 7 00:03:29 2020.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Mastering Python's documentation!
============================================
.. toctree::
:maxdepth: 2
:caption: Contents:
modules
.. automodule:: 13_sphinx_style
:members:
:undoc-members:
:show-inheritance:
.. automodule:: 14_google_style
:members:
:undoc-members:
:show-inheritance:
.. automodule:: 15_numpy_style
:members:
:undoc-members:
:show-inheritance:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
+35
View File
@@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
+7
View File
@@ -0,0 +1,7 @@
apidoc_example
==============
.. toctree::
:maxdepth: 4
apidoc_example
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB