“with suppress”在我的python3代码中不再工作了?

2024-09-25 00:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理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>
   <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>

我知道孩子们<attributes>并不总是满的,根据文档,这是不需要的

我已经成功地处理了所有这些记录(即使是不存在的记录),例如:

from contextlib import suppress

with suppress(AttributeError): tipoVinho = produtos.find('attributes/type').text
with suppress(AttributeError): paisVinho = produtos.find('attributes/country').text

因此,如果<attributes><type>不存在,它就跳过属性错误并继续

现在,出乎意料的是,每当我陷入一个缺少的属性时,我就会得到一个"name 'tipoVinho' is not defined"错误,就像with suppress子句不再执行任何操作一样

我还没有升级任何东西,它是几天前才开始的(注意,我有几个案例中缺少一些属性,所以这是很常见的)

我遗漏了什么吗


Tags: namebrapistring属性typewith记录
1条回答
网友
1楼 · 发布于 2024-09-25 00:26:19

当您抑制AttributeError时,赋值被取消。毕竟,右侧表达式(produtos.find().text)没有返回,根本没有。它甚至没有返回None!相反,它抛出了一个异常。这会导致tipoVinho未定义的情况

您将需要为异常发生时执行特殊的大小写,使contextlib.suppress不是正确的工具。相反,只需使用例外:

try:
    tipoVinho = produtos.find('attributes/type').text
except AttributeError:
    tipVinho = None

或者在可能失败的赋值之前将tipVinho设置为某个默认值。确保在每次循环迭代中重置它,如果这样做的话

相关问题 更多 >