stylistic question -- optional return value
Erik Max Francis
max at alcyone.com
Wed Aug 28 21:37:48 CEST 2002
Andrew Koenig wrote:
> Another possibility is to return either (x, None) or (x, y). Now
> it is easy to extract x from the compound result. However,
> that strategy removes None from the set of permissible values for y.
If that's a problem, you can always use the fake object trick:
Sentinel = object()
def soAndSo(self, ...):
return x, C.Sentinel
You're guaranteed that C.Sentinel will be a unique object, distinct from
None or any other object you might want to return, so you can do a test
x, y = c.soAndso(...)
if y is C.Sentinel:
# only got the one x object.
I tend to highly prefer using None for this purpose; I can't think of an
instance when I've needed to use this technique, but it is there.
> Yet another possibility is to return (False, x) or (True, x, y).
> Now x is in a common position, so retrieving it is straightforward.
> However, I can obtain the same information content by returning
> (x,) or (x, y). However, I can easily imagine people becoming
> confused by 1-tuples.
Returning either a 1-tuple or a 2-tuple seems reasonable if what's being
returned really does have some sense of a sequence, even if it might be
a little strained. If instead what you're really trying to return is
either one or two independent bits of information simultaneously, then
I'd say always returning a 2-tuple with either None or a proxy sentinel
object for the second element is a better approach.
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
Church / http://www.alcyone.com/pyos/church/
A lambda calculus explorer in Python.
More information about the Python-list