Reputation: 317
I need to determine the output of a function if whether the function is printing a statement, or writing it out on a .txt file. Is there a way to do this in Python? I thought perhaps the hasattr('myfunction', 'str') might work, but it did not.
Examples of functions:
def x():
print('dog')
def y():
open("file.txt", "w").write("dog")
Upvotes: 0
Views: 58
Reputation: 1499
The print function can take more arguments than just whats going to be written:
print(*objects, sep=' ', end='\n', file=sys.stdout)
So you could write a wrapper function for print that also appends a boolean to a list that is true if the file was sys.stdout and false otherwise.
import sys
write_history = []
def write(*objects, sep=' ', end='\n', file=sys.stdout):
print(*objects, sep=sep, end=end, file=file)
write_history.append(file==sys.stdout)
Then just always use the write function, and when you want to test the output of a function, simply clear the write_history and call that function.
Upvotes: 1