I had an interesting problem today.
def get_tag_by_name(a_dict, key):
return a_dict.get(key, "")
record={"key": "-1"}
print(get_tag_by_name(record, "key") is "-1")
print(get_tag_by_name(record, "key") == "-1")
Returns:
False
True
Now I do understand that:
is will compare the memory location. It is used for object-level comparison.
== will compare the variables in the program. It is used for checking at a value level.
is checks for address level equivalence
== checks for value level equivalence
What I do not understand is, why is the dictionary.get(key,"") creating a new object when the string is "-1" vs "test"
>>> def get_tag_by_name(a_dict, key):
... return a_dict.get(key, "")
...
>>> record={"num_key": "-1", "str_key": "test"}
>>> print(get_tag_by_name(record, "num_key") is "-1", get_tag_by_name(record, "num_key") == "-1")
False True
>>> print(get_tag_by_name(record, "str_key") is "test", get_tag_by_name(record, "str_key") == "test")
True True
>>>
Already consulted: