BioImageAnalysisNotebooks icon indicating copy to clipboard operation
BioImageAnalysisNotebooks copied to clipboard

Code decompilation

Open haesleinhuepf opened this issue 1 year ago • 2 comments

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

haesleinhuepf avatar Aug 19 '24 16:08 haesleinhuepf

Come up with a new notebook that combines the code snippets above to make a decorator that prints out the code of a function before executing it

haesleinhuepf avatar Aug 19 '24 16:08 haesleinhuepf

git-bob solve

haesleinhuepf avatar Aug 19 '24 16:08 haesleinhuepf