Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用条件';与';Python中的语句_Python_Python 3.x - Fatal编程技术网

使用条件';与';Python中的语句

使用条件';与';Python中的语句,python,python-3.x,Python,Python 3.x,我正在尝试用Python处理一个大字节流。据我所知,使用“with”语句可以防止将临时数据加载到内存中,这对我来说是一个优势 我的问题是我有两个选择源数据流的选项:原始数据流或源路径 if sourceRef: with open(sourceRef, 'rb') as ds: dstreams['master'] = self._generateMasterFile(ds) else: with self._validate(source) as ds:

我正在尝试用Python处理一个大字节流。据我所知,使用“with”语句可以防止将临时数据加载到内存中,这对我来说是一个优势

我的问题是我有两个选择源数据流的选项:原始数据流或源路径

if sourceRef:
    with open(sourceRef, 'rb') as ds:
        dstreams['master'] = self._generateMasterFile(ds)
else:
    with self._validate(source) as ds:
        dstreams['master'] = self._generateMasterFile(ds)
这可以正常工作,但我有更复杂的场景,其中“with”语句后面的操作更复杂,我不想重复它们

有没有办法压缩这两个选项

谢谢,

通用汽车


编辑:我正在使用Python3。

只要这两个东西分别使用
工作,您就可以按如下方式内联
if
语句:

with (open(sourceRef, 'rb') if sourceRef else self._validate(source)) as ds:
    dstreams['master'] = self._generateMasterFile(ds)

最干净的解决方案可能是事先定义
ds

if sourceRef:
    ds = open(sourceRef, 'rb')
else:
    ds = self._validate(source)

with ds:
    dstreams['master'] = self._generateMasterFile(ds)

当您有两个以上可能的
ds
值时,这种方法也能以干净的方式工作(您只需事先扩展检查以确定
ds
的值)。

可以创建一个方法并将返回值传递给with,以避免编写大量with语句“使用'with'语句可以防止将临时数据加载到内存中,”听起来不像我所知道的'with'语句要做的事情:它的主要目的是在'with'块完成时自动执行操作(例如,对于文件,退出该块会关闭文件)。由于某些原因,这在Python 3中不起作用:
>>var=b如果b或者a>>>使用var:…打印(var)…回溯(最近一次调用):文件““,第1行,在AttributeError:\uuuu exit\uuuu
@gattumarrudu请参阅上面hlt的评论,这与Python 3无关。但是,当代码在
if
块和
with
块之间抛出异常时,会发生什么情况?这个代码看起来很脆弱。(当然,你的情况并不比没有使用
with
更糟。)也许更好的办法是将
if
块包装到函数中?@BrandonHumpert:可能,似乎在打开资源和进入with块之间总有一段时间。因此,即使在使用get_ds(sourceRef)编写
时:
我们也可能会在两者之间出现异常。我真正关心的是,如果有人回去维护您在这里编写的代码,其他代码插入
if
块和
with
块之间的空间的概率不是零。这不是因为Python 3,而是因为
with
中使用的每个对象都必须定义一个
\uuuuuuu
方法(您在该注释中给出的示例中的对象没有)