检查字典中项是否存在,这样做是不好的实践吗?

2 投票
7 回答
962 浏览
提问于 2025-04-17 18:09

这段代码是用Python写的,运行得很好:

# tests if class exists in the dictionary attrs
try:
    self.attrs['class']
# if it doesnt python will throw an exception
except KeyError:
    self.attrs['class'] = "someclass"
# else it is defined, so we concat someclass to previous value
else:
    self.attrs['class'] = "someclass %s" % self.attrs['class']

不过,我担心这样做不是个好习惯,因为如果Python更新了,改变了抛出的异常名称,代码可能就会失效。这算是坏习惯吗?有没有更好的做法呢?

7 个回答

2

@mgilson的回答很棒。这是另一种方法,可能更容易理解,并且解决了最后一个空格的问题:

if 'class' in self.attrs:
    self.attrs['class'] = "someclass %s" % self.attrs['class']
else:
    self.attrs['class'] = "someclass"
2

为什么要依赖异常处理,而不直接使用成员测试呢:

# tests if class exists in the dictionary attrs
if 'class' in self.attrs:
    self.attrs['class'] = "someclass %s" % self.attrs['class']
else:
    self.attrs['class'] = "someclass"

或者至少,可以去掉那个没有实际作用的try:

# tests if class exists in the dictionary attrs
try:
    self.attrs['class'] = "someclass %s" % self.attrs['class']
except KeyError:
    self.attrs['class'] = "someclass"
4

你那里的查找次数比需要的多很多……在这种情况下,你可以试试这样做:

self.attrs['class'] = 'someclass %s' % self.attrs.get('class','')

这样做会给你:

'someclass '

不过,如果你的字典里还没有 'class' 这个键的话(这和之前的情况只差一个空格)。

撰写回答