Suppose I have a function that prints five lines of text. I want to add prefix like 'asdf ' and suffix ' qwerty' for every line it prints on console. How to do this with decorator in python. Output generated can come from logging module or print statements in function that we want to decorate.
Asked
Active
Viewed 1,855 times
-2
-
if you go through a good decorator tutorial or even from the python docs itself, this question will come by intuition to you – Ishan Srivastava Jun 09 '18 at 10:16
-
2If you know how to implement a decorator all that's left to know in order to solve your problem can be found [here](https://stackoverflow.com/questions/22822267/python-capture-print-output-of-another-module). – timgeb Jun 09 '18 at 10:19
-
1I'd probably replace stdout's `write` method instead of replacing the entire stdout stream with StringIO. You could, and it would work fine, but you'd be delaying seeing *any* output until the function completed in its entirety. Replacing `write`, on the other hand, lets you see output as soon as the wrapped function emits it. – jedwards Jun 09 '18 at 11:18
2 Answers
1
def my_decorator(func):
def wrapping_func(strlist):
for index, i in enumerate(strlist):
strlist[index] = 'wubalubadubdub' + i
return func(strlist)
return wrapping_func
@my_decorator
def fun(str_list):
for i in str_list:
print(i)
if __name__ == "__main__":
fun(['a', 'b'])
Duplicate question but anyways the above code is what you are looking for, the wrapping_func
merely modifies the arguments that are given to the function i.e. adds a prefix and returns while calling the original function with the modified arguments with the my_decorator
function just returning the wrapping_func
.

Ishan Srivastava
- 1,129
- 1
- 11
- 29
-
I think you have not understood question or you have not paid attention. You are modifying input to function which just prints given strings as input. As I mentioned in question output to console can come from logging also – Raghu Ram Jun 09 '18 at 16:45
-
@RaghuRam you need to explain what you want more precisely in the question. If you follow the eg.. that I gave, the things you are asking for have nothing to do with decorators, and can be asked in different questions for eg.. giving output to console etc – Ishan Srivastava Jun 09 '18 at 23:56
1
Here is one sample code to demonstrate this problem. Print statements output is customized, but not statements from logging module.
from contextlib import contextmanager
@contextmanager
def no_stdout():
import sys
old_stdout = sys.stdout
class CustomPrint():
def __init__(self, stdout):
self.old_stdout = stdout
def write(self, text):
if len(text.rstrip()):
self.old_stdout.write('custom Print--->'+ text)
sys.stdout = CustomPrint(old_stdout)
try:
yield
finally:
sys.stdout = old_stdout
def fun():
import logging
logger = logging.getLogger("tester")
logger.info("Test line from function")
print "BEFORE"
with no_stdout():
print "WHY HELLO!\n"
print "DING DONG!\n"
import logging
logger = logging.getLogger("test")
logger.info(" Hello world")
fun()
print "AFTER"
output:
BEFORE
custom Print--->WHY HELLO!
custom Print--->DING DONG!
2018-06-11 15:52:30,088 (42092) test INFO - Hello world
2018-06-11 15:52:30,092 (42092) tester INFO - Test line from function
AFTER
we see that logging modules output is not customized.

bujji jajala
- 11
- 1