diff --git a/docs/03_advanced_python/code_decompilation.ipynb b/docs/03_advanced_python/code_decompilation.ipynb new file mode 100644 index 000000000..f5f511485 --- /dev/null +++ b/docs/03_advanced_python/code_decompilation.ipynb @@ -0,0 +1,77 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Code Decompilation with a Decorator\n", + "\n", + "This notebook demonstrates how to use a Python decorator to inspect and decompile the code of a function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import dis\n", + "import uncompyle6\n", + "import io\n", + "\n", + "def inspect_and_decompile_function(func):\n", + " def wrapper(*args, **kwargs):\n", + " # Access the function's code object\n", + " code = func.__code__\n", + " \n", + " # Print some details about the function's code\n", + " print(f\"Function name: {func.__name__}\")\n", + " print(f\"Function arguments: {code.co_varnames}\")\n", + " print(f\"Function constants: {code.co_consts}\")\n", + " print(f\"Function bytecode:\")\n", + " dis.dis(func)\n", + " \n", + " # Decompile and print the source code\n", + " bytecode_stream = io.StringIO()\n", + " uncompyle6.deparse_code(code, out=bytecode_stream)\n", + " print(\"Decompiled source code:\")\n", + " print(bytecode_stream.getvalue())\n", + " \n", + " # Call the original function\n", + " return func(*args, **kwargs)\n", + " \n", + " return wrapper\n", + "\n", + "@inspect_and_decompile_function\n", + "def sample_function(a, b):\n", + " x = a + b\n", + " return x * 2\n", + "\n", + "# Example usage\n", + "result = sample_function(2, 3)\n", + "print(\"Result:\", result)\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.5" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/_toc.yml b/docs/_toc.yml index 73c440203..0d46b2cfd 100644 --- a/docs/_toc.yml +++ b/docs/_toc.yml @@ -275,6 +275,7 @@ parts: - file: 03_advanced_python/partial - file: 03_advanced_python/parallelization - file: 03_advanced_python/numba + - file: 03_advanced_python/decompilation_decorator - file: 15_gpu_acceleration/readme sections: @@ -429,4 +430,3 @@ parts: - file: 01_introduction/glossary - file: imprint -