I've seen lots of times something like:
def parse(text):
if hasattr(text, 'read'):
text = text.read()
# Parse the text here...
but if I pass an instance of the following class, it will surely fail:
class X(object):
def __init__(self):
self.read = 10
My question is: What is the most pythonic way of handling it?
I've been thinking about two main ways:
if hasattr(text, 'read') and callable(text.read):
text = text.read()
and
try:
text = text.read()
except ...