[Python-ideas] Better repr() for sentinel objects
Chris Angelico
rosuav at gmail.com
Sat Feb 15 12:56:32 CET 2014
A common pattern, both in the stdlib and in user code, is the
dedicated sentinel object to recognize an omitted argument:
no_timeout = object()
def get_data(source, timeout=no_timeout):
if timeout is not no_timeout:
source.set_alarm(timeout)
return source.pop()
This is a bit unclear in the function signature, as seen in help():
"""
Help on function get_data in module __main__:
get_data(source, timeout=<object object at 0x7f579fe53070>)
"""
The stdlib does this:
"""
Help on function create_connection in module socket:
create_connection(address, timeout=<object object at 0x7fe52900b080>,
source_address=None)
""" # chomp docstring
"""
Help on function urlopen in module urllib.request:
urlopen(url, data=None, timeout=<object object at 0x7fe52900b080>, *,
cafile=None, capath=None, cadefault=False)
""" # no docstring to chomp, actually
It's not particularly useful to get the object's address. Proposal: A
self-documenting Sentinel class which serves the exact same purpose.
class Sentinel:
def __init__(self, desc):
self.desc = desc
def __repr__(self):
return "Sentinel(" + repr(self.desc) + ")"
This can then be used just like object(), only it retains something
for the benefit of its repr:
no_timeout = Sentinel("No timeout")
# Same function definition
"""
Help on function get_data in module __main__:
get_data(source, timeout=Sentinel('No timeout'))
"""
I don't know how this interacts with Argument Clinic and C-written
functions. If there's something that's being done for those that would
make sentinels come out a particular way in their help() info, ideally
this should be displayed the same way (or at least similarly).
Thoughts?
ChrisA
More information about the Python-ideas
mailing list