是否有可能与python中的/ as语句可选? [英] Is it possible to have an optional with/as statement in python?
问题描述
FILE = open(f)
do_something(FILE)
FILE .close()
最好使用这个:
$ b $ (f)作为FILE:
do_something(FILE)
b
如果我有这样的事情,怎么办?
如果f不是无:
FILE = open(f)
else:
FILE = None
do_something(FILE)
如果FILE不是无:
FILE.close()
其中do_something也有一个if FILE is None子句,在这种情况下仍然有用 - >不要如果文件是无的只想跳过do_something。
是否有一个明智的方式将其转换为/作为形式?或者我只是想解决可选文件问题的方式不正确?
:
如果f不是None:
打开(f)作为FILE:
do_something(FILE )
else:
do_something(f)
(文件
是内置的btw)
更新这是一个很好的方式来做一个可选的None不会崩溃的即时上下文:
$ p $ from contextlib import contextmanager
none_context = contextmanager(lambda:iter([None]))()
#< contextlib.GeneratorContextManager at 0x1021a0110>
with(open(f)if f is not None none none_context)as FILE:
do_something(FILE)
它创建一个返回None值的上下文。带有的将产生FILE作为文件对象,或者产生一个None类型。但是None类型将有一个正确的
__ exit __
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?
If you were to just write it like this:
if f is not None:
with open(f) as FILE:
do_something(FILE)
else:
do_something(f)
(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:
from contextlib import contextmanager
none_context = contextmanager(lambda: iter([None]))()
# <contextlib.GeneratorContextManager at 0x1021a0110>
with (open(f) if f is not None else none_context) as FILE:
do_something(FILE)
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__
这篇关于是否有可能与python中的/ as语句可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!