carl.hiass
carl.hiass

Reputation: 1764

Modify function's code in wrapper function

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?

Upvotes: 1

Views: 268

Answers (1)

user5386938
user5386938

Reputation:

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')

Upvotes: 1

Related Questions