Skip to content
Advertisement

Is it possible to have an optional with/as statement in python?

Instead of this:

JavaScript

it’s better to use this:

JavaScript

What if I have something like this?

JavaScript

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?

Advertisement

Answer

If you were to just write it like this:

JavaScript

(file is a builtin btw )

Update

Here is a funky way to do an on-the-fly context with an optional None that won’t crash:

JavaScript

It creates a context that returns a None value. The with will either produce FILE as a file object, or a None type. But the None type will have a proper __exit__

Update

If you are using Python 3.7 or higher, then you can declare the null context manager for stand-in purposes in a much simpler way:

JavaScript

You can read more about these here:

https://docs.python.org/3.7/library/contextlib.html#contextlib.nullcontext

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement