Using tuple as parameter to a function
marco.nawijn at colosso.nl
marco.nawijn at colosso.nl
Mon Nov 9 09:57:39 EST 2015
On Monday, November 9, 2015 at 2:58:21 PM UTC+1, Chris Angelico wrote:
> On Tue, Nov 10, 2015 at 12:40 AM, Cecil Westerhof <Cecil at decebal.nl> wrote:
> > I was thinking about something like:
> > values = (( 1, 100), ( 2, 100), ( 5, 100),
> > 10, 100), (20, 100), (40, 100))
> > for value in values:
> > do_stress_test('sqlite', ???)
> > do_stress_test('postgres', ???)
> >
> > Is this possible? If so: what do I put at the place of the '???'?
> >
> > I could change the second and third parameter to a tuple as the second
> > parameter, but I prefer three parameters if that would be possible.
>
> Easy! Just unpack the tuple. Two options:
>
> # Unpack in the loop
> for count, size in values:
> do_stress_test('sqlite', count, size)
> do_stress_test('postgres', count, size)
>
> # Unpack in the function call
> for value in values:
> do_stress_test('sqlite', *value)
> do_stress_test('postgres', *value)
>
> Either will work. For what you're doing here, I'd be inclined to the
> first option, so you can give the values appropriate names (I'm
> completely guessing here that they might be some sort of iteration
> count and pool size; use names that make sense to your program); the
> other option looks uglier in this particular instance, though it's a
> more direct answer to your question.
>
> This is one of Python's best-kept secrets, I think. It's not easy to
> stumble on it, but it's so handy once you know about it.
>
> ChrisA
If the two numbers are actually conceptually connected, you could
consider passing them as a namedtuple. The function would then
receive two parameters instead of three. Something like the
following (expanding on ChrisA's example):
from collections import namedtuple
StressParameters = namedtuple('StressParameters', ('count', 'size'))
def do_stress_test(db_backend, stress_parameters):
# Some useful stuff...
count = stress_parameters.count
size = stress_parameters.size
# More useful stuff
parameters = [StressParameters(1, 100), StressParameters(2,100)]
for p in parameters:
do_stress_test('sqlite', p)
do_stress_test('postgres', p)
More information about the Python-list
mailing list