Skip to content

Code decompilation #69

@haesleinhuepf

Description

@haesleinhuepf

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions