首页 > 解决方案 > Python:如何从内部框架更改函数的参数值?

问题描述

在下面的例子中,force应该改变函数的参数xdoubleValidateAndCast检查给定的参数并将其强制转换。所以在这种情况下,在force返回之后,x应该是2,因此 的返回值double应该是 4。假设所有的改变都是在force函数中完成的。

我如何实现这一目标?inspect到目前为止,我已经研究并将继续学习。

def is_number(x):
  try:
    float(x)
    return True
  except:
    return False


def to_int(x):
  return int(float(x))

def double(x):
  force(x=ValidateAndCast(is_number, to_int))
  return x * 2

x = '2.54'
y = double(x)
print(y)

标签: python-3.xparametersargumentsframeinspect

解决方案


这个解决方案对我有用

import ctypes
import inspect


def change():

  def apply(frame):
    frame.f_locals['x'] = 4
    ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(frame), ctypes.c_int(1))

  calling_frame = inspect.stack()[1][0]
  apply(calling_frame)


def f(x):
  change()
  return x * 2


y = f(2)
print(y) # prints 8

推荐阅读