0

I'm trying to build a piece of code that prints out whatever is written on the console, but still executing whatever a person writes on it. For example:

I have this function:

def create_set():
    return []

Whenever someone puts this: c = create_set() in the console. I want the program to create the set AND print out the string "c = create_set()"

How can I do that? Some help would be much aprecciated

Daniel
  • 3
  • 6
  • What do you mean by "the console"? Are you trying to modify the REPL? – Sneftel Dec 03 '17 at 23:00
  • For example, when you're in a Python console, and you open a python file, imagine you have functions on that file, and when you call those functions, I want to printout that call as a string, and still allow the program to execute that call. P.S. I could just put a `print("function name")` on each function but that's not what I want the program to do. – Daniel Dec 03 '17 at 23:03
  • @Daniel: are you perhaps looking for the [`pdb`](https://docs.python.org/3/library/pdb.html) tool? – Daniel Pryden Dec 03 '17 at 23:44
  • @DanielPryden not exactly, I just want a piece of code that whenever some call is made, it prints out exactly what was typed and still executes whatever it was supposed to. – Daniel Dec 03 '17 at 23:57
  • @Daniel: If you execute with a debugger, you can set breakpoint(s) on the code of interest and dump any local variables. I'm pretty sure that will solve your problem and doesn't require you to write any code at all. – Daniel Pryden Dec 04 '17 at 00:03
  • @DanielPryden yes I know that but I want it to be automatic. When I type something in the console, I want it to be printed immediately after or before it executes. One of those would be fine – Daniel Dec 04 '17 at 00:18

1 Answers1

0

You could write a decorator that does this, but you'll have to add this to every method per hand or do some magic in the module __dict__ (which I don't recommend). This works (I tested it) in python 3.6, if you use the commented version it works in python 2.7. They changed the stack-signature from 2.X to 3.X.

from inspect import stack
from functools import wraps

def printer(f):
     @wraps(f)
     def wrapped(*args, **kwargs):
         call_info = stack()[1].code_context  # In Python 2.7.X, replace with stack()[1][4]
         # Use index 1 because 0 is always this wrapper function
         for context in call_info:
             print(context.strip())

         return f(*args, **kwargs)
     return wrapped

Use it like this:

@printer
def test():
    return 5

x = test()

This will print x = test()to stdout. If you want this for debugging, that is totally fine, but if this is something your code relies on in production I would not recommend it, because it will kill your performance, see for example here.

RunOrVeith
  • 4,487
  • 4
  • 32
  • 50