-1

In an existing code-base, sometimes I would like to change fixed values into stochastic values. As an oversimplified example:

def existing_function(v):
   return v + 1

# Normal usage:
v = 1
existing_function(v)
2
existing_function(v)
2

# 'Stochastic' usage
v = aStochasticVariable()

class X:
   def __init__(self, v):
      self. v = v

   def existing_function(self):
      return self.v

o= X(v)

o.existing_function()
5
o.existing_function()
9

I was thinking of sub classing for example the builtin (int or float) but I don't know how to get the value of (eg) the int (what is the name of the variable that holds the value of the int?). Another options would be to use the dunder call as a property:

class StochasticInt(int):
   @property
   def __call__(self):
      return random.randint()

But this does not work. I also can't find a solution in the known libs, so ... anybody any ideas, thoughts?

Kind regards, vA

Van Alles
  • 11
  • 3

1 Answers1

0

The __call__ method is called when the instance is called, so you were very close but you need to call the v this way : v().
Also, randint need two argument a and b such that a <= N <= b.
Here for the example, we setup a=1 and b=10 :

class StochasticVariable(int):
   def __call__(self):
      return random.randint(0, 10)

Then we can call it this way :

>>> v = StochasticVariable()
>>> v()
5
>>> existing_function(v())
8
tlentali
  • 3,407
  • 2
  • 14
  • 21
  • Hi tientali, thanks for the effort. It's close but no sigar (yet). The issue is that with this solution, within the function you'll still have an int. My bad, as the example usage was not clear enough. Therefor I adapted the example to get more clear what I'm thinking of: the variable should be stochastic within a function or as in the example: within an object. – Van Alles Oct 15 '21 at 19:14
  • Few answers. Maybe it helps if I explain the usage: I run a simulation in which __init__'s with tens of parameters. The simulation does hundreds runs. For testing, but also for simulation, I want to control when the parameters are to be fixed and when to be stochastic. With aStochasticVariable as proposed this would be very easy, without changing the code but I don't find a pythonic way. I could replicate the int class but that would not be pythonic nor DRY. – Van Alles Oct 20 '21 at 11:31