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).
Python 3.3.4 (v3.3.4:7ff62415e426, Feb 9 2014, 00:29:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from unittest.mock import sentinel
>>> sentinel.FOO
sentinel.FOO
>>> sentinel.FOO is sentinel.FOO
True
>>> sentinel.BarBamBaz
sentinel.BarBamBaz
Thoughts?
ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
http://www.voidspace.org.uk/
May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html