How to get/set local variables of a function (from outside) in Python?

前端 未结 5 1367
误落风尘
误落风尘 2020-11-28 10:08

If I have a function (in Python 2.5.2) like:

def sample_func():
    a = 78
    b = range(5)
    #c = a + b[2] - x

My questions are:

5条回答
  •  心在旅途
    2020-11-28 10:48

    No. A function that isn't being run doesn't have locals; it's just a function. Asking how to modify a function's locals when it's not running is like asking how to modify a program's heap when it's not running.

    You can modify constants, though, if you really want to.

    def func():
        a = 10
        print a
    
    co = func.func_code
    modified_consts = list(co.co_consts)
    for idx, val in enumerate(modified_consts):
        if modified_consts[idx] == 10: modified_consts[idx] = 15
    
    modified_consts = tuple(modified_consts)
    
    import types
    modified_code = types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, modified_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab)
    modified_func = types.FunctionType(modified_code, func.func_globals)
    # 15:
    modified_func()
    

    It's a hack, because there's no way to know which constant in co.co_consts is which; this uses a sentinel value to figure it out. Depending on whether you can constrain your use cases enough, that might be enough.

提交回复
热议问题