armory icon indicating copy to clipboard operation
armory copied to clipboard

Add method hooking to probe functionality

Open davidslater opened this issue 2 years ago • 1 comments

This would make it much easier to grab values from various functions, such as in https://github.com/twosixlabs/armory/issues/1462, where we could simply hook this method: https://github.com/twosixlabs/armory/blob/388edde7d85f96dac6a96c13854b955f1bb5c3c3/armory/art_experimental/attacks/carla_obj_det_patch.py#L262

Something like our eval patch (but hooking instead of replacing):

import types                                                                              
                                                                                          
                                                                                          
def patch_method(obj):                                                                    
    """                                                                                   
    Patch method for given class or object instance.                                      
                                                                                          
    If a class is passed in, patches ALL instances of class.                              
    If an object is passed in, only patches the given instance.                           
    """                                                                                   
                                                                                          
    def decorator(method):                                                                
        if not isinstance(obj, object):                                                   
            raise ValueError(f"patch_method input {obj} is not a class or object")        
        if isinstance(obj, type):                                                         
            cls = obj                                                                     
            setattr(cls, method.__name__, method)                                         
        else:                                                                             
            setattr(obj, method.__name__, types.MethodType(method, obj))                  
        return method                                                                     
                                                                                          
    return decorator

Or something similar to: https://stackoverflow.com/questions/35758323/hook-python-module-function

This could involve pre-hooking (hooking the inputs to the method) and post-hooking (hooking the return value).

davidslater avatar May 13 '22 22:05 davidslater

see additional issue here

christopherwoodall avatar Dec 05 '22 19:12 christopherwoodall