473,799 Members | 3,101 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.00 5),

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 3629

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)

iD8DBQFBmjMiJd0 1MZaTXX0RAlWuAJ 9NYRLC8x8rkvZIT iSBFbAs4mfeZQCe LWbV
28XJV/WFluHxo6P1mfWkE 5w=
=TW1+
-----END PGP SIGNATURE-----

Jul 18 '05 #3
"Jeff Epler" <je****@unpytho nic.net> wrote in message
news:ma******** *************** *************** @python.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***********@A cm.Org
Jul 18 '05 #5
On Tue, 16 Nov 2004 16:42:57 GMT, Paul McGuire
<pt***@austin.r r._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.00 5),

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=Non e):
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********@gmai l.com
mail: ca********@yaho o.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=Non e):
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=Non e): .... return it.islice(it.ch ain(iter(seq), it.repeat(defau ltitem)), 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 misunderstandin g 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=Non e): ... return it.islice(it.ch ain(iter(seq), it.repeat(defau ltitem)), 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 misunderstandin g 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********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #8
Paul McGuire <pt***@austin.r r._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
3532
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 by pointer in C++, is there such way in Python? Thansk in advance. J.R.
1
1561
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 (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_SetString(PyExc_TypeError,"tuple's 1st member was not an integer");
66
5041
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
2803
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 _build_used(): .... y = x + 1 .... return x, y ....
22
3504
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); //do I need to de reference here or just pass theString without the "ref"
16
1355
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', 'less'), ('something', 'nothing'), ('good', 'bad')) print x
14
1450
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> list =
4
4629
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 the number of variables need not to fit the number of list elements. That means, if you have less list elements variables are filled with
21
7274
by: Martin Geisler | last post by:
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkjlQNwACgkQ6nfwy35F3Tj8ywCgox+XdmeDTAKdN9Q8KZAvfNe4 0/4AmwZGClr8zmonPAFnFsAOtHn4JhfY =hTwE -----END PGP SIGNATURE-----
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10490
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9078
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.