#๐Ÿ”’ convert a function into a yield each time it evaluates another function

13 messages ยท Page 1 of 1 (latest)

lament bear
#

This might just be too crazy to be possible but I figured it might be worth a try asking.
Lets say I have two functions, where solver evaluates objective arbitrary amount of times, and can be taken from various libraries (so I can't edit it).

def objective(x): return x**2
def solver(objective):
  x = 100
  for i in range(10):
    # do stuff with x
    value = objective(x)

is there any way to convert an arbitrary function like solver into a generator which yields each time it evaluates objective? This is what I want to convert it to:

def objective(x): return x**2
def solver(objective):
  x = 100
  for i in range(10):
    # do stuff with x
    value = objective(x)
    yield
strong umbraBOT
#

@lament bear

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

frank elbow
# lament bear This might just be too crazy to be possible but I figured it might be worth a tr...

it already works?

>>> def objective(x):
...   print(f'received {x}')
...
>>>
>>> def solver(objective):
...   x = 100
...   for i in range(10):
...     # do stuff with x
...     value = objective(x)
...     yield
...
>>> solver(objective)
<generator object solver at 0x000001A01E87C9E0>
>>> for _ in solver(objective):
...   continue
...
received 100
received 100
received 100
received 100
received 100
received 100
received 100
received 100
received 100
received 100
>>>
#

like whats the problem

lament bear
frank elbow
#

but otherwise, it did run 10 times and 10 times only, so seems to be working

lament bear
frank elbow
#

then I don't really think so

steady bane
#

Theoretically you could fake a generator-like behaviour by running solver in another thread, and having objective block each time it's called until it gets a signal to proceed.

strong umbraBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.