How does python's dict .get() method check default argument?

后端 未结 1 821
小鲜肉
小鲜肉 2021-01-27 00:28

I have met a strange Python behavior which is difficult to explain to myself. When I pass a default value for getting a key from a dict - looks like it firstly try to find that

相关标签:
1条回答
  • 2021-01-27 00:47

    it has nothing to do with dict.get

    When you call a function in python, arguments are evaluated.

    In your case the key exists, but both arguments need to be evaluated before key lookup occurs.

    For instance what would "work" would be:

    k_dict.get("red") or obj_1.attr4
    

    Since red key exists, the second argument isn't evaluated. It only crashes if red doesn't exist. It doesn't help much in that case (your way of doing it has the merit to catch the error whatever the outcome is at least so keep on doing it!), but if you had some complex computation to perform as the default argument it would:

    k_dict.get("red",super_expensive_computation())
    

    is slow even if red exists when:

    k_dict.get("red") or super_expensive_computation()
    

    is fast when red exists. The or technique relies on the fact that the values cannot be 0, just None. Else just use if "red" in k_dict construct.

    0 讨论(0)
提交回复
热议问题