stylistic question -- optional return value

Bjorn Pettersen BPettersen at
Wed Aug 28 15:12:23 EDT 2002

> From: Andrew Koenig [mailto:ark at] 
> >> From: Andrew Koenig [mailto:ark at]
> >> 
> >> Suppose I have a function that sometimes returns one value
> >> and sometimes returns two.  What's the cleanest way to define 
> >> such an interface?
> Bjorn> The only time I've had type errors in my Python 
> programs is when 
> Bjorn> I've tried to do this with a function. If I *have* to do it, I 
> Bjorn> would probably chose something along the lines of:
> Bjorn>   def fn(args):
> Bjorn>       class Tmp: pass
> Bjorn>       tmp = Tmp()
> Bjorn>       ...
> Bjorn>       tmp.x = __
> Bjorn>       tmp.y = __
> Bjorn>       return tmp
> Bjorn> your next question should be "why isn't fn a method of Tmp 
> Bjorn> instead" to which I would reply "indeed" <wink>
> Actually, my next question would be why you didn't use a 
> 2-tuple instead of defining a class with the same properties.

I could have used a dict, but I generally never use tuples if I need to
return a variable number of arguments. Since I'm assuming the values
you're returning are related, it seems natural to me to wrap them up in
an instance.

> And my answer to your question is that the function I'm 
> defining is actually a family of methods in a fairly 
> substantial class hierarchy.

You know your situation best of course, so maybe it makes more sense for
you to always return a tuple with sentinels for missing data...?

-- bjorn

More information about the Python-list mailing list