[Tutor] diferent between " "(empty string) and None as condition

Cameron Simpson cs at cskk.id.au
Sat Apr 25 03:38:44 EDT 2020


On 24Apr2020 23:07, boB Stepp <robertvstepp at gmail.com> wrote:
>On Fri, Apr 24, 2020 at 7:56 AM Mats Wichmann <mats at wichmann.us> wrote:
>
>> === extra credit, no need to go here if you don't want:
>>
>> There are also cases where things are coded in such a way that None is a
>> valid value, and can't be used as the sentinel, and you need yet another
>> value to distinguish that something out-of-band happened...
>
>Would you please show a realistic example where one might do this --
>where None can't be used as a sentinel because it is otherwise
>occupied?

Anything where a valid function result might be None.

Invented example:

    from queue import Queue

    EOF = object()
    Q = Queue()
    d = {'a': 0, 'b': 2}
    for k in 'a', 'b', 'c':
        Q.put( d.get(k) )
    Q.put(EOF)
    while True:
        v = Q.get()
        if v is EOF:
            break
        print("v =", v)

Here we have a Queue onto which we might want to put _any_ value, 
including None. The consumer wnats to know when all the values have been 
received. For this purpose we make a special object instance EOF for the 
sentinel, which we know will not be used as a value.

This kind of "make a special instance of object" is in fact a common 
idiom for sentinel in Python.

Cheers,
Cameron Simpson <cs at cskk.id.au>

Q: How does a hacker fix a function which doesn't work for all of the 
elements in its domain?
A: He changes the domain.
- Rich Wareham <rjw57 at hermes.cam.ac.uk>


More information about the Tutor mailing list