Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

python - Sentinel object and its applications?

I know in python the builtin object() returns a sentinel object. I'm curious to what it is, but mainly its applications.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

object is the base class that all other classes inherit from in python 3. There's not a whole lot you can do with a plain old object. However an object's identity could be useful. For example the iter function takes a sentinel argument that signals when to stop termination. We could supply an object() to that.

sentinel = object()

def step():
    inp = input('enter something: ')
    if inp == 'stop' or inp == 'exit' or inp == 'done':
        return sentinel
    return inp

for inp in iter(step, sentinel):
    print('you entered', inp)

This will ask for input until the user types stop, exit, or done. I'm not exactly sure when iter with a sentinel is more useful than a generator, but I guess it's interesting anyway.

I'm not sure if this answers your question. To be clear, this is just a possible application of object. Fundamentally its existence in the python language has nothing to do with it being usable as a sentinel value (to my knowledge).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...