Instead of this:
file = open(f)
do_something(file)
file.close()
it’s better to use this:
with open(f) as file:
do_something(file)
What if I have something like this?
if f is not None:
file = open(f)
else:
file = None
do_something(file)
if file is not None:
file.close()
Where do_something also has an if file is None clause, and still does something useful in that case – I don’t want to just skip do_something if file is None.
Is there a sensible way of converting this to with/as form? Or am I just trying to solve the optional file problem in a wrong way?
For Python 3.7 or higher, then you can use the
nullcontextfor stand-in purposes:For older Python versions, you can build one yourself on-the-fly with an optional
None:It creates a context that returns
None. Thewithwill either produceFILEas a file object, orNone. But theNonetype will have a proper__exit__Another solution would be to just write it like this:
(
fileis a builtin btw )