A question on modification of a list via a function invocation

Marko Rauhamaa marko at pacujo.net
Fri Sep 8 05:33:05 EDT 2017


Gregory Ewing <greg.ewing at canterbury.ac.nz>:

> Marko Rauhamaa wrote:
>> I definitely trust that:
>>
>>    a = b
>>    assert a is b
>>
>> even when b holds an immutable object.
>
> That's true, but there's rarely a good use case for that
> fact that isn't better addressed with an equality comparison
> rather than an 'is' test.

I use the principle in sentinel objects. I don't care about equality but
identity.

> As an example, back in the days of string exceptions,
> the established idiom was
>
>    MyException = "MyException"
>
>   try:
>      ...
>      raise MyException
>      ...
>   except MyException:
>      ...
>
> Which worked, but it was error-prone. Writing
>
>    except "MyException":
>
> instead would *probably* work, but wasn't guaranteed.
> If the implementation had matched string exceptions
> by equality rather than identity, that wouldn't have
> been an issue.

I would never have thought of doing that. However, strings are as good
sentinel objects as any (they are trivially printable). Whatever
sentinel object you choose, identity is the name of the game, not
equality.


Marko



More information about the Python-list mailing list