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
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:
def awesome_parse(path_or_file):
if isinstance(path_or_file, basestring):
f = file_to_close = open(path_or_file, 'rb')
else:
f = path_or_file
file_to_close = None
try:
return do_stuff(f)
finally:
if file_to_close:
file_to_close.close()
You can abstract this away by writing your own context manager:
@contextlib.contextmanager
def awesome_open(path_or_file):
if isinstance(path_or_file, basestring):
f = file_to_close = open(path_or_file, 'rb')
else:
f = path_or_file
file_to_close = None
try:
yield f
finally:
if file_to_close:
file_to_close.close()
def awesome_parse(path_or_file):
with awesome_open(path_or_file) as f:
return do_stuff(f)