0

In the example below, force should change the value of the parameter x of the double function. ValidateAndCast checks the given parameter and casts it. So in this case, after force returns, x should be 2, and thus the return value of double should be 4. Assume that all the altering is done in the force function.

How do I achieve this? I've looked into inspect so far and will continue studying.

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)

1 Answers1

0

This solution works for me.

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