My code:
fh = None
if args.optional_input_file_path is not None:
fh = open(args.optional_input_file_path)
my_function(foo, bar, fh)
if args.optional_input_file_path is not None:
fh.close()
I don't like how I need to write if args.optional_input_file is not None: twice.
Moving the conditional logic inside my_function also isn't ideal because I'm intentionally passing in IO objects to the function instead of file paths to make it easier to test.
Is there a cleaner way to achieve the same thing?
I want to be able to write my_function(foo, bar, fh) exactly once, and have fh be either an IO object or None, depending on the value of args.optional_input_file_path.