1

Is it possible to replace the actual code of a function by the function that wraps it? Here I'm trying to replace print statements with log statements:

import logging
import re

def print_to_log(func):
    def wrapper_print_to_log(*args, **kwargs):
        # how to do something like this?
        re.sub(r'print\s*\(',  'logging.info(', **function_code**)
        return func(*args, **wargs)
    return wrapper_print_to_log


@print_to_log
def greet(name='bob'):
    print ("Hello, %s" % name)
    print ("How are you sir?")

Is it possible to replace the code or do something similar to the above?

3
  • Is your goal here to have flexibility in logging, or are you really interested in dynamically rewriting code, and the code here is just an example? Commented Oct 28, 2019 at 2:42
  • @bjudson actually to rewrite the code -- logging is just an example. Commented Oct 28, 2019 at 2:43
  • have you explored monkey patching (eg the unittest.mock module)? Commented Oct 29, 2019 at 17:11

1 Answer 1

1

Perhaps you can temporarily replace sys.stdout?

import logging
import re
import sys
import io

def print_to_log(func):
    def wrapper_print_to_log(*args, **kwargs):
        stdout = sys.stdout
        b = io.StringIO()
        sys.stdout = b
        try:
            return func(*args, **kwargs)
        finally:
            sys.stdout = stdout
            print(b.getvalue().upper())

    return wrapper_print_to_log

@print_to_log
def greet(name='bob'):
    print("Hello, %s" % name)
    print("How are you sir?")

greet('justin')
Sign up to request clarification or add additional context in comments.

3 Comments

Apparently, on python 3, you can also replace the built-in print function with any other function: print = logging.info. Just use the finally block to restore the print back to the built-in function afterwards.
Odd... replacing print seems to only work from the interactive prompt.
Ahh... but one can assign to builtins.print after import builtins. But now I am curious as to whether what the OP wants is actually possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.