Python中x = y or z表达式含义咨询(附subprocess模块代码示例)
x = y or z in Python Hey there! Let me break down this common Python idiom using your specific example to make it crystal clear.
First, let's recall how Python's or operator works—it's not just for boolean checks! Here's the core logic:
- When you write
y or z, Python evaluatesyfirst. - If
yis a truthy value (anything that isn't considered "false" in Python—like non-empty dictionaries, non-zero numbers, non-empty strings, etc.), the entire expression returnsy. - If
yis a falsy value (thinkNone,False,0, empty lists[], empty dictionaries{}, empty strings"", etc.), Python then evaluateszand returnsz.
So x = y or z is essentially a concise way to set a default value for x: use y if it's "valid" (truthy), fall back to z if y is missing or empty.
Applying this to your code
Looking at your line:
self.lpAttributeList = lpAttributeList or {"handle_list": []}
This does exactly what you'd expect for setting a safe default:
- If
lpAttributeListis already a truthy value (say, a pre-populated dictionary like{"handle_list": [some_handle], "other_key": "value"}),self.lpAttributeListwill take that existing value. - If
lpAttributeListis falsy (likeNone, or an empty dictionary{}), the code will instead assign{"handle_list": []}toself.lpAttributeList. This guarantees thatself.lpAttributeListalways has ahandle_listkey with an empty list at minimum, preventing key errors later when you try to access that attribute.
A quick caveat
Keep in mind this idiom has a small gotcha: if y is a falsy value that you actually want to preserve (like 0 when you need x to be 0, or an empty string when you need x to be ""), y or z will overwrite it with z. In those cases, you'd want to use a more explicit check, like x = z if y is None else y instead. But in your dictionary example, this isn't an issue—since an empty dictionary is probably a sign you want the default anyway!
内容的提问来源于stack exchange,提问作者Pablo Ballesteros

