File names and file objects [was Re: My Python annoyances]
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sat May 5 13:06:35 EDT 2007
On Fri, 04 May 2007 07:55:25 -0700, Alex Martelli wrote:
>> What about the case where I have an array of objects that represent some
>> particular binary file format. If the object is a file, then I want to
>> copy its contents. If the object is a string, then I want to write the
>> string. And so forth.
>
> "Type-switching" in this way is a rather dubious practice in any
> language (it can't respect the "open-closed" principle).
What do people think about functions that accept either a file name or a
file object?
def handle_file(obj):
if type(obj) == str:
need_to_close = True
obj = file(obj, 'r')
else:
need_to_close = False
do_something_with(obj.read())
if need_to_close:
data.close()
Good idea? Bad idea? Just a matter of personal preference?
--
Steven.
More information about the Python-list
mailing list