I want to write a function that accepts either a path as a string or a file object. So far I have:
def awesome_parse(path_or_file):
if isinstance(path_or_file, basestring):
f = open(path_or_file, 'rb')
else:
f = path_or_file
with f as f:
return do_stuff(f)
where do_stuff takes an open file object.
Is there a better way to do this? Does with f as f: have any repercussions?
Thanks!
The odd thing about your code is that if it is passed an open file, it will close it. This isn’t good. Whatever code opened the file should be responsible for closing it. This makes the function a bit more complex though:
You can abstract this away by writing your own context manager: