Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic Method for handling None and with Statement

I want to call a function and either pass a File-like object or None. But, using the File-like object, I want to handle its resource allocation properly with the with statement. But, Python will raise an exception (AttributeError) if my with expression evaluates to None. I suppose I could write the full try/except block longhand, but does a concise Pythonic way of handling this situation exist?

def call_method(o1, o2, f_in):
    if f_in:
        pass # Do something optional if we have the f_in value

# ...

with (open(path, 'rb') if flag else None) as f_in:
    call_method(opt1, opt2, f_in)
    # Throws an AttributeError, since None does not have __exit__
like image 614
palswim Avatar asked Mar 05 '26 10:03

palswim


1 Answers

If you want a context manager that does nothing, that's contextlib.nullcontext(), not None:

import contextlib

with (open(whatever) if flag else contextlib.nullcontext()) as f:
    do_whatever()

f will be None in the not flag case - the thing that gets assigned to f is __enter__'s return value, which doesn't have to be the context manager itself.

like image 173
user2357112 supports Monica Avatar answered Mar 07 '26 22:03

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!