Looking for the best way to translate an idiom

drobinow at gmail.com drobinow at gmail.com
Mon Dec 15 01:54:47 CET 2008

On Dec 14, 11:19 am, Paul  Moore <p.f.mo... at gmail.com> wrote:
> I'm translating some code from another language (Lua) which has
> multiple function return values. So, In Lua, it's possible to define a
> function
>     function f()
>         return 1,2,3
>     end
> which returns 3 values. These can then be used/assigned by the caller:
>     a,b,c = f()
> So far, much like Python, but the key difference is that in Lua,
> excess arguments are ignored - so you can do
>     a = f()
> or even
>     a = f() + 1
> where in the latter, a is 2 (as addition only needs 1 argument, so the
> extra ones are discarded).
> This results in the code which I'm trying to translate having
> functions which return multiple arguments, the first of which is the
> "main" result, and the following values are "extra" results
> (specifically, the position at which a match is found, followed by the
> "captured" values of the match).
> I'm trying to find a natural equivalent in Python. So far, I've
> considered the following:
> - return a tuple (pos, captures). This is messy, because you end up
> far too often unpacking the tuple and throwing away the second value
> - return an object with pos and captures attributes. This is better,
> as you can do match(...).pos to get the position alone, but it doesn't
> really feel "pythonic" (all those calls with .pos at the end...)
> - have 2 calls, one to return just the position, one to return both.
> This feels awkward, because of the 2 method names to remember.
> To make things worse, Lua indexes strings from 1, so it can use a
> position of 0 to mean "no match" - so that a simple "did it match?"
> test looks like if (match(....))... - where in Python I need if
> (matchpos(...) != -1)... (Although if I return a match object, I can
> override __nonzero__ to allow me to use the simpler Lua form).
> Can anyone suggest a good idiom for this situation? At the moment, I'm
> returning a match object (the second option) which seems like the
> least bad of the choices (and it mirrors how the re module works,
> which is somewhat useful). But I'd like to know what others think. If
> you were using a pattern matching library, what interface would you
> prefer?
> I suspect my intuition isn't accurate here, as most of the use I've
> made of the library is in writing tests, which isn't typical use :-(
> Thanks for any assistance.
> Paul

I'm baffled by this discussion.
What's wrong with
   a, dontcare, dontcare2 = f()
   a = a + 1

 Simple, clear, and correct.

More information about the Python-list mailing list