Hacker News new | ask | show | jobs
by bhickey 746 days ago
> dynamically redefine functions even to violate lexical scoping

When would someone want to do this?

1 comments

Let's say you had a library function foo, which takes no arguments, does an expensive computation, and then prints a single result to the console. You need the function to instead return the value, so that you can do more computation on it. You could write a wrapper function that will call foo, but replace the print function with one that records the printed result.

For example:

  def foo():
      print('usually this value is inaccessible from "python land"')
  def extract_printed_values(bar):
      global print
      old_print, returnv = print, None
      def new_print(x):
          nonlocal returnv
          old_print(returnv := x)
      print = new_print
      bar()
      print = old_print
      return returnv
  fooval = extract_printed_values(foo)
fooval will then be equal to whatever value foo printed to the console, otherwise foo will behave exactly the same as normal (assuming it only printed a single value), and print will even behave normally afterwards