473,394 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Idiom for default values when unpacking a tuple

I'm trying to manage some configuration data in a list of tuples, and I
unpack the values with something like this:

configList = [
("A",1,2,3),
("F",1,3,4),
("X",2,3,4),
("T",1,5,4),
("W",6,3,4),
("L",1,3,8),
]
for data in configList:
name,a,b,c = data
... do something with a,b, and c

Now I would like to add a special fourth config value to "T":
("T",1,5,4,0.005),

and I would like to avoid having to put 0's or None's in all of the others.
Is there a clean Python idiom for unpacking a tuple so that any unassigned
target values get a default, or None, as in:

tup = (1,2)
a,b,c = tup

gives a = 1, b = 2, and c = None.

I've tried creating a padUnpack class, but things aren't quite clicking...

TIA,
-- Paul
Jul 18 '05 #1
8 3607

You can always have a try/exept clause around unpacking. That you could
fator out into a function that always returns the right sized tuples. Like
this:

def unpack(t):
try:
a,b,c = t
d = None
except ValueError:
a,b,c,d = t
return a,b,c,d

--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
A function to pad a tuple to a given length is not hard to write.
[l] * i is empty if i <= 0, otherwise it has i repetitions of l.

def pad(t,l):
return t + (None,) * (l - len(t))

tup = (1,2)
a, b, c = pad(tup, 3)
print a, b, c

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFBmjMiJd01MZaTXX0RAlWuAJ9NYRLC8x8rkvZITiSBFb As4mfeZQCeLWbV
28XJV/WFluHxo6P1mfWkE5w=
=TW1+
-----END PGP SIGNATURE-----

Jul 18 '05 #3
"Jeff Epler" <je****@unpythonic.net> wrote in message
news:ma**************************************@pyth on.org...

So is there any easy way for the pad function to figure out for itself that
the target length is 3, without my having to tell it so?

-- Paul
Jul 18 '05 #4
Paul McGuire wrote:
So is there any easy way for the pad function to figure out for itself that
the target length is 3, without my having to tell it so?

Nope.
If there were, what would you propose the function "pad" below use as a
desired length in the statement:

a,b,c = pad(something)[1:4]

--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #5
On Tue, 16 Nov 2004 16:42:57 GMT, Paul McGuire
<pt***@austin.rr._bogus_.com> wrote:
I'm trying to manage some configuration data in a list of tuples, and I
unpack the values with something like this:

configList = [
("A",1,2,3),
("F",1,3,4),
("X",2,3,4),
("T",1,5,4),
("W",6,3,4),
("L",1,3,8),
]
for data in configList:
name,a,b,c = data
... do something with a,b, and c

Now I would like to add a special fourth config value to "T":
("T",1,5,4,0.005),

and I would like to avoid having to put 0's or None's in all of the others.
Is there a clean Python idiom for unpacking a tuple so that any unassigned
target values get a default, or None, as in:

tup = (1,2)
a,b,c = tup

gives a = 1, b = 2, and c = None.

I've tried creating a padUnpack class, but things aren't quite clicking...

TIA,
-- Paul


How about having a iterator function that is guaranteed to always
return a fixed number of elements, regardless of the size of the
sequence? I've checked it, and it does not exist in itertools.
Something like this (simple-minded, just a proof of concept, and
highly optimizable in at least a hundred different ways :-):

def iterfixed(seq, times, defaultitem=None):
for i in range(times):
if i < len(seq):
yield seq[i]
else:
yield defaultitem

To unpack a tuple using it, it's simply a matter to use it like this:
tuple(iterfixed((1,2,3,4), 3)) (1, 2, 3) tuple(iterfixed((1,2,3,4), 6)) (1, 2, 3, 4, None, None)

In fact, if you *are* doing tuple unpacking, *you don't have to build
the tuple*. You can simply do it like this:
a,b,c = iterfixed((1,2,3,4), 3)
a,b,c (1, 2, 3) a,b,c,d,e,f = iterfixed((1,2,3,4), 6)
a,b,c,d,e,f

(1, 2, 3, 4, None, None)

The only catch is that, if you have only one parameter, then all you
will get is the generator itself. But that's a corner case, and not
the intended use anyway.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmail.com
mail: ca********@yahoo.com
Jul 18 '05 #6
Carlos Ribeiro wrote:
How about having a iterator function that is guaranteed to always
return a fixed number of elements, regardless of the size of the
sequence? I've checked it, and it does not exist in itertools.
Something like this (simple-minded, just a proof of concept, and
highly optimizable in at least a hundred different ways :-):

def iterfixed(seq, times, defaultitem=None):
for i in range(times):
if i < len(seq):
yield seq[i]
else:
yield defaultitem
Well, it doesn't quite exist in itertools, but it's there with just a
simple composition:
def iterfixed(seq, times, defaultitem=None): .... return it.islice(it.chain(iter(seq), it.repeat(defaultitem)), times)
.... tuple(iterfixed((1,2,3,4), 3)) (1, 2, 3) tuple(iterfixed((1,2,3,4), 6)) (1, 2, 3, 4, None, None) a,b,c = iterfixed((1,2,3,4), 3)
a,b,c (1, 2, 3) a,b,c,d,e,f = iterfixed((1,2,3,4), 6)
a,b,c,d,e,f (1, 2, 3, 4, None, None)
The only catch is that, if you have only one parameter, then all you
will get is the generator itself. But that's a corner case, and not
the intended use anyway.


Not exactly sure what you mean here. If you only have one item in your
unpack tuple, I believe things still work, e.g.:
a, = iterfixed((1,2,3,4), 1)
a

1

But I'm probably just misunderstanding your statement...

Steve
Jul 18 '05 #7
On Thu, 18 Nov 2004 03:34:42 GMT, Steven Bethard
<st************@gmail.com> wrote:
Well, it doesn't quite exist in itertools, but it's there with just a
simple composition:
>>> def iterfixed(seq, times, defaultitem=None): ... return it.islice(it.chain(iter(seq), it.repeat(defaultitem)), times)
...


After I posted the previous recipe I polished it up a little bit more
and renamed it as "iunpack". It now returns the remaining part of the
tuple as the last item. As it is, it's a good candidate for itertools
-- it's way more convenient than the composition option, and judging
by how many times the issue was brought up here, it's a relatively
common problem.
>>> tuple(iterfixed((1,2,3,4), 3)) (1, 2, 3) >>> tuple(iterfixed((1,2,3,4), 6)) (1, 2, 3, 4, None, None) >>> a,b,c = iterfixed((1,2,3,4), 3)
>>> a,b,c (1, 2, 3) >>> a,b,c,d,e,f = iterfixed((1,2,3,4), 6)
>>> a,b,c,d,e,f (1, 2, 3, 4, None, None)
The only catch is that, if you have only one parameter, then all you
will get is the generator itself. But that's a corner case, and not
the intended use anyway.


Not exactly sure what you mean here. If you only have one item in your
unpack tuple, I believe things still work, e.g.:
>>> a, = iterfixed((1,2,3,4), 1)
>>> a

1

But I'm probably just misunderstanding your statement...


No -- it's that you remembered to include the comma. My example was to
assign it it one item only, which really isn't tuple unpacking; but
this is a easy mistake to do in this case. Anyway, it should work as
intended.

BTW, I never saw it mentioned before that iterators can be used at the
right side of an assignment with the tuple meaning. Nice side effect,
I think.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmail.com
mail: ca********@yahoo.com
Jul 18 '05 #8
Paul McGuire <pt***@austin.rr._bogus_.com> wrote:
Is there a clean Python idiom for unpacking a tuple so that any
unassigned target values get a default, or None


If i is a tuple you want unpacked, then something like

(lambda a, b, c, d = None: (a, b, c, d))(*i)

is the expanded version with defaults substituted.

-- [mdw]
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

46
by: J.R. | last post by:
Hi folks, The python can only support passing value in function call (right?), I'm wondering how to effectively pass a large parameter, such as a large list or dictionary? It could achieved...
1
by: Jon Perez | last post by:
I want to retrieve a value from a tuple and convert it to a C type. Is the following idiom okay? if (!( ( tmp_pyobj=PyTuple_GetItem(tuple,1) ) && ( c_int=PyInt_AsLong(tmp_pyobj) ) )) { if...
66
by: Darren Dale | last post by:
Hello, def test(data): i = ? This is the line I have trouble with if i==1: return data else: return data a,b,c,d = test()
8
by: Nick Coghlan | last post by:
Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def...
22
by: tshad | last post by:
If I am passing a variable by reference to another routine by reference, do I need to dereference first? string testString; .... FirstSub(ref firstString) { HandleString(ref firstString); ...
16
by: John Salerno | last post by:
I'm a little confused, but I'm sure this is something trivial. I'm confused about why this works: ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) (('hello', 'goodbye'), ('more',...
14
by: Ernesto García García | last post by:
Hi experts, it's very common that I have a list and I want to print it with commas in between. How do I do this in an easy manner, whithout having the annoying comma in the end? <code> ...
4
by: McA | last post by:
Hi all, probably a dumb question, but I didn't find something elegant for my problem so far. In perl you can unpack the element of a list to variables similar as in python (a, b, c = ), but...
21
by: Martin Geisler | last post by:
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkjlQNwACgkQ6nfwy35F3Tj8ywCgox+XdmeDTAKdN9Q8KZAvfNe4 0/4AmwZGClr8zmonPAFnFsAOtHn4JhfY =hTwE -----END PGP...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.