├── tests ├── __init__.py ├── util.py ├── test_integration.py ├── test_handler.py ├── test_instrumenter.py ├── test_callback.py └── test_trigger.py ├── requirements-dev.txt ├── src └── dowhen │ ├── types.py │ ├── __init__.py │ ├── handler.py │ ├── util.py │ ├── callback.py │ ├── instrumenter.py │ └── trigger.py ├── docs ├── api.rst ├── Makefile ├── make.bat ├── faq.rst ├── index.rst ├── conf.py └── usage.rst ├── NOTICE ├── .github └── workflows │ ├── lint.yml │ ├── docs.yml │ ├── publish.yml │ └── build_test.yml ├── Makefile ├── .readthedocs.yaml ├── pyproject.toml ├── README.md ├── .gitignore └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | # Build Packages 2 | build 3 | setuptools 4 | wheel 5 | 6 | # Lint & Coverage 7 | ruff 8 | mypy 9 | coverage 10 | 11 | # Test 12 | pytest 13 | pytest-cov 14 | coredumpy 15 | 16 | # Documentation requirements 17 | sphinx>=8.0 18 | sphinx-rtd-theme 19 | sphinx-autodoc-typehints 20 | -------------------------------------------------------------------------------- /src/dowhen/types.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import re 6 | from typing import Literal 7 | 8 | IdentifierType = int | str | re.Pattern | Literal["", ""] | None 9 | -------------------------------------------------------------------------------- /src/dowhen/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | __version__ = "0.1.0" 6 | 7 | from .callback import bp, do, goto 8 | from .instrumenter import DISABLE 9 | from .trigger import when 10 | from .util import clear_all, get_source_hash 11 | 12 | __all__ = ["bp", "clear_all", "do", "get_source_hash", "goto", "when", "DISABLE"] 13 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | This page contains the complete API reference for dowhen. 5 | 6 | Core Module 7 | ----------- 8 | 9 | .. automodule:: dowhen 10 | :members: 11 | 12 | Callback Module 13 | --------------- 14 | 15 | .. automodule:: dowhen.callback 16 | :members: 17 | 18 | Trigger Module 19 | -------------- 20 | 21 | .. automodule:: dowhen.trigger 22 | :members: 23 | 24 | Handler Module 25 | -------------- 26 | 27 | .. automodule:: dowhen.handler 28 | :members: 29 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2025 Tian Gao 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | lint: 11 | strategy: 12 | matrix: 13 | python-version: ['3.12', '3.13', '3.13t'] 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Set up Python 18 | uses: actions/setup-python@v5 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | - name: Install dependency 22 | run: pip install -r requirements-dev.txt 23 | - name: Lint 24 | run: make lint 25 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: docs 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | paths: 7 | - "docs/**" 8 | - ".github/workflows/docs.yml" 9 | pull_request: 10 | paths: 11 | - "docs/**" 12 | - ".github/workflows/docs.yml" 13 | 14 | jobs: 15 | docs: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Set up Python 20 | uses: actions/setup-python@v5 21 | with: 22 | python-version: "3.12" 23 | - name: Install dependency 24 | run: pip install -r requirements-dev.txt 25 | - name: Build documentation 26 | run: make docs 27 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | python -m build 3 | 4 | install: 5 | pip install -e . 6 | 7 | lint: 8 | ruff check src tests 9 | ruff format src tests --diff 10 | mypy src 11 | 12 | lint-fix: 13 | ruff check src tests --fix 14 | ruff format src tests 15 | 16 | test: 17 | pytest --cov=dowhen --cov-report=term-missing:skip-covered tests 18 | 19 | .PHONY: docs 20 | 21 | docs: 22 | cd docs && make html 23 | 24 | docs-clean: 25 | cd docs && make clean 26 | 27 | clean: 28 | rm -rf __pycache__ 29 | rm -rf tests/__pycache__ 30 | rm -rf src/dowhen/__pycache__ 31 | rm -rf build 32 | rm -rf dist 33 | rm -rf dowhen.egg-info 34 | rm -rf src/dowhen.egg-info 35 | rm -rf docs/_build 36 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # Read the Docs configuration file 2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 3 | 4 | # Required 5 | version: 2 6 | 7 | # Set the OS, Python version, and other tools you might need 8 | build: 9 | os: ubuntu-24.04 10 | tools: 11 | python: "3.13" 12 | 13 | # Build documentation in the "docs/" directory with Sphinx 14 | sphinx: 15 | configuration: docs/conf.py 16 | 17 | # Optionally, but recommended, 18 | # declare the Python requirements required to build your documentation 19 | # See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html 20 | python: 21 | install: 22 | - requirements: requirements-dev.txt 23 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Python package build and publish 2 | 3 | on: 4 | release: 5 | types: [created] 6 | jobs: 7 | pypi-publish: 8 | name: Upload release to PyPI 9 | runs-on: ubuntu-latest 10 | environment: 11 | name: pypi 12 | url: https://pypi.org/p/dowhen 13 | permissions: 14 | id-token: write # IMPORTANT: this permission is mandatory for trusted publishing 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Set up Python 18 | uses: actions/setup-python@v5 19 | with: 20 | python-version: "3.12" 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install build setuptools wheel 25 | - name: Build source tar 26 | run: | 27 | python -m build 28 | - name: Publish package distributions to PyPI 29 | uses: pypa/gh-action-pypi-publish@release/v1 30 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | %SPHINXBUILD% >NUL 2>NUL 14 | if errorlevel 9009 ( 15 | echo. 16 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 17 | echo.installed, then set the SPHINXBUILD environment variable to point 18 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 19 | echo.may add the Sphinx directory to PATH. 20 | echo. 21 | echo.If you don't have Sphinx installed, grab it from 22 | echo.https://www.sphinx-doc.org/ 23 | exit /b 1 24 | ) 25 | 26 | if "%1" == "" goto help 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "dowhen" 7 | authors = [{name = "Tian Gao", email = "gaogaotiantian@hotmail.com"}] 8 | description = "An instrumentation tool for Python" 9 | readme = "README.md" 10 | requires-python = ">=3.12" 11 | license = {file = "LICENSE"} 12 | dynamic = ["version"] 13 | classifiers = [ 14 | "Development Status :: 4 - Beta", 15 | "Programming Language :: Python :: 3.12", 16 | "Programming Language :: Python :: 3.13", 17 | "Intended Audience :: Developers", 18 | "License :: OSI Approved :: Apache Software License", 19 | "Operating System :: MacOS", 20 | "Operating System :: POSIX :: Linux", 21 | "Operating System :: Microsoft :: Windows", 22 | "Topic :: Utilities", 23 | ] 24 | 25 | [project.urls] 26 | Homepage = "https://github.com/gaogaotiantian/dowhen" 27 | 28 | [tool.setuptools.dynamic] 29 | version = {attr = "dowhen.__version__"} 30 | 31 | [tool.ruff] 32 | lint.select = ["F", "I"] 33 | -------------------------------------------------------------------------------- /tests/util.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import contextlib 6 | import io 7 | import sys 8 | import textwrap 9 | 10 | 11 | @contextlib.contextmanager 12 | def disable_coverage(): 13 | try: 14 | import coverage 15 | 16 | cov = coverage.Coverage().current() 17 | except ModuleNotFoundError: 18 | cov = None 19 | 20 | if cov is None: 21 | yield 22 | return 23 | 24 | cov.stop() 25 | yield 26 | cov.start() 27 | 28 | 29 | @contextlib.contextmanager 30 | def do_pdb_test(command): 31 | command_input = io.StringIO(textwrap.dedent(command)) 32 | output = io.StringIO() 33 | 34 | _stdin = sys.stdin 35 | _stdout = sys.stdout 36 | try: 37 | sys.stdin = command_input 38 | sys.stdout = output 39 | with disable_coverage(): 40 | yield output 41 | finally: 42 | sys.stdin = _stdin 43 | sys.stdout = _stdout 44 | -------------------------------------------------------------------------------- /docs/faq.rst: -------------------------------------------------------------------------------- 1 | Frequently Asked Questions 2 | ========================== 3 | 4 | When do we need this? 5 | --------------------- 6 | 7 | ``dowhen`` serves well in these scenarios: 8 | 9 | 1. **monkeypatching**: 10 | 11 | ``dowhen`` allows you to inject code at specific points in your application 12 | without modifying the original codebase. When you need to change the behavior 13 | of stdlib or third-party libraries, you can use ``dowhen`` to do it to 14 | avoid vendoring your own version or swapping the whole function. 15 | 16 | 2. **debugging**: 17 | 18 | ``dowhen`` is just like a debugger - it can print stuff or execute code 19 | at specific points in your code to help you understand what is going on. 20 | Unlike a debugger, it is easily reproducible - you don't need to type 21 | commands in a terminal. 22 | 23 | 3. **logging**: 24 | 25 | ``dowhen`` can be used to log all kinds of stuff without adding extra 26 | code to your application. 27 | 28 | Is the overhead high? 29 | ---------------------- 30 | 31 | Not at all. ``dowhen`` utilizes ``sys.monitoring`` so it only triggers 32 | events when necessary. It has minimal impact on performance. 33 | 34 | Why 3.12+? 35 | ---------- 36 | 37 | ``dowhen`` uses the new ``sys.monitoring`` module introduced in Python 3.12. 38 | -------------------------------------------------------------------------------- /.github/workflows/build_test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build_test: 13 | strategy: 14 | matrix: 15 | os: [ubuntu-latest, windows-latest, macos-latest, macos-14] 16 | python-version: ['3.12', '3.13', '3.13t'] 17 | runs-on: ${{ matrix.os }} 18 | timeout-minutes: 30 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Install dependencies 26 | run: pip install -r requirements-dev.txt 27 | - name: Build 28 | run: python -m build 29 | - name: Install 30 | run: pip install . 31 | - name: Test 32 | run: pytest --cov=dowhen --cov-report=xml:coverage.xml --enable-coredumpy --coredumpy-dir ./coredumpy_data tests 33 | - name: Upload coverage reports to Codecov 34 | uses: codecov/codecov-action@v4.0.1 35 | with: 36 | slug: gaogaotiantian/dowhen 37 | file: ./coverage.xml 38 | - name: Upload coredumpy data if applicable 39 | uses: gaogaotiantian/upload-coredumpy@v0.2 40 | if: failure() 41 | with: 42 | name: coredumpy_data_${{ matrix.os }}_${{ matrix.python-version }} 43 | path: ./coredumpy_data 44 | retention-days: 7 45 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | dowhen documentation 2 | ==================== 3 | 4 | ``dowhen`` is an instrumentation tool for Python that allows you execute 5 | certain code at specific triggers in a clean and maintainable way. 6 | 7 | Installation 8 | ------------ 9 | 10 | .. code-block:: bash 11 | 12 | pip install dowhen 13 | 14 | Quick Start 15 | ----------- 16 | 17 | .. code-block:: python 18 | 19 | from dowhen import bp, do, goto, when 20 | 21 | def f(x): 22 | x += 100 23 | # Let's change the value of x before return 24 | return x 25 | 26 | # do("x = 1") is the callback 27 | # when(f, "return x") is the trigger 28 | # This is equivalent to: 29 | # handler = when(f, "return x").do("x = 1") 30 | handler = do("x = 1").when(f, "return x") 31 | # x = 1 is executed before "return x" 32 | assert f(0) == 1 33 | 34 | # You can remove the handler 35 | handler.remove() 36 | assert f(0) == 100 37 | 38 | # bp() is another callback that brings up pdb 39 | handler = bp().when(f, "return x") 40 | # This will enter pdb 41 | f(0) 42 | # You can temporarily disable the handler 43 | # handler.enable() will enable it again 44 | handler.disable() 45 | 46 | # goto() is a callback too 47 | # This will skip the line of `x += 100` 48 | # The handler will be removed after the context 49 | with goto("return x").when(f, "x += 100"): 50 | assert f(0) == 0 51 | 52 | # You can chain callbacks and they'll run in order 53 | # You don't need to store the handler if you don't use it 54 | when(f, "x += 100").goto("return x").do("x = 42") 55 | assert f(0) == 42 56 | 57 | .. toctree:: 58 | :maxdepth: 2 59 | :caption: Contents: 60 | 61 | usage 62 | api 63 | faq 64 | 65 | Indices and tables 66 | ================== 67 | 68 | * :ref:`genindex` 69 | * :ref:`modindex` 70 | * :ref:`search` 71 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # For the full list of built-in configuration values, see the documentation: 4 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 5 | 6 | import os 7 | import sys 8 | 9 | # Add the source directory to the path 10 | sys.path.insert(0, os.path.abspath('../src')) 11 | 12 | # -- Project information ----------------------------------------------------- 13 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 14 | 15 | project = 'dowhen' 16 | copyright = '2025, Tian Gao' 17 | author = 'Tian Gao' 18 | import dowhen 19 | release = dowhen.__version__ 20 | 21 | # -- General configuration --------------------------------------------------- 22 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 23 | 24 | extensions = [ 25 | 'sphinx.ext.autodoc', 26 | 'sphinx.ext.viewcode', 27 | 'sphinx.ext.intersphinx', 28 | 'sphinx.ext.napoleon', 29 | 'sphinx_autodoc_typehints', 30 | ] 31 | 32 | templates_path = ['_templates'] 33 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 34 | 35 | language = 'en' 36 | 37 | # -- Options for HTML output ------------------------------------------------- 38 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 39 | 40 | html_theme = 'sphinx_rtd_theme' 41 | html_static_path = ['_static'] 42 | 43 | # -- Options for autodoc extension ------------------------------------------- 44 | autodoc_default_options = { 45 | 'members': True, 46 | 'undoc-members': True, 47 | 'show-inheritance': True, 48 | } 49 | autodoc_member_order = 'bysource' 50 | 51 | # -- Options for intersphinx extension --------------------------------------- 52 | # https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html#configuration 53 | 54 | intersphinx_mapping = { 55 | 'python': ('https://docs.python.org/3', None), 56 | } 57 | -------------------------------------------------------------------------------- /tests/test_integration.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import inspect 6 | 7 | import pytest 8 | 9 | import dowhen 10 | 11 | 12 | def test_clear_all(): 13 | def f(x): 14 | return x 15 | 16 | dowhen.do("x = 1").when(f, "return x") 17 | dowhen.do("x = 1").when(f, "") 18 | dowhen.do("x = 1").when(f, "") 19 | 20 | assert f(2) == 1 21 | dowhen.clear_all() 22 | assert f(2) == 2 23 | 24 | 25 | def test_multi_callback(): 26 | def f(x, y): 27 | return x + y 28 | 29 | handler_x = dowhen.do("x = 1").when(f, "return x + y") 30 | handler_y = dowhen.do("y = 2").when(f, "return x + y") 31 | 32 | assert f(0, 0) == 3 33 | 34 | handler_x.remove() 35 | assert f(0, 0) == 2 36 | 37 | handler_y.remove() 38 | assert f(0, 0) == 0 39 | 40 | 41 | def func_test(x, y): 42 | x = x + 1 43 | y = y + 1 44 | return x, y 45 | 46 | 47 | @pytest.mark.parametrize( 48 | "cb_func, entity, identifiers, expected_results", 49 | [ 50 | ("x = 2", func_test, ("return x",), ([0, 0], (2, 1))), 51 | ("x += 1", func_test, ("return x", ""), ([0, 0], (3, 1))), 52 | ("x += 1", func_test, (), ([0, 0], (4, 1))), 53 | ("x = 2", None, ("return x",), ([0, 0], (2, 1))), 54 | ], 55 | ) 56 | def test_integration(cb_func, entity, identifiers, expected_results): 57 | args, retval = expected_results 58 | handler = dowhen.do(cb_func).when(entity, *identifiers) 59 | assert func_test(*args) == retval 60 | handler.remove() 61 | 62 | handler = dowhen.when(entity, *identifiers).do(cb_func) 63 | assert func_test(*args) == retval 64 | handler.remove() 65 | 66 | 67 | def test_signature(): 68 | def f(): 69 | pass 70 | 71 | callback = dowhen.do("x = 1") 72 | trigger = dowhen.when(f) 73 | handler = dowhen.do("x = 1").when(f) 74 | 75 | signature_pairs = [ 76 | (callback.when, dowhen.when), 77 | (trigger.do, dowhen.do), 78 | (handler.do, dowhen.do), 79 | (trigger.goto, dowhen.goto), 80 | (handler.goto, dowhen.goto), 81 | (trigger.bp, dowhen.bp), 82 | (handler.bp, dowhen.bp), 83 | ] 84 | for func1, func2 in signature_pairs: 85 | assert ( 86 | inspect.signature(func1).parameters == inspect.signature(func2).parameters 87 | ) 88 | -------------------------------------------------------------------------------- /src/dowhen/handler.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | from __future__ import annotations 6 | 7 | import sys 8 | from types import FrameType 9 | from typing import Any, Callable 10 | 11 | from .callback import Callback 12 | from .instrumenter import Instrumenter 13 | from .trigger import Trigger 14 | 15 | DISABLE = sys.monitoring.DISABLE 16 | 17 | 18 | class EventHandler: 19 | def __init__(self, trigger: Trigger, callback: Callback): 20 | self.trigger = trigger 21 | self.callbacks: list[Callback] = [callback] 22 | self.disabled = False 23 | self.removed = False 24 | 25 | def disable(self) -> None: 26 | if self.removed: 27 | raise RuntimeError("Cannot disable a removed handler.") 28 | self.disabled = True 29 | 30 | def enable(self) -> None: 31 | if self.removed: 32 | raise RuntimeError("Cannot enable a removed handler.") 33 | if self.disabled: 34 | self.disabled = False 35 | Instrumenter().restart_events() 36 | 37 | def submit(self) -> None: 38 | Instrumenter().submit(self) 39 | 40 | def remove(self) -> None: 41 | Instrumenter().remove_handler(self) 42 | self.removed = True 43 | 44 | def __call__(self, frame: FrameType, **kwargs) -> Any: 45 | if not self.disabled: 46 | if not self.trigger.has_event(frame): 47 | return DISABLE 48 | should_fire = self.trigger.should_fire(frame) 49 | if should_fire is DISABLE: 50 | self.disable() 51 | elif should_fire: 52 | for cb in self.callbacks: 53 | if cb(frame, **kwargs) is DISABLE: 54 | self.disable() 55 | 56 | if self.disabled: 57 | return DISABLE 58 | 59 | def __enter__(self) -> "EventHandler": 60 | return self 61 | 62 | def __exit__(self, exc_type, exc_value, traceback) -> None: 63 | self.remove() 64 | 65 | def bp(self) -> "EventHandler": 66 | from .callback import Callback 67 | 68 | self.callbacks.append(Callback.bp()) 69 | return self 70 | 71 | def do(self, func: str | Callable) -> "EventHandler": 72 | from .callback import Callback 73 | 74 | self.callbacks.append(Callback.do(func)) 75 | return self 76 | 77 | def goto(self, target: str | int) -> "EventHandler": 78 | from .callback import Callback 79 | 80 | self.callbacks.append(Callback.goto(target)) 81 | return self 82 | -------------------------------------------------------------------------------- /tests/test_handler.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import sys 6 | 7 | import pytest 8 | 9 | import dowhen 10 | 11 | from .util import do_pdb_test 12 | 13 | 14 | def test_enable_disable(): 15 | # This function can't be at the same line as f(x) in other files 16 | # See gh-78 17 | def f(x): 18 | return x 19 | 20 | handler = dowhen.do("print('hello');x = 1").when(f, "return x") 21 | 22 | assert f(2) == 1 23 | handler.disable() 24 | assert f(2) == 2 25 | handler.enable() 26 | assert f(2) == 1 27 | handler.remove() 28 | assert f(2) == 2 29 | with pytest.raises(RuntimeError): 30 | handler.enable() 31 | with pytest.raises(RuntimeError): 32 | handler.disable() 33 | 34 | 35 | def test_handler_call(): 36 | def f(x): 37 | return x 38 | 39 | x = 0 # This is the variable we will modify in the handler 40 | handler = dowhen.do("x = 1").when(f, "return x") 41 | frame = sys._getframe() 42 | handler(frame) 43 | assert x == 1 44 | 45 | x = 0 46 | handler.disable() 47 | handler(frame) 48 | assert x == 0 49 | 50 | with dowhen.do("pass").when(None, "assert") as handler: 51 | assert handler(frame) is None 52 | 53 | with dowhen.do("pass").when(None, "pass") as handler: 54 | assert handler(frame) is dowhen.DISABLE 55 | 56 | 57 | def test_handler_disable(): 58 | def f(x): 59 | return x 60 | 61 | def cb(): 62 | return dowhen.DISABLE 63 | 64 | handler = dowhen.do(cb).when(f, "return x") 65 | frame = sys._getframe() 66 | assert handler(frame) is dowhen.DISABLE 67 | assert handler.disabled 68 | 69 | handler = dowhen.do("x = 1").when(f, "return x", condition=lambda: dowhen.DISABLE) 70 | assert handler(frame) is dowhen.DISABLE 71 | assert handler.disabled 72 | 73 | 74 | def test_remove(): 75 | def f(x): 76 | return x 77 | 78 | def change(x): 79 | return {"x": 1} 80 | 81 | handler = dowhen.do(change).when(f, "return x") 82 | handler.remove() 83 | assert handler.removed is True 84 | 85 | assert f(0) == 0 86 | 87 | # double remove should be safe 88 | handler.remove() 89 | 90 | 91 | def test_with(): 92 | def f(x): 93 | return x 94 | 95 | with dowhen.do("x = 1").when(f, "return x"): 96 | assert f(0) == 1 97 | assert f(0) == 0 98 | 99 | 100 | def test_chain(): 101 | def f(x): 102 | x += 1 103 | assert False 104 | return x 105 | 106 | dowhen.when(f, "x += 1").do("x += 1").do("x += 1").goto("return x").bp() 107 | 108 | commands = """ 109 | p x + 100 110 | c 111 | """ 112 | 113 | with do_pdb_test(commands) as output: 114 | assert f(0) == 2 115 | 116 | out = output.getvalue() 117 | assert "(Pdb) " in out 118 | assert "102" in out 119 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dowhen 2 | 3 | [![build](https://github.com/gaogaotiantian/dowhen/actions/workflows/build_test.yml/badge.svg)](https://github.com/gaogaotiantian/dowhen/actions/workflows/build_test.yml) 4 | [![readthedocs](https://img.shields.io/readthedocs/dowhen)](https://dowhen.readthedocs.io/) 5 | [![coverage](https://img.shields.io/codecov/c/github/gaogaotiantian/dowhen)](https://codecov.io/gh/gaogaotiantian/dowhen) 6 | [![pypi](https://img.shields.io/pypi/v/dowhen.svg)](https://pypi.org/project/dowhen/) 7 | [![support-version](https://img.shields.io/pypi/pyversions/dowhen)](https://img.shields.io/pypi/pyversions/dowhen) 8 | [![sponsor](https://img.shields.io/badge/%E2%9D%A4-Sponsor%20me-%23c96198?style=flat&logo=GitHub)](https://github.com/sponsors/gaogaotiantian) 9 | 10 | `dowhen` makes instrumentation (monkeypatch) super intuitive and maintainable 11 | with minimal overhead! 12 | 13 | You can execute arbitrary code at specific points of your application, 14 | third-party libraries or stdlib in order to 15 | 16 | * debug your program 17 | * change the original behavior of the libraries 18 | * monitor your application 19 | 20 | ## Installation 21 | 22 | ``` 23 | pip install dowhen 24 | ``` 25 | 26 | ## Usage 27 | 28 | The core idea behind `dowhen` is to do a *callback* on a *trigger*. The 29 | *trigger* is specified with `when` and there are 3 kinds of *callbacks*. 30 | 31 | ### do 32 | 33 | `do` executes an arbitrary piece of code. 34 | 35 | ```python 36 | from dowhen import do 37 | 38 | def f(x): 39 | x += 100 40 | # Let's change the value of x before return 41 | return x 42 | 43 | # do("x = 1") is the callback 44 | # when(f, "return x") is the trigger 45 | # This is equivalent to: 46 | # handler = when(f, "return x").do("x = 1") 47 | handler = do("x = 1").when(f, "return x") 48 | # x = 1 is executed before "return x" 49 | assert f(0) == 1 50 | 51 | # You can remove the handler 52 | handler.remove() 53 | assert f(0) == 100 54 | ``` 55 | 56 | ### bp 57 | 58 | `bp` sets a breakpoint and brings up `pdb`. 59 | 60 | ```python 61 | from dowhen import bp 62 | 63 | # bp() is another callback that brings up pdb 64 | handler = bp().when(f, "return x") 65 | # This will enter pdb 66 | f(0) 67 | # You can temporarily disable the handler 68 | # handler.enable() will enable it again 69 | handler.disable() 70 | ``` 71 | 72 | ### goto 73 | 74 | `goto` changes the next line to execute. 75 | 76 | ```python 77 | from dowhen import goto 78 | 79 | # This will skip the line of `x += 100` 80 | # The handler will be removed after the with context 81 | with goto("return x").when(f, "x += 100"): 82 | assert f(0) == 0 83 | ``` 84 | 85 | ### callback chains 86 | 87 | ```python 88 | from dowhen import when 89 | 90 | # You can chain callbacks and they'll run in order at the trigger 91 | # You don't need to store the handler if you don't use it 92 | when(f, "x += 100").goto("return x").do("x = 42") 93 | assert f(0) == 42 94 | ``` 95 | 96 | See detailed documentation at https://dowhen.readthedocs.io/ 97 | 98 | ## License 99 | 100 | Copyright 2025 Tian Gao. 101 | 102 | Distributed under the terms of the [Apache 2.0 license](https://github.com/gaogaotiantian/dowhen/blob/master/LICENSE). 103 | -------------------------------------------------------------------------------- /tests/test_instrumenter.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import dis 6 | import sys 7 | 8 | import dowhen 9 | from dowhen.instrumenter import Instrumenter 10 | 11 | from .util import disable_coverage 12 | 13 | E = sys.monitoring.events 14 | 15 | 16 | def assert_instrumented_line_count(func, count): 17 | assert ( 18 | len( 19 | [ 20 | inst 21 | for inst in dis.get_instructions(func, adaptive=True) 22 | if inst.opname == "INSTRUMENTED_LINE" 23 | ] 24 | ) 25 | == count 26 | ) 27 | 28 | 29 | def test_local_events(): 30 | def f(x): 31 | return x 32 | 33 | handler_line = dowhen.do("x = 1").when(f, "return x") 34 | assert sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) == E.LINE 35 | 36 | dowhen.do("x = 1").when(f, "") 37 | assert ( 38 | sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) 39 | == E.LINE | E.PY_START 40 | ) 41 | 42 | dowhen.do("x = 1").when(f, "") 43 | assert ( 44 | sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) 45 | == E.LINE | E.PY_START | E.PY_RETURN 46 | ) 47 | 48 | handler_line.remove() 49 | assert ( 50 | sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) 51 | == E.PY_START | E.PY_RETURN 52 | ) 53 | 54 | dowhen.clear_all() 55 | assert ( 56 | sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) 57 | == E.NO_EVENTS 58 | ) 59 | 60 | 61 | def test_events_on_same_line(): 62 | def f(x): 63 | return x 64 | 65 | handler1 = dowhen.do("x = 1").when(f, "return x") 66 | handler2 = dowhen.do("x = 1").when(f, "return x") 67 | 68 | assert sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) == E.LINE 69 | 70 | handler1.remove() 71 | assert sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) == E.LINE 72 | 73 | handler2.remove() 74 | assert ( 75 | sys.monitoring.get_local_events(Instrumenter().tool_id, f.__code__) 76 | == E.NO_EVENTS 77 | ) 78 | 79 | 80 | def test_line_event_disabled(): 81 | def f(x): 82 | x += 1 83 | return x 84 | 85 | dowhen.do("x = 1").when(f, "return x") 86 | with disable_coverage(): 87 | f(0) 88 | assert_instrumented_line_count(f, 1) 89 | 90 | 91 | def test_disable_from_callback(): 92 | def f(x): 93 | return x 94 | 95 | call_count = 0 96 | 97 | def cb(): 98 | nonlocal call_count 99 | call_count += 1 100 | return dowhen.DISABLE 101 | 102 | handler = dowhen.do(cb).when(f, "return x") 103 | 104 | f(0) 105 | f(0) 106 | assert call_count == 1 107 | assert handler.disabled 108 | 109 | handler.enable() 110 | f(0) 111 | f(0) 112 | assert call_count == 2 113 | 114 | with disable_coverage(): 115 | f(0) 116 | assert_instrumented_line_count(f, 0) 117 | 118 | 119 | def test_disable_from_condition(): 120 | def f(x): 121 | return x 122 | 123 | call_count = 0 124 | 125 | def cond(): 126 | nonlocal call_count 127 | call_count += 1 128 | return dowhen.DISABLE 129 | 130 | handler = dowhen.when(f, "return x", condition=cond).do("x = 1") 131 | 132 | f(0) 133 | f(0) 134 | assert call_count == 1 135 | assert handler.disabled 136 | 137 | handler.enable() 138 | f(0) 139 | f(0) 140 | assert call_count == 2 141 | 142 | with disable_coverage(): 143 | f(0) 144 | assert_instrumented_line_count(f, 0) 145 | -------------------------------------------------------------------------------- /src/dowhen/util.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | from __future__ import annotations 6 | 7 | import functools 8 | import inspect 9 | import re 10 | from collections.abc import Callable 11 | from types import CodeType, FrameType, FunctionType, MethodType, ModuleType 12 | from typing import Any 13 | 14 | from .types import IdentifierType 15 | 16 | 17 | def getrealsourcelines(obj) -> tuple[list[str], int]: 18 | try: 19 | lines, start_line = inspect.getsourcelines(obj) 20 | # We need to find the actual definition of the function/class 21 | # when it is decorated 22 | while lines[0].strip().startswith("@"): 23 | # If the first line is a decorator, we need to skip it 24 | # and move to the next line 25 | lines.pop(0) 26 | start_line += 1 27 | except OSError: 28 | lines, start_line = [], obj.co_firstlineno 29 | 30 | return lines, start_line 31 | 32 | 33 | @functools.lru_cache(maxsize=256) 34 | def get_all_code_objects(code: CodeType) -> list[CodeType]: 35 | """ 36 | Recursively get all code objects from the given code object. 37 | """ 38 | all_code_objects = [] 39 | stack = [code] 40 | while stack: 41 | current_code = stack.pop() 42 | assert isinstance(current_code, CodeType) 43 | 44 | all_code_objects.append(current_code) 45 | for const in current_code.co_consts: 46 | if isinstance(const, CodeType): 47 | stack.append(const) 48 | 49 | return all_code_objects 50 | 51 | 52 | @functools.lru_cache(maxsize=256) 53 | def get_line_numbers( 54 | code: CodeType, identifier: IdentifierType | tuple[IdentifierType, ...] 55 | ) -> dict[CodeType, list[int]]: 56 | if not isinstance(identifier, tuple): 57 | identifier = (identifier,) 58 | 59 | line_numbers_ret: dict[CodeType, list[int]] = {} 60 | line_numbers_sets = [] 61 | 62 | lines, start_line = getrealsourcelines(code) 63 | 64 | for ident in identifier: 65 | if isinstance(ident, int): 66 | line_numbers_set = {ident} 67 | else: 68 | if isinstance(ident, str) or isinstance(ident, re.Pattern): 69 | line_numbers_set = set() 70 | for i, line in enumerate(lines): 71 | line = line.strip() 72 | if (isinstance(ident, str) and line.startswith(ident)) or ( 73 | isinstance(ident, re.Pattern) and ident.match(line) 74 | ): 75 | line_number = start_line + i 76 | line_numbers_set.add(line_number) 77 | else: 78 | raise TypeError(f"Unknown identifier type: {type(ident)}") 79 | 80 | if not line_numbers_set: 81 | return {} 82 | line_numbers_sets.append(line_numbers_set) 83 | 84 | agreed_line_numbers = set.intersection(*line_numbers_sets) 85 | for sub_code in get_all_code_objects(code): 86 | for line_number in agreed_line_numbers: 87 | if line_number in (line[2] for line in sub_code.co_lines()): 88 | line_numbers_ret.setdefault(sub_code, []).append(line_number) 89 | 90 | for line_numbers in line_numbers_ret.values(): 91 | line_numbers.sort() 92 | 93 | return line_numbers_ret 94 | 95 | 96 | @functools.lru_cache(maxsize=256) 97 | def get_func_args(func: Callable) -> list[str]: 98 | args = inspect.getfullargspec(inspect.unwrap(func)).args 99 | # For bound methods, skip the first argument since it's already bound 100 | if inspect.ismethod(func): 101 | return args[1:] 102 | else: 103 | return args 104 | 105 | 106 | def call_in_frame(func: Callable, frame: FrameType, **kwargs) -> Any: 107 | f_locals = frame.f_locals 108 | args = [] 109 | for arg in get_func_args(func): 110 | if arg == "_frame": 111 | argval = frame 112 | elif arg == "_retval": 113 | if "retval" not in kwargs: 114 | raise TypeError("You can only use '_retval' in callbacks.") 115 | argval = kwargs["retval"] 116 | elif arg in f_locals: 117 | argval = f_locals[arg] 118 | else: 119 | raise TypeError(f"Argument '{arg}' not found in frame locals.") 120 | args.append(argval) 121 | return func(*args) 122 | 123 | 124 | def get_source_hash(entity: CodeType | FunctionType | MethodType | ModuleType | type): 125 | import hashlib 126 | 127 | source = inspect.getsource(entity) 128 | return hashlib.md5(source.encode("utf-8")).hexdigest()[-8:] 129 | 130 | 131 | def clear_all() -> None: 132 | from .instrumenter import Instrumenter 133 | 134 | Instrumenter().clear_all() 135 | get_all_code_objects.cache_clear() 136 | get_line_numbers.cache_clear() 137 | get_func_args.cache_clear() 138 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # Abstra 171 | # Abstra is an AI-powered process automation framework. 172 | # Ignore directories containing user credentials, local state, and settings. 173 | # Learn more at https://abstra.io/docs 174 | .abstra/ 175 | 176 | # Visual Studio Code 177 | # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore 178 | # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore 179 | # and can be added to the global gitignore or merged into this file. However, if you prefer, 180 | # you could uncomment the following to ignore the enitre vscode folder 181 | # .vscode/ 182 | 183 | # Ruff stuff: 184 | .ruff_cache/ 185 | 186 | # PyPI configuration file 187 | .pypirc 188 | 189 | # Cursor 190 | # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to 191 | # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data 192 | # refer to https://docs.cursor.com/context/ignore-files 193 | .cursorignore 194 | .cursorindexingignore -------------------------------------------------------------------------------- /tests/test_callback.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import sys 6 | 7 | import pytest 8 | 9 | import dowhen 10 | 11 | from .util import do_pdb_test 12 | 13 | 14 | def test_do_when(): 15 | def f(x): 16 | return x 17 | 18 | dowhen.do("x = 1").when(f, "return x") 19 | assert f(2) == 1 20 | dowhen.clear_all() 21 | assert f(2) == 2 22 | 23 | 24 | def test_do_when_with_function(): 25 | def f(x, y): 26 | return x + y 27 | 28 | def change(x, y): 29 | x = 2 30 | y = 3 31 | return {"x": x, "y": y} 32 | 33 | dowhen.do(change).when(f, "return x + y") 34 | assert f(1, 1) == 5 35 | 36 | 37 | def test_do_when_with_method(): 38 | def f(x): 39 | return x 40 | 41 | class A: 42 | def change(self, x): 43 | return {"x": 1} 44 | 45 | @classmethod 46 | def classmethod_change(cls, x): 47 | return {"x": 2} 48 | 49 | @staticmethod 50 | def staticmethod_change(x): 51 | return {"x": 3} 52 | 53 | with dowhen.do(A().change).when(f, "return x"): 54 | assert f(2) == 1 55 | 56 | with dowhen.do(A.classmethod_change).when(f, "return x"): 57 | assert f(3) == 2 58 | 59 | with dowhen.do(A.staticmethod_change).when(f, "return x"): 60 | assert f(4) == 3 61 | 62 | 63 | def test_callback_call(): 64 | x = 0 65 | callback = dowhen.do("x = 1") 66 | frame = sys._getframe() 67 | callback(frame) 68 | assert x == 1 69 | 70 | 71 | def test_method_callback_call(): 72 | class A: 73 | def change(self, x): 74 | return {"x": 1} 75 | 76 | x = 0 77 | callback = dowhen.do(A().change) 78 | frame = sys._getframe() 79 | callback(frame) 80 | assert x == 1 81 | 82 | 83 | def test_callback_writeback(): 84 | x = 0 85 | 86 | def change(x): 87 | return {"x": 1} 88 | 89 | def change_with_frame(_frame): 90 | return {"x": _frame.f_locals["x"] + 1} 91 | 92 | def change_wrong(x): 93 | return {"y": 1} 94 | 95 | def change_wrong_type(x): 96 | return [1] 97 | 98 | frame = sys._getframe() 99 | callback = dowhen.do(change) 100 | callback(frame) 101 | assert x == 1 102 | 103 | callback = dowhen.do(change_with_frame) 104 | callback(frame) 105 | assert x == 2 106 | 107 | with pytest.raises(TypeError): 108 | callback_wrong = dowhen.do(change_wrong) 109 | callback_wrong(frame) 110 | 111 | with pytest.raises(TypeError): 112 | callback_wrong_type = dowhen.do(change_wrong_type) 113 | callback_wrong_type(frame) 114 | 115 | callback = dowhen.do(change) 116 | del x 117 | with pytest.raises(TypeError): 118 | callback(frame) 119 | 120 | dowhen.clear_all() 121 | 122 | 123 | def test_callback_retval(): 124 | def f(x): 125 | return x 126 | 127 | retval_holder = [] 128 | 129 | def cb(_retval): 130 | retval_holder.append(_retval) 131 | 132 | with dowhen.do(cb).when(f, ""): 133 | assert f(0) == 0 134 | assert retval_holder == [0] 135 | 136 | with pytest.raises(TypeError): 137 | with dowhen.do(cb).when(f, "return x"): 138 | f(0) 139 | 140 | retval_holder.clear() 141 | callback = dowhen.do(cb) 142 | frame = sys._getframe() 143 | assert callback(frame, retval=0) is None 144 | assert retval_holder == [0] 145 | 146 | with pytest.raises(TypeError): 147 | callback(frame) 148 | 149 | 150 | def test_callback_disable(): 151 | def cb(): 152 | return dowhen.DISABLE 153 | 154 | callback = dowhen.do(cb) 155 | frame = sys._getframe() 156 | assert callback(frame) is dowhen.DISABLE 157 | 158 | 159 | def test_callback_invalid_type(): 160 | with pytest.raises(TypeError): 161 | dowhen.do(123) 162 | 163 | def f(x): 164 | return x 165 | 166 | def change(y): 167 | return {"y": 1} 168 | 169 | def change_wrong(x): 170 | return {"y": 1} 171 | 172 | def change_wrong_type(x): 173 | return [1] 174 | 175 | with pytest.raises(TypeError): 176 | dowhen.do(change).when(f, "return x") 177 | f(0) 178 | 179 | with pytest.raises(TypeError): 180 | dowhen.do(change_wrong).when(f, "return x") 181 | f(0) 182 | 183 | with pytest.raises(TypeError): 184 | dowhen.do(change_wrong_type).when(f, "return x") 185 | f(0) 186 | 187 | 188 | def test_frame(): 189 | def f(x): 190 | return x 191 | 192 | def cb(_frame): 193 | return {"x": _frame.f_locals["x"] + 1} 194 | 195 | dowhen.do(cb).when(f, "return x") 196 | assert f(0) == 1 197 | 198 | 199 | def test_goto(): 200 | def f(): 201 | x = 0 202 | if x == 0: 203 | assert False 204 | x = 1 205 | return x 206 | 207 | with dowhen.goto("x = 1").when(f, "assert False"): 208 | assert f() == 1 209 | 210 | with dowhen.goto("+1").when(f, "assert False"): 211 | assert f() == 1 212 | 213 | 214 | def test_bp(): 215 | def f(x): 216 | x = x + 1 217 | return x 218 | 219 | command = """ 220 | w 221 | n 222 | c 223 | """ 224 | 225 | handler1 = dowhen.bp().when(f, "x = x + 1") 226 | with do_pdb_test(command) as output1: 227 | f(0) 228 | handler1.remove() 229 | 230 | handler2 = dowhen.when(f, "x = x + 1").bp() 231 | with do_pdb_test(command) as output2: 232 | f(0) 233 | handler2.remove() 234 | 235 | for out in (output1.getvalue(), output2.getvalue()): 236 | assert "x = x + 1" in out 237 | assert "(Pdb) " in out 238 | assert "test_bp()" in out 239 | assert "return x" in out 240 | -------------------------------------------------------------------------------- /src/dowhen/callback.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | from __future__ import annotations 6 | 7 | import ctypes 8 | import inspect 9 | import sys 10 | import warnings 11 | from collections.abc import Callable 12 | from types import CodeType, FrameType, FunctionType, MethodType, ModuleType 13 | from typing import TYPE_CHECKING, Any 14 | 15 | from .types import IdentifierType 16 | from .util import call_in_frame, get_line_numbers 17 | 18 | if TYPE_CHECKING: # pragma: no cover 19 | from .handler import EventHandler 20 | 21 | 22 | DISABLE = sys.monitoring.DISABLE 23 | 24 | 25 | class Callback: 26 | def __init__(self, func: str | Callable, **kwargs): 27 | if isinstance(func, str): 28 | pass 29 | elif inspect.isfunction(func): 30 | self.func_args = inspect.getfullargspec(func).args 31 | elif inspect.ismethod(func): 32 | self.func_args = inspect.getfullargspec(func).args 33 | else: 34 | raise TypeError(f"Unsupported callback type: {type(func)}. ") 35 | self.func = func 36 | self.kwargs = kwargs 37 | 38 | def __call__(self, frame: FrameType, **kwargs) -> Any: 39 | ret = None 40 | if isinstance(self.func, str): 41 | if self.func == "goto": # pragma: no cover 42 | self._call_goto(frame) 43 | else: 44 | self._call_code(frame) 45 | elif inspect.isfunction(self.func) or inspect.ismethod(self.func): 46 | ret = self._call_function(frame, **kwargs) 47 | else: # pragma: no cover 48 | assert False, "Unknown callback type" 49 | 50 | if sys.version_info < (3, 13): 51 | LocalsToFast = ctypes.pythonapi.PyFrame_LocalsToFast 52 | LocalsToFast.argtypes = [ctypes.py_object, ctypes.c_int] 53 | LocalsToFast(frame, 0) 54 | 55 | if ret is DISABLE: 56 | return DISABLE 57 | 58 | def _call_code(self, frame: FrameType) -> None: 59 | assert isinstance(self.func, str) 60 | exec(self.func, frame.f_globals, frame.f_locals) 61 | 62 | def _call_function(self, frame: FrameType, **kwargs) -> Any: 63 | assert isinstance(self.func, (FunctionType, MethodType)) 64 | writeback = call_in_frame(self.func, frame, **kwargs) 65 | 66 | f_locals = frame.f_locals 67 | if isinstance(writeback, dict): 68 | for arg, val in writeback.items(): 69 | if arg not in f_locals: 70 | raise TypeError(f"Argument '{arg}' not found in frame locals.") 71 | f_locals[arg] = val 72 | elif writeback is DISABLE: 73 | return DISABLE 74 | elif writeback is not None: 75 | raise TypeError( 76 | "Callback function must return a dictionary for writeback, or None, " 77 | f"got {type(writeback)} instead." 78 | ) 79 | 80 | def _call_goto(self, frame: FrameType) -> None: # pragma: no cover 81 | # Changing frame.f_lineno is only allowed in trace functions so it's 82 | # impossible to get coverage for this function 83 | target = self.kwargs["target"] 84 | if isinstance(target, int): 85 | line_number = target 86 | elif ( 87 | isinstance(target, str) 88 | and (target.startswith("+") or target.startswith("-")) 89 | and target[1:].isdigit() 90 | ): 91 | line_number = frame.f_lineno + int(target) 92 | else: 93 | line_numbers = get_line_numbers(frame.f_code, target).get( 94 | frame.f_code, None 95 | ) 96 | if line_numbers is None: 97 | raise ValueError( 98 | f"Could not determine line number for target: {target}" 99 | ) 100 | elif len(line_numbers) > 1: 101 | raise ValueError( 102 | f"Multiple line numbers found for target '{target}': {line_numbers}" 103 | ) 104 | line_number = line_numbers[0] 105 | with warnings.catch_warnings(): 106 | # This gives a RuntimeWarning in Python 3.12 107 | warnings.simplefilter("ignore", RuntimeWarning) 108 | # mypy thinks f_lineno is read-only 109 | frame.f_lineno = line_number # type: ignore 110 | 111 | @classmethod 112 | def do(cls, func: str | Callable) -> Callback: 113 | return cls(func) 114 | 115 | @classmethod 116 | def goto(cls, target: str | int) -> Callback: 117 | return cls("goto", target=target) 118 | 119 | @classmethod 120 | def bp(cls) -> Callback: 121 | def do_breakpoint(_frame: FrameType) -> None: # pragma: no cover 122 | import pdb 123 | 124 | p = pdb.Pdb() 125 | p.set_trace(_frame) 126 | if hasattr(p, "set_enterframe"): 127 | # set_enterframe is backported to 3.12 so the early versions 128 | # of Python 3.12 will not have this method 129 | with p.set_enterframe(_frame): 130 | p.user_line(_frame) 131 | else: 132 | p.user_line(_frame) 133 | 134 | return cls(do_breakpoint) 135 | 136 | def when( 137 | self, 138 | entity: CodeType | FunctionType | MethodType | ModuleType | type | None, 139 | *identifiers: IdentifierType | tuple[IdentifierType, ...], 140 | condition: str | Callable[..., bool | Any] | None = None, 141 | source_hash: str | None = None, 142 | ) -> "EventHandler": 143 | from .trigger import when 144 | 145 | trigger = when( 146 | entity, *identifiers, condition=condition, source_hash=source_hash 147 | ) 148 | 149 | from .handler import EventHandler 150 | 151 | handler = EventHandler(trigger, self) 152 | handler.submit() 153 | 154 | return handler 155 | 156 | 157 | bp = Callback.bp 158 | do = Callback.do 159 | goto = Callback.goto 160 | -------------------------------------------------------------------------------- /src/dowhen/instrumenter.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | from __future__ import annotations 5 | 6 | import sys 7 | from collections import defaultdict 8 | from types import CodeType, FrameType 9 | from typing import TYPE_CHECKING 10 | 11 | if TYPE_CHECKING: # pragma: no cover 12 | from .handler import EventHandler 13 | 14 | E = sys.monitoring.events 15 | DISABLE = sys.monitoring.DISABLE 16 | 17 | 18 | class Instrumenter: 19 | _initialized: bool = False 20 | 21 | def __new__(cls, *args, **kwargs) -> Instrumenter: 22 | if not hasattr(cls, "_instance"): 23 | cls._instance = super().__new__(cls) 24 | return cls._instance 25 | 26 | def __init__(self, tool_id: int = 4): 27 | if not self._initialized: 28 | self.tool_id = tool_id 29 | self.handlers: defaultdict[CodeType | None, dict] = defaultdict(dict) 30 | 31 | sys.monitoring.use_tool_id(self.tool_id, "dowhen instrumenter") 32 | sys.monitoring.register_callback(self.tool_id, E.LINE, self.line_callback) 33 | sys.monitoring.register_callback( 34 | self.tool_id, E.PY_RETURN, self.return_callback 35 | ) 36 | sys.monitoring.register_callback( 37 | self.tool_id, E.PY_START, self.start_callback 38 | ) 39 | self._initialized = True 40 | 41 | def clear_all(self) -> None: 42 | for code in self.handlers: 43 | if code is None: 44 | sys.monitoring.set_events(self.tool_id, E.NO_EVENTS) 45 | else: 46 | sys.monitoring.set_local_events(self.tool_id, code, E.NO_EVENTS) 47 | self.handlers.clear() 48 | 49 | def submit(self, event_handler: "EventHandler") -> None: 50 | trigger = event_handler.trigger 51 | for event in trigger.events: 52 | code = event.code 53 | if event.event_type == "line": 54 | assert ( 55 | isinstance(event.event_data, dict) 56 | and "line_number" in event.event_data 57 | ) 58 | self.register_line_event( 59 | code, 60 | event.event_data["line_number"], 61 | event_handler, 62 | ) 63 | elif event.event_type == "start": 64 | self.register_start_event(code, event_handler) 65 | elif event.event_type == "return": 66 | self.register_return_event(code, event_handler) 67 | 68 | def register_line_event( 69 | self, code: CodeType | None, line_number: int, event_handler: "EventHandler" 70 | ) -> None: 71 | self.handlers[code].setdefault("line", {}).setdefault(line_number, []).append( 72 | event_handler 73 | ) 74 | 75 | if code is None: 76 | events = sys.monitoring.get_events(self.tool_id) 77 | sys.monitoring.set_events(self.tool_id, events | E.LINE) 78 | else: 79 | events = sys.monitoring.get_local_events(self.tool_id, code) 80 | sys.monitoring.set_local_events(self.tool_id, code, events | E.LINE) 81 | sys.monitoring.restart_events() 82 | 83 | def line_callback(self, code: CodeType, line_number: int): # pragma: no cover 84 | handlers = [] 85 | if None in self.handlers: 86 | handlers.extend(self.handlers[None].get("line", {}).get(line_number, [])) 87 | handlers.extend(self.handlers[None].get("line", {}).get(None, [])) 88 | if code in self.handlers: 89 | handlers.extend(self.handlers[code].get("line", {}).get(line_number, [])) 90 | handlers.extend(self.handlers[code].get("line", {}).get(None, [])) 91 | if handlers: 92 | return self._process_handlers(handlers, sys._getframe(1)) 93 | return sys.monitoring.DISABLE 94 | 95 | def register_start_event( 96 | self, code: CodeType | None, event_handler: "EventHandler" 97 | ) -> None: 98 | self.handlers[code].setdefault("start", []).append(event_handler) 99 | 100 | if code is None: 101 | events = sys.monitoring.get_events(self.tool_id) 102 | sys.monitoring.set_events(self.tool_id, events | E.PY_START) 103 | else: 104 | events = sys.monitoring.get_local_events(self.tool_id, code) 105 | sys.monitoring.set_local_events(self.tool_id, code, events | E.PY_START) 106 | sys.monitoring.restart_events() 107 | 108 | def start_callback(self, code: CodeType, offset: int): # pragma: no cover 109 | handlers = [] 110 | if None in self.handlers: 111 | handlers.extend(self.handlers[None].get("start", [])) 112 | if code in self.handlers: 113 | handlers.extend(self.handlers[code].get("start", [])) 114 | if handlers: 115 | return self._process_handlers(handlers, sys._getframe(1)) 116 | return sys.monitoring.DISABLE 117 | 118 | def register_return_event( 119 | self, code: CodeType | None, event_handler: "EventHandler" 120 | ) -> None: 121 | self.handlers[code].setdefault("return", []).append(event_handler) 122 | 123 | if code is None: 124 | events = sys.monitoring.get_events(self.tool_id) 125 | sys.monitoring.set_events(self.tool_id, events | E.PY_RETURN) 126 | else: 127 | events = sys.monitoring.get_local_events(self.tool_id, code) 128 | sys.monitoring.set_local_events(self.tool_id, code, events | E.PY_RETURN) 129 | sys.monitoring.restart_events() 130 | 131 | def return_callback( 132 | self, code: CodeType, offset: int, retval: object 133 | ): # pragma: no cover 134 | handlers = [] 135 | if None in self.handlers: 136 | handlers.extend(self.handlers[None].get("return", [])) 137 | if code in self.handlers: 138 | handlers.extend(self.handlers[code].get("return", [])) 139 | if handlers: 140 | return self._process_handlers(handlers, sys._getframe(1), retval=retval) 141 | return sys.monitoring.DISABLE 142 | 143 | def _process_handlers( 144 | self, handlers: list["EventHandler"], frame: FrameType, **kwargs 145 | ): # pragma: no cover 146 | disable = sys.monitoring.DISABLE 147 | for handler in handlers: 148 | disable = handler(frame, **kwargs) and disable 149 | return sys.monitoring.DISABLE if disable else None 150 | 151 | def restart_events(self) -> None: 152 | sys.monitoring.restart_events() 153 | 154 | def remove_handler(self, event_handler: "EventHandler") -> None: 155 | trigger = event_handler.trigger 156 | for event in trigger.events: 157 | code = event.code 158 | if code not in self.handlers or event.event_type not in self.handlers[code]: 159 | continue 160 | if event.event_type == "line": 161 | assert ( 162 | isinstance(event.event_data, dict) 163 | and "line_number" in event.event_data 164 | ) 165 | handlers = self.handlers[code]["line"].get( 166 | event.event_data["line_number"], [] 167 | ) 168 | else: 169 | handlers = self.handlers[code][event.event_type] 170 | 171 | if event_handler in handlers: 172 | handlers.remove(event_handler) 173 | 174 | if event.event_type == "line" and not handlers: 175 | assert ( 176 | isinstance(event.event_data, dict) 177 | and "line_number" in event.event_data 178 | ) 179 | del self.handlers[code]["line"][event.event_data["line_number"]] 180 | 181 | if not self.handlers[code][event.event_type]: 182 | del self.handlers[code][event.event_type] 183 | removed_event = { 184 | "line": E.LINE, 185 | "start": E.PY_START, 186 | "return": E.PY_RETURN, 187 | }[event.event_type] 188 | 189 | if code is None: 190 | events = sys.monitoring.get_events(self.tool_id) 191 | sys.monitoring.set_events(self.tool_id, events & ~removed_event) 192 | else: 193 | events = sys.monitoring.get_local_events(self.tool_id, code) 194 | sys.monitoring.set_local_events( 195 | self.tool_id, code, events & ~removed_event 196 | ) 197 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Usage Guide 2 | =========== 3 | 4 | This guide provides comprehensive information on how to use ``dowhen`` for instrumentation. 5 | 6 | Basic Concepts 7 | -------------- 8 | 9 | An instrumentation is basically a callback on a trigger. You can think of ``do`` as a callback, and ``when`` as a trigger. 10 | 11 | Triggers 12 | -------- 13 | 14 | ``when`` 15 | ~~~~~~~~ 16 | 17 | ``when`` takes an ``entity``, optional positional ``identifiers`` and an optional keyword-only ``condition``. 18 | 19 | * ``entity`` - a function, method, code object, class, module or ``None`` 20 | * ``identifiers`` - something to locate a specific line or a special event 21 | * ``condition`` - an expression or a function to determine whether the trigger should fire 22 | 23 | Entity 24 | ^^^^^^ 25 | 26 | You need to specify an entity to instrument. This can be a function, method, code object, class, module or ``None``. 27 | 28 | If you pass a class or module, ``dowhen`` will instrument all functions and methods in that class or module. 29 | 30 | If you pass ``None``, ``dowhen`` will instrument globally, which means every code object will be instrumented. 31 | This will introduce an overhead at the beginning, but the unnecessary events will be disabled while the 32 | program is running. 33 | 34 | Identifiers 35 | ^^^^^^^^^^^ 36 | 37 | Line 38 | """" 39 | 40 | To locate a line, you can use the absolute line number, a string starting with ``+`` as 41 | the relative line number, the prefix of the line or a regex pattern. 42 | 43 | Notice that the indentation of the line is stripped before matching. 44 | 45 | .. code-block:: python 46 | 47 | from dowhen import when 48 | 49 | def f(x): 50 | return x # line 4 51 | 52 | # These will all locate line 4 53 | when(f, 4) # absolute line number 54 | when(f, "+1") # relative to function start 55 | when(f, "return x") # exact match of the line content 56 | when(f, "ret") # prefix of the line 57 | when(f, re.compile(r"return.*")) # regex 58 | 59 | If an identifier matches multiple lines, the callback will trigger on all of them. 60 | 61 | .. code-block:: python 62 | 63 | def f(x): 64 | x += 0 65 | x += 0 66 | return x 67 | 68 | do("x += 1").when(f, "x +=") # triggers on both lines 69 | assert f(0) == 2 70 | 71 | Special Events 72 | """""""""""""" 73 | 74 | Besides locating lines, you can also use special events as identifiers: 75 | 76 | * ``""`` - when the function is called 77 | * ``""`` - when the function returns 78 | 79 | .. code-block:: python 80 | 81 | when(f, "") # triggers when f is called 82 | when(f, "") # triggers when f returns 83 | 84 | Combination of Identifiers 85 | """""""""""""""""""""""""" 86 | 87 | You can combine multiple identifiers to make the trigger more specific: 88 | 89 | .. code-block:: python 90 | 91 | when(f, ("return x", "+1")) # triggers on `return x` only when it's the +1 line 92 | 93 | Multiple identifiers 94 | """""""""""""""""""" 95 | 96 | You can also specify multiple identifiers to trigger on: 97 | 98 | .. code-block:: python 99 | 100 | def f(x): 101 | for i in range(100): 102 | x += i 103 | return x 104 | 105 | do("print(x)").when(f, "return x", "") # triggers on both `return x` and when f is called 106 | 107 | Conditions 108 | ^^^^^^^^^^ 109 | 110 | You can add conditions to triggers to make them more specific: 111 | 112 | .. code-block:: python 113 | 114 | from dowhen import when 115 | 116 | def f(x): 117 | return x 118 | 119 | when(f, "return x", condition="x == 0").do("x = 1") 120 | assert f(0) == 1 # x is set to 1 when x is 0 121 | assert f(2) == 2 # x is not modified when x is not 0 122 | 123 | You can also use a function as a condition: 124 | 125 | .. code-block:: python 126 | 127 | from dowhen import when 128 | 129 | def f(x): 130 | return x 131 | 132 | def check(x): 133 | return x == 0 134 | 135 | when(f, "return x", condition=check).do("x = 1") 136 | assert f(0) == 1 # x is set to 1 when x is 0 137 | assert f(2) == 2 # x is not modified when x is not 0 138 | 139 | If the condition function returns ``dowhen.DISABLE``, the trigger will not fire anymore. 140 | 141 | .. code-block:: python 142 | 143 | from dowhen import when, DISABLE 144 | 145 | def f(x): 146 | return x 147 | 148 | def check(x): 149 | if x == 0: 150 | return True 151 | return DISABLE 152 | 153 | when(f, "return x", condition=check).do("x = 1") 154 | assert f(0) == 1 # x is set to 1 when x is 0 155 | assert f(2) == 2 # x is not modified and the trigger is disabled 156 | assert f(0) == 0 # x is not modified anymore 157 | 158 | Source Hash 159 | ^^^^^^^^^^^ 160 | 161 | If you need to confirm that the source code of the function has not changed, 162 | you can use the ``source_hash`` argument. 163 | 164 | .. code-block:: python 165 | 166 | from dowhen import when, get_source_hash 167 | 168 | def f(x): 169 | return x 170 | 171 | # Calculate this once and use the constant in your code 172 | source_hash = get_source_hash(f) 173 | # This will raise an error if the source code of f changes 174 | when(f, "return x", source_hash=source_hash).do("x = 1") 175 | 176 | ``source_hash`` is not a security feature. It is just a sanity check to ensure 177 | that the source code of the function has not changed so your instrumentation 178 | is still valid. It's just a piece of the md5 hash of the source code of the function. 179 | 180 | Callbacks 181 | --------- 182 | 183 | ``do`` 184 | ~~~~~~ 185 | 186 | ``do`` executes code when the trigger fires, it can be a string or a function. 187 | 188 | .. code-block:: python 189 | 190 | from dowhen import do 191 | 192 | def f(x): 193 | return x 194 | 195 | do("x = 1").when(f, "return x") 196 | assert f(0) == 1 197 | 198 | If you are using a function for ``do``, the local variables that match the function arguments 199 | will be automatically passed to the function. 200 | 201 | Special arguments: 202 | 203 | * ``_frame`` - when used, the current `frame object `_ is passed. 204 | * ``_retval`` - when used, the return value of the function is passed. Only valid for ```` triggers. 205 | 206 | If you want to change the value of the local variables, you need to return a dictionary 207 | with the variable names as keys and the new values as values. 208 | 209 | You can also return ``dowhen.DISABLE`` to disable the trigger. 210 | 211 | .. code-block:: python 212 | 213 | from dowhen import do 214 | 215 | def f(x): 216 | return x 217 | 218 | def callback(x): 219 | return {"x": 1} 220 | 221 | do(callback).when(f, "return x") 222 | assert f(0) == 1 223 | 224 | def callback_special(_frame, _retval): 225 | assert _frame.f_locals["x"] == 1 226 | assert _retval == 1 227 | 228 | do(callback_special).when(f, "") 229 | assert f(0) == 1 230 | 231 | ``bp`` 232 | ~~~~~~ 233 | 234 | ``bp`` enters pdb at the trigger. 235 | 236 | .. code-block:: python 237 | 238 | from dowhen import bp 239 | 240 | def f(x): 241 | return x 242 | 243 | # Equivalent to setting a breakpoint at f 244 | bp().when(f, "") 245 | 246 | ``goto`` 247 | ~~~~~~~~ 248 | 249 | ``goto`` can modify execution flow. 250 | 251 | .. code-block:: python 252 | 253 | from dowhen import goto 254 | 255 | def f(x): 256 | x = 1 257 | return x 258 | 259 | # This skips the line `x = 1` and goes directly to `return x` 260 | goto("return x").when(f, "x = 1") 261 | assert f(0) == 0 262 | 263 | You can pass an absolute line number or a source line to ``goto``, similar to ``identifier`` 264 | in ``when``. ``goto`` also takes a relative line number, but it is relative to the *executing line*. 265 | Therefore, it can take both ``+`` and ``-``. 266 | 267 | Handlers 268 | -------- 269 | 270 | When you combine a trigger with a callback, you create a handler. 271 | 272 | .. code-block:: python 273 | 274 | from dowhen import when, do 275 | 276 | def f(x): 277 | return x 278 | 279 | # This creates a handler 280 | handler = when(f, "return x").do("x = 1") 281 | assert f(0) == 1 # x is set to 1 when f is called 282 | 283 | # You can temporarily disable the handler 284 | handler.disable() 285 | assert f(0) == 0 # x is not modified anymore 286 | 287 | # You can re-enable the handler 288 | handler.enable() 289 | assert f(0) == 1 # x is set to 1 again 290 | 291 | # You can also remove the handler permanently 292 | handler.remove() 293 | assert f(0) == 0 # x is not modified anymore 294 | 295 | You can use ``with`` statement to create a handler that is automatically removed after the block: 296 | 297 | .. code-block:: python 298 | 299 | from dowhen import do 300 | 301 | def f(x): 302 | return x 303 | 304 | with do("x = 1").when(f, "return x"): 305 | assert f(0) == 1 306 | assert f(0) == 0 307 | 308 | ``Handler`` can use ``do``, ``bp``, and ``goto`` as well, which allows you to 309 | chain multiple callbacks together: 310 | 311 | .. code-block:: python 312 | 313 | from dowhen import when 314 | 315 | def f(x): 316 | x += 100 317 | return x 318 | 319 | when(f, "x += 100").goto("return x").do("x += 1") 320 | assert f(0) == 1 321 | 322 | Utilities 323 | --------- 324 | 325 | clear_all 326 | ~~~~~~~~~ 327 | 328 | You can clear all handlers set by ``dowhen`` using ``clear_all``. 329 | 330 | .. code-block:: python 331 | 332 | from dowhen import clear_all 333 | 334 | clear_all() 335 | -------------------------------------------------------------------------------- /tests/test_trigger.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | import functools 6 | import re 7 | import sys 8 | 9 | import pytest 10 | 11 | import dowhen 12 | 13 | 14 | def test_event_line_number(): 15 | def f(): 16 | pass 17 | 18 | target_line_number = f.__code__.co_firstlineno + 1 19 | 20 | for entity in (f, f.__code__): 21 | for identifier in [ 22 | target_line_number, 23 | "+1", 24 | "pass", 25 | ("+1", "pass"), 26 | re.compile(r"pass"), 27 | ]: 28 | trigger = dowhen.when(entity, identifier) 29 | assert trigger.events[0].event_type == "line" 30 | assert trigger.events[0].event_data["line_number"] == target_line_number 31 | 32 | with pytest.raises(ValueError): 33 | dowhen.when(f, "nonexistent") 34 | 35 | with pytest.raises(ValueError): 36 | dowhen.when(f, ("+3", "pass")) 37 | 38 | 39 | def test_event_multiple_line_match(): 40 | def f(x): 41 | x += 1 42 | x += 2 43 | return x 44 | 45 | dowhen.when(f, "x +=").do("x += 1") 46 | assert f(0) == 5 47 | 48 | 49 | def test_when_do(): 50 | def f(x): 51 | return x 52 | 53 | dowhen.when(f, "return x").do("x = 1") 54 | assert f(2) == 1 55 | dowhen.clear_all() 56 | assert f(2) == 2 57 | 58 | 59 | def test_start_return(): 60 | def f(x): 61 | return x 62 | 63 | start_trigger = dowhen.when(f, "") 64 | assert start_trigger.events[0].event_type == "start" 65 | assert start_trigger.events[0].event_data == {} 66 | handler = start_trigger.do("x = 1") 67 | assert f(2) == 1 68 | handler.remove() 69 | assert f(2) == 2 70 | 71 | return_trigger = dowhen.when(f, "") 72 | assert return_trigger.events[0].event_type == "return" 73 | assert return_trigger.events[0].event_data == {} 74 | return_value = None 75 | 76 | def return_event_handler(): 77 | nonlocal return_value 78 | return_value = 42 79 | 80 | handler = return_trigger.do(return_event_handler) 81 | f(0) 82 | assert return_value == 42 83 | return_value = 0 84 | handler.remove() 85 | f(0) 86 | assert return_value == 0 87 | 88 | 89 | def test_closure(): 90 | def f(x): 91 | def g(): 92 | return x 93 | 94 | return g() 95 | 96 | dowhen.when(f, "return x").do("x = 1") 97 | assert f(2) == 1 98 | 99 | 100 | def test_method(): 101 | class A: 102 | def f(self, x): 103 | return x 104 | 105 | a = A() 106 | dowhen.when(a.f, "return x").do("x = 1") 107 | assert a.f(2) == 1 108 | 109 | 110 | def test_module(): 111 | import random 112 | 113 | co_lines = random.randrange.__code__.co_lines() 114 | for _, _, lineno in co_lines: 115 | if lineno != random.randrange.__code__.co_firstlineno: 116 | first_line = lineno 117 | break 118 | assert isinstance(first_line, int) 119 | write_back = [] 120 | with dowhen.when(random, first_line).do(lambda: write_back.append(True)): 121 | random.randrange(10) 122 | assert write_back == [True] 123 | write_back.clear() 124 | 125 | with dowhen.when(random, f"+{first_line}").do(lambda: write_back.append(True)): 126 | random.randrange(10) 127 | assert write_back == [True] 128 | 129 | 130 | def test_class(): 131 | class A: 132 | def f(self, x): 133 | return x 134 | 135 | def g(self, x): 136 | return x 137 | 138 | a = A() 139 | 140 | with dowhen.when(A, "return x").do("x = 1"): 141 | assert a.f(2) == 1 142 | assert a.g(2) == 1 143 | 144 | with dowhen.when(A, "+2").do("x = 1"): 145 | assert a.f(2) == 1 146 | assert a.g(2) == 2 147 | 148 | 149 | def test_decorator(): 150 | def decorator(func): 151 | @functools.wraps(func) 152 | def wrapper(x): 153 | return func(x) 154 | 155 | return wrapper 156 | 157 | @decorator 158 | def f(x): 159 | x += 1 160 | return x 161 | 162 | with dowhen.when(f, "return x").do("x = 42"): 163 | assert f(0) == 42 164 | 165 | with dowhen.when(f, "+1").do("x += 1"): 166 | assert f(0) == 2 167 | 168 | with dowhen.when(f, "+2").do("x = 42"): 169 | assert f(0) == 42 170 | 171 | @decorator 172 | def cond(x): 173 | return x > 1 174 | 175 | with dowhen.when(f, "return x", condition=cond).do("x = 42"): 176 | assert f(0) == 1 177 | assert f(1) == 42 178 | 179 | @decorator 180 | def cb(x): 181 | return {"x": 42} 182 | 183 | with dowhen.when(f, "return x").do(cb): 184 | assert f(0) == 42 185 | 186 | 187 | def test_code_without_source(): 188 | src = """def f(x):\n return x\nf(0)""" 189 | code = compile(src, "", "exec") 190 | events = [] 191 | with dowhen.when(code, "+1").do(lambda: events.append(0)): 192 | exec(code) 193 | assert events == [0] 194 | 195 | 196 | def test_every_line(): 197 | def f(x): 198 | x = 1 199 | x = 2 200 | x = 3 201 | return x 202 | 203 | lst = [] 204 | 205 | def cb(x): 206 | lst.append(x) 207 | 208 | dowhen.when(f).do(cb) 209 | f(0) 210 | assert lst == [0, 1, 2, 3] 211 | 212 | 213 | def test_multiple_lines(): 214 | def f(x): 215 | x = 1 216 | x = 2 217 | x = 3 218 | return x 219 | 220 | lst = [] 221 | 222 | def cb(x): 223 | lst.append(x) 224 | 225 | dowhen.when(f, "x = 1", "x = 3").do(cb) 226 | f(0) 227 | assert lst == [0, 2] 228 | dowhen.clear_all() 229 | 230 | 231 | def test_mix_events(): 232 | def f(x): 233 | for i in range(100): 234 | x += i 235 | return x 236 | 237 | write_back = [] 238 | dowhen.when(f, "", "return x").do(lambda: write_back.append(1)) 239 | f(0) 240 | assert write_back == [1, 1] 241 | 242 | 243 | def test_global_events(): 244 | def f(x): 245 | x += 1 246 | return x 247 | 248 | events = [] 249 | 250 | def f_callback(_frame): 251 | if _frame.f_code.co_name == "f": 252 | events.append(0) 253 | 254 | with dowhen.when(None, "").do(f_callback): 255 | f(0) 256 | 257 | with dowhen.when(None, "").do(f_callback): 258 | f(0) 259 | 260 | with dowhen.when(None, "return").do(f_callback): 261 | f(0) 262 | 263 | assert events == [0, 0, 0] 264 | 265 | with pytest.raises(ValueError): 266 | dowhen.when(None, "+1") 267 | 268 | 269 | def test_goto(): 270 | def f(): 271 | x = 0 272 | if x == 0: 273 | assert False 274 | x = 1 275 | return x 276 | 277 | with dowhen.when(f, "assert False").goto("x = 1"): 278 | assert f() == 1 279 | 280 | with dowhen.when(f, "assert False").do("x = 2").goto("-1"): 281 | assert f() == 1 282 | 283 | 284 | def test_condition(): 285 | def f(x): 286 | return x 287 | 288 | dowhen.when(f, "return x", condition="x == 0").do("x = 1") 289 | 290 | assert f(0) == 1 291 | assert f(2) == 2 292 | 293 | dowhen.clear_all() 294 | 295 | dowhen.when(f, "return x", condition=lambda x: x == 0).do("x = 1") 296 | assert f(0) == 1 297 | assert f(2) == 2 298 | 299 | dowhen.clear_all() 300 | 301 | with pytest.raises(ValueError): 302 | dowhen.when(f, "return x", condition="x ==") 303 | 304 | with pytest.raises(TypeError): 305 | dowhen.when(f, "return x", condition=1.5) 306 | 307 | 308 | def test_source_hash(): 309 | def f(x): 310 | return x 311 | 312 | source_hash = dowhen.get_source_hash(f) 313 | 314 | dowhen.when(f, "return x", source_hash=source_hash) 315 | 316 | with pytest.raises(ValueError): 317 | dowhen.when(f, "return x", source_hash=source_hash + "1") 318 | 319 | with pytest.raises(TypeError): 320 | dowhen.when(f, "return x", source_hash=123) 321 | 322 | 323 | def test_should_fire(): 324 | def f(x): 325 | return x 326 | 327 | frame = sys._getframe() 328 | 329 | for trigger in ( 330 | dowhen.when(f, "return x", condition="x == 0"), 331 | dowhen.when(f, "return x", condition=lambda x: x == 0), 332 | ): 333 | x = 0 334 | assert trigger.should_fire(frame) is True 335 | x = 1 336 | assert trigger.should_fire(frame) is False 337 | del x 338 | assert trigger.should_fire(frame) is False 339 | 340 | 341 | def test_has_event(): 342 | def f(x): 343 | x += 1 344 | return x 345 | 346 | frame = sys._getframe() 347 | trigger = dowhen.when(None, "assert") 348 | assert trigger.has_event(frame) is True 349 | 350 | trigger = dowhen.when(None, "trigger") 351 | assert trigger.has_event(frame) is False 352 | 353 | trigger = dowhen.when(f, "return x") 354 | assert trigger.has_event(frame) is True 355 | 356 | 357 | def test_invalid_type(): 358 | def f(): 359 | pass 360 | 361 | with pytest.raises(TypeError): 362 | dowhen.when(123, 1) 363 | 364 | with pytest.raises(TypeError): 365 | dowhen.when(f, 1.5) 366 | 367 | with pytest.raises(ValueError): 368 | dowhen.when(None, "return", source_hash="12345678") 369 | 370 | 371 | def test_invalid_line_number(): 372 | def f(): 373 | pass 374 | 375 | with pytest.raises(ValueError): 376 | dowhen.when(f, 1000) 377 | 378 | with pytest.raises(ValueError): 379 | dowhen.when(f, "+1000") 380 | 381 | code = compile("pass", "", "exec") 382 | with pytest.raises(ValueError): 383 | dowhen.when(code, "return") 384 | -------------------------------------------------------------------------------- /src/dowhen/trigger.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 2 | # For details: https://github.com/gaogaotiantian/dowhen/blob/master/NOTICE 3 | 4 | 5 | from __future__ import annotations 6 | 7 | import inspect 8 | import sys 9 | from collections.abc import Callable 10 | from types import CodeType, FrameType, FunctionType, MethodType, ModuleType 11 | from typing import TYPE_CHECKING, Any, Literal 12 | 13 | from .types import IdentifierType 14 | from .util import call_in_frame, get_line_numbers, get_source_hash, getrealsourcelines 15 | 16 | if TYPE_CHECKING: # pragma: no cover 17 | from .callback import Callback 18 | from .handler import EventHandler 19 | 20 | 21 | DISABLE = sys.monitoring.DISABLE 22 | 23 | 24 | class _Event: 25 | def __init__( 26 | self, 27 | code: CodeType | None, 28 | event_type: Literal["line", "start", "return"], 29 | event_data: dict | None, 30 | ): 31 | self.code = code 32 | self.event_type = event_type 33 | self.event_data = event_data or {} 34 | 35 | 36 | class Trigger: 37 | def __init__( 38 | self, 39 | events: list[_Event], 40 | condition: str | Callable[..., bool] | None = None, 41 | is_global: bool = False, 42 | ): 43 | self.events = events 44 | self.condition = condition 45 | self.is_global = is_global 46 | 47 | @classmethod 48 | def _get_code_from_entity( 49 | cls, entity: CodeType | FunctionType | MethodType | ModuleType | type | None 50 | ) -> list[CodeType] | list[None]: 51 | """ 52 | Get code objects from the given entity. 53 | """ 54 | code_objects: list[CodeType] = [] 55 | 56 | entity_list = [] 57 | 58 | if entity is None: 59 | return [None] 60 | 61 | if inspect.ismodule(entity) or inspect.isclass(entity): 62 | for _, obj in inspect.getmembers_static( 63 | entity, lambda o: isinstance(o, (FunctionType, MethodType, CodeType)) 64 | ): 65 | entity_list.append(obj) 66 | else: 67 | entity_list.append(entity) 68 | 69 | for entity in entity_list: 70 | if inspect.isfunction(entity) or inspect.ismethod(entity): 71 | entity = inspect.unwrap(entity) 72 | if inspect.isfunction(entity) or inspect.ismethod(entity): 73 | code_objects.append(entity.__code__) 74 | else: # pragma: no cover 75 | raise TypeError( 76 | f"Expected a function or method, got {type(entity)}" 77 | ) 78 | elif inspect.iscode(entity): 79 | code_objects.append(entity) 80 | else: 81 | raise TypeError(f"Unknown entity type: {type(entity)}") 82 | 83 | return code_objects 84 | 85 | @classmethod 86 | def unify_identifiers( 87 | cls, 88 | entity: CodeType | FunctionType | MethodType | ModuleType | type | None, 89 | *identifiers: IdentifierType | tuple[IdentifierType, ...], 90 | ) -> tuple[IdentifierType | tuple[IdentifierType, ...], ...]: 91 | """Unify identifiers by resolving relative line numbers.""" 92 | 93 | def unify_identifier( 94 | entity: CodeType | FunctionType | MethodType | ModuleType | type | None, 95 | identifier: IdentifierType, 96 | ) -> IdentifierType: 97 | if ( 98 | isinstance(identifier, str) 99 | and identifier.startswith("+") 100 | and identifier[1:].isdigit() 101 | ): 102 | if entity is None: 103 | raise ValueError( 104 | "Cannot use relative line numbers with a None entity." 105 | ) 106 | elif isinstance(entity, ModuleType): 107 | return int(identifier) 108 | else: 109 | _, start_line = getrealsourcelines(entity) 110 | return start_line + int(identifier) 111 | return identifier 112 | 113 | unified_identifiers: list[IdentifierType | tuple[IdentifierType, ...]] = [] 114 | for identifier in identifiers: 115 | if isinstance(identifier, tuple): 116 | unified_identifiers.append( 117 | tuple(unify_identifier(entity, ident) for ident in identifier) 118 | ) 119 | else: 120 | unified_identifiers.append(unify_identifier(entity, identifier)) 121 | 122 | return tuple(unified_identifiers) 123 | 124 | @classmethod 125 | def when( 126 | cls, 127 | entity: CodeType | FunctionType | MethodType | ModuleType | type | None, 128 | *identifiers: IdentifierType | tuple[IdentifierType, ...], 129 | condition: str | Callable[..., bool | Any] | None = None, 130 | source_hash: str | None = None, 131 | ): 132 | if isinstance(condition, str): 133 | try: 134 | compile(condition, "", "eval") 135 | except SyntaxError: 136 | raise ValueError(f"Invalid condition expression: {condition}") 137 | elif condition is not None and not callable(condition): 138 | raise TypeError( 139 | f"Condition must be a string or callable, got {type(condition)}" 140 | ) 141 | 142 | if source_hash is not None: 143 | if not isinstance(source_hash, str): 144 | raise TypeError( 145 | f"source_hash must be a string, got {type(source_hash)}" 146 | ) 147 | if entity is None: 148 | raise ValueError("source_hash cannot be used with a None entity.") 149 | if get_source_hash(entity) != source_hash: 150 | raise ValueError( 151 | "The source hash does not match the entity's source code." 152 | ) 153 | 154 | events = [] 155 | 156 | code_objects = cls._get_code_from_entity(entity) 157 | 158 | if not identifiers: 159 | for code in code_objects: 160 | events.append(_Event(code, "line", {"line_number": None})) 161 | else: 162 | identifiers = cls.unify_identifiers(entity, *identifiers) 163 | for identifier in identifiers: 164 | if identifier == "": 165 | for code in code_objects: 166 | events.append(_Event(code, "start", None)) 167 | elif identifier == "": 168 | for code in code_objects: 169 | events.append(_Event(code, "return", None)) 170 | else: 171 | for code in code_objects: 172 | if code is None: 173 | # Global event, entity is None 174 | events.append( 175 | _Event( 176 | None, 177 | "line", 178 | {"line_number": None, "identifier": identifier}, 179 | ) 180 | ) 181 | else: 182 | line_numbers = get_line_numbers(code, identifier) 183 | for c, numbers in line_numbers.items(): 184 | for number in numbers: 185 | events.append( 186 | _Event(c, "line", {"line_number": number}) 187 | ) 188 | 189 | if not events: 190 | raise ValueError( 191 | "Could not set any event based on the entity and identifiers." 192 | ) 193 | 194 | return cls(events, condition=condition, is_global=entity is None) 195 | 196 | def bp(self) -> "EventHandler": 197 | from .callback import Callback 198 | 199 | return self._submit_callback(Callback.bp()) 200 | 201 | def do(self, func: str | Callable) -> "EventHandler": 202 | from .callback import Callback 203 | 204 | return self._submit_callback(Callback.do(func)) 205 | 206 | def goto(self, target: str | int) -> "EventHandler": 207 | from .callback import Callback 208 | 209 | return self._submit_callback(Callback.goto(target)) 210 | 211 | def has_event(self, frame: FrameType) -> bool | Any: 212 | if self.is_global and self.events[0].event_type == "line": 213 | identifier = self.events[0].event_data.get("identifier") 214 | assert isinstance(identifier, (str, int, tuple)) 215 | line_numbers = get_line_numbers(frame.f_code, identifier).get( 216 | frame.f_code, None 217 | ) 218 | if line_numbers is None: 219 | return False 220 | elif frame.f_lineno not in line_numbers: 221 | return False 222 | return True 223 | 224 | def should_fire(self, frame: FrameType) -> bool | Any: 225 | if self.condition is None: 226 | return True 227 | try: 228 | if isinstance(self.condition, str): 229 | return eval(self.condition, frame.f_globals, frame.f_locals) 230 | elif callable(self.condition): 231 | return call_in_frame(self.condition, frame) 232 | except Exception: 233 | return False 234 | 235 | assert False, "Unknown condition type" # pragma: no cover 236 | 237 | def _submit_callback(self, callback: "Callback") -> "EventHandler": 238 | from .handler import EventHandler 239 | 240 | handler = EventHandler(self, callback) 241 | handler.submit() 242 | 243 | return handler 244 | 245 | 246 | when = Trigger.when 247 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------