Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions docs/03_advanced_python/code_decompilation.ipynb
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 1 addition & 1 deletion docs/_toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -429,4 +430,3 @@ parts:
- file: 01_introduction/glossary

- file: imprint