-
Notifications
You must be signed in to change notification settings - Fork 40
Description
It would be nice to demonstrate code decompilation with a function decorator.
Therefore, we should add a new notebook to the advanced python folder and also to the _toc.yml
In this notebook, we use approximately this code to implement a python decorator:
import dis
def inspect_function(func):
def wrapper(*args, **kwargs):
# Access the function's code object
code = func.__code__
# Print some details about the function's code
print(f"Function name: {func.__name__}")
print(f"Function arguments: {code.co_varnames}")
print(f"Function constants: {code.co_consts}")
print(f"Function bytecode:")
dis.dis(func)
# Call the original function
return func(*args, **kwargs)
return wrapper
@inspect_function
def sample_function(a, b):
x = a + b
return x * 2
# Example usage
result = sample_function(2, 3)
print("Result:", result)
And this code for printing the code of a given function:
import uncompyle6
import io
def decompile_function(func):
code = func.__code__
bytecode_stream = io.StringIO()
uncompyle6.deparse_code(code, out=bytecode_stream)
return bytecode_stream.getvalue()
# Example function
def sample_function(a, b):
x = a + b
return x * 2
# Decompile the function
source_code = decompile_function(sample_function)
print(source_code)
git-bob solve
github-actions
Metadata
Metadata
Assignees
Labels
No labels