In my code, I have a load_dataset function that reads a text file and does some processing. Recently I thought about adding support to file-like objects, and I wondered over the best approach to this. Currently I have two implementations in mind:
First, type checking:
if isinstance(inputelement, basestring):
# open file, processing etc
# or
# elif hasattr(inputelement, "read"):
elif isinstance(inputelement, file):
# Do something else
Alternatively, two different arguments:
def load_dataset(filename=None, stream=None):
if filename is not None and stream is None:
# open file etc
elif stream is not None and filename is None:
# do something else
Both solutions however don’t convince me too much, especially the second as I see way too many pitfalls.
What is the cleanest (and most Pythonic) way to accept a file-like object or string to a function that does text reading?
Don’t accept both files and strings. If you’re going to accept file-like objects, then it means you won’t check the type, just call the required methods on the actual parameter (
read,write, etc.). If you’re going to accept strings, then you’re going to end upopen-ing files, which means you won’t be able to mock the parameters. So I’d say accept files, let the caller pass you a file-like object, and don’t check the type.