“with suppress”在我的Python 3代码中不再工作了?
我正在从一个API处理以下XML,该API有一组如下记录:“with suppress”在我的Python 3代码中不再工作了?,python,xml,Python,Xml,我正在从一个API处理以下XML,该API有一组如下记录: <br.com.wine.sfweb.rest.controller.api.products.ProductDTO> <sku>18683</sku> <imageUrl>/renderImage.image?imageName=produtos/18683-01.png</imageUrl> <id>89117</id> &l
<br.com.wine.sfweb.rest.controller.api.products.ProductDTO>
<sku>18683</sku>
<imageUrl>/renderImage.image?imageName=produtos/18683-01.png</imageUrl>
<id>89117</id>
<name>WineBox W Explorer Series</name>
<type>Vinho</type>
<attributes>
<marketingCampaign>estoque-limitado</marketingCampaign>
<country>Wine</country>
</attributes>
<ratings>
<averageRating>4.19</averageRating>
<numberOfRatings>21</numberOfRatings>
<histogram>
<entry>
<string>3.0</string>
<long>2</long>
</entry>
<entry>
<string>4.0</string>
<long>9</long>
</entry>
<entry>
<string>1.0</string>
<long>1</long>
</entry>
<entry>
<string>5.0</string>
<long>9</long>
</entry>
</histogram>
</ratings>
<rating>4.19</rating>
<numberOfRatings>21</numberOfRatings>
<available>true</available>
<listPrice>402.00</listPrice>
<salesPriceNonMember>402.00</salesPriceNonMember>
<salesPriceClubMember>341.70</salesPriceClubMember>
</br.com.wine.sfweb.rest.controller.api.products.ProductDTO>
因此,如果不存在,它将跳过属性错误并继续
现在,出乎意料的是,每当我遇到一个缺少的属性时,我都会得到一个名为“tipoVinho”的未定义错误,就像with suppress子句不再执行任何操作一样
我还没有升级任何东西,几天前才开始注意到我有一些属性丢失的情况,所以这很常见
我遗漏了什么吗?当您取消AttributeError时,作业将被取消。毕竟,右侧表达式produtos.find.text根本没有返回。它甚至没有返回一个!相反,它抛出了一个异常。这导致tipoVinho未定义的情况 当异常发生时,您需要使用特殊的大小写,使contextlib.suppress不是正确的工具。相反,只需使用异常:
try:
tipoVinho = produtos.find('attributes/type').text
except AttributeError:
tipVinho = None
或者在分配可能失败之前,将tipVinho设置为某个默认值。如果您这样做,请确保在每个循环迭代中重置它 那很有趣,谢谢!当我知道某个东西可能抛出AttributeError时,我确实看到自己在使用suppress,但是当我在抑制这个错误时,我不是在传递错误吗?也就是说,在这种情况下,当我调用tipoVinho=produtos.find但它没有找到属性时,它仍然会创建变量并将其设置为NULL,不是吗?这是我的理解,因为直到几天前,它还在使用相同的XML属性,但在我看来,初始化循环中的变量绝对是合理的。
try:
tipoVinho = produtos.find('attributes/type').text
except AttributeError:
tipVinho = None