Examples¶
A numbered learning path of short scripts that use only the public API, from first steps to
advanced. Each builds what it needs in a temporary folder (or in STUBPY_EXAMPLES_OUT if set),
so it runs as it is: python examples/01_render_a_module.py. Each also has a notebook with
its output next to it. The test suite runs them all. They live in the examples/ folder of the
repository.
Render one module¶
render builds one stub without writing it.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
module = WORK / "clock.py"
module.write_text(
"import time\n\n\n"
"def now(utc: bool = False) -> float:\n"
" return time.time()\n\n\n"
"class Timer:\n"
" running = False\n\n"
" def start(self, label='timer'):\n"
" self.running = True\n",
encoding="utf-8",
)
# %%
result = stubpy.render(module)
print(result.text)
print("ok:", result.ok)
Forwarded keyword arguments¶
A class passes **kwargs to its base class; the stub lists the parameters they stand for.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
SOURCE = '''class Shape:
def __init__(self, color: str = "black", width: float = 1.0):
self.color = color
self.width = width
class Circle(Shape):
def __init__(self, radius: float, **kwargs):
super().__init__(**kwargs)
self.radius = radius
'''
module = WORK / "shapes.py"
module.write_text(SOURCE, encoding="utf-8")
# %%
print(stubpy.render(module).text)
Generate a package¶
generate writes the stubs of a package and returns a report.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
package = WORK / "shapes"
(package / "tools").mkdir(parents=True, exist_ok=True)
(package / "__init__.py").write_text("from .tools import area as area\n", encoding="utf-8")
(package / "tools" / "__init__.py").write_text(
"def area(width: float, height: float = 1.0) -> float:\n return width * height\n", encoding="utf-8"
)
# %%
report = stubpy.generate(package, WORK / "stubs")
print(report.summary())
for path in report.written:
print(path.relative_to(WORK / "stubs").as_posix())
# %%
print((WORK / "stubs" / "shapes" / "tools" / "__init__.pyi").read_text(encoding="utf-8"))
Check for stale stubs¶
check reports the stubs that no longer match their source.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
module = WORK / "clock.py"
module.write_text("def now(utc: bool = False) -> float: ...\n", encoding="utf-8")
stubpy.generate(module, WORK / "stubs")
report = stubpy.check(module, WORK / "stubs")
print(report.summary())
# %%
module.write_text("def now(utc: bool = False, tz: str = 'UTC') -> float: ...\n", encoding="utf-8")
report = stubpy.check(module, WORK / "stubs")
print(report.summary())
print("stale:", [path.name for path in report.stale])
Configuration file¶
load_config reads the [tool.stubpy] table.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
(WORK / "pyproject.toml").write_text(
'[tool.stubpy]\ntargets = ["src/mypkg"]\noutput_dir = "stubs"\ninclude_private = true\n',
encoding="utf-8",
)
(WORK / "src" / "mypkg").mkdir(parents=True, exist_ok=True)
(WORK / "src" / "mypkg" / "__init__.py").write_text(
"def _helper(x: int) -> int: ...\n\n\ndef api(x: int) -> int: ...\n", encoding="utf-8"
)
# %%
config = stubpy.load_config(WORK)
print("targets:", [Path(target).name for target in config.targets])
print("output_dir:", Path(config.output_dir).name)
print("include_private:", config.include_private)
# %%
report = stubpy.generate(config=config)
print(report.summary())
print((Path(config.output_dir) / "mypkg" / "__init__.pyi").read_text(encoding="utf-8"))
Hints for compiled code¶
A JIT-wrapped or compiled callable has no signature to introspect. The hints give it one.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
SOURCE = '''from stubpy import hint
def jit(function):
return function
@jit
@hint.signature("(x: float, y: float = 0.0) -> float")
def blend(*args):
return args[0]
@jit
@hint.returns("list[int]")
def histogram(values, bins=10):
return []
'''
module = WORK / "fast.py"
module.write_text(SOURCE, encoding="utf-8")
# %%
print(stubpy.render(module).text)
Cython sources¶
An unbuilt .pyx is stubbed from its source alone.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
# %%
package = WORK / "fastmath"
package.mkdir(exist_ok=True)
(package / "__init__.py").write_text("", encoding="utf-8")
(package / "_core.pyx").write_text(
"def scale(double x, int factor=2):\n"
" '''Multiply x by factor.'''\n"
" return x * factor\n",
encoding="utf-8",
)
# %%
report = stubpy.generate(package, WORK / "stubs")
print(report.summary())
print((WORK / "stubs" / "fastmath" / "_core.pyi").read_text(encoding="utf-8"))
Docstring sync¶
sync_docstrings copies runtime docstrings into a hand-written stub.
# %%
import os
import tempfile
from pathlib import Path
import stubpy
TEMP = tempfile.TemporaryDirectory()
WORK = Path(os.environ.get("STUBPY_EXAMPLES_OUT") or TEMP.name).resolve()
import sys
# %%
package = WORK / "docdemo"
package.mkdir(exist_ok=True)
(package / "__init__.py").write_text("", encoding="utf-8")
(package / "_native.py").write_text(
'def scale(x, factor=2):\n """Multiply x by factor."""\n return x * factor\n', encoding="utf-8"
)
stub = package / "_native.pyi"
stub.write_text("def scale(x: float, factor: int = 2) -> float: ...\n", encoding="utf-8")
sys.path.insert(0, str(WORK))
# %%
synced = stubpy.sync_docstrings(stub)
print(synced.text)
pre-commit¶
repos:
- repo: https://github.com/wzjoriv/stubpy
rev: 1.7.1
hooks:
- id: stubpy-check