473,383 Members | 1,788 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,383 software developers and data experts.

Using tuples correctly?

I like tuples alot. But in some situations you seem to be forced to
access the elements of a tuple via its indexes and that is pretty
ugly. For example:

# make_color() returns a rgb tuple (r, g, b). I.e. (255, 0, 0)
print "The red value is: ", make_color()[0]

Not nice at all. It is maybe OK for a rgb tuple that only has three
elements, but for a tuple that has 10+ elements, index access is
rediculous. In that case, unpacking wont helpe either. What you would
like to write is:

print "The red value is: ", make_color().r

You can get that to work by using this recipe
http://aspn.activestate.com/ASPN/Coo.../Recipe/218485 from
the Python Cookbook. Then write this:

Color = superTuple("Color", ["r", "g", "b"])
def make_color():
return Color(12, 24, 48)

However, then make_color has to assume that there already exists a
special tuple type named Color. But that assumption is bad and you
shouldn't need to assume it. You could also write

return superTuple("Color", ["r", "g", "b"])(12, 24, 48)

To create the tuple type and instantiate it at the same type. But it
is alot to write. You could trim it down to: st("r", "g", "b")(12, 24,
48) if you want to save your fingers. Still to much and looks kinda
awkward.

After some more browsing of the Python Cookbook and googling it seems
like lots of people is trying to emulate structs on the fly in python.
So why aren't there a tuple-with-named-attributes type in python? So
you could write stuff like this:

return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)

Clearly, I must be thinking wrong or it would already be implemented
in python. Atleast there would have been a PEP for it. Maybe I'm just
using tuples incorrectly and that is why my code uses index access to
tuples? Someone must have already thought about this and they must
have discussed it and quickly realized that this is A Very Bad Thing.
But why? I'm new, so please dont get to angry if the answer is
obvious.

--
mvh Björn
Jul 18 '05 #1
3 1722
On Mon, 11 Oct 2004 05:53:47 +0200, =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?= <bj*****@gmail.com> wrote:
I like tuples alot. But in some situations you seem to be forced to
access the elements of a tuple via its indexes and that is pretty
ugly. For example:

# make_color() returns a rgb tuple (r, g, b). I.e. (255, 0, 0)
print "The red value is: ", make_color()[0]

Not nice at all. It is maybe OK for a rgb tuple that only has three
elements, but for a tuple that has 10+ elements, index access is
rediculous. In that case, unpacking wont helpe either. What you would
like to write is:

print "The red value is: ", make_color().r

You can get that to work by using this recipe
http://aspn.activestate.com/ASPN/Coo.../Recipe/218485 from
the Python Cookbook. Then write this:

Color =3D superTuple("Color", ["r", "g", "b"])
def make_color():
return Color(12, 24, 48)

However, then make_color has to assume that there already exists a
special tuple type named Color. But that assumption is bad and you
shouldn't need to assume it. You could also write Why is that bad? You only have to define it once.
return superTuple("Color", ["r", "g", "b"])(12, 24, 48)

To create the tuple type and instantiate it at the same type. But it
is alot to write. You could trim it down to: st("r", "g", "b")(12, 24,
48) if you want to save your fingers. Still to much and looks kinda
awkward. How about
return Color(12, 24, 48, order='r g b')
or
Color.names = 'r g b'.split() # override names for all instances that don't have order=
... # above is not even necessary, since that's the initial names value
return Color(g=24, r=12, b=48) # use names to assign ordered values
or
return Color() # put zeroes for unspecified values to match names length

etc. See below
After some more browsing of the Python Cookbook and googling it seems
like lots of people is trying to emulate structs on the fly in python.
So why aren't there a tuple-with-named-attributes type in python? So
you could write stuff like this:

return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)

Clearly, I must be thinking wrong or it would already be implemented
in python. Atleast there would have been a PEP for it. Maybe I'm just
using tuples incorrectly and that is why my code uses index access to
tuples? Someone must have already thought about this and they must
have discussed it and quickly realized that this is A Very Bad Thing.
But why? I'm new, so please dont get to angry if the answer is
obvious.


Not sure what you are needing, but consider yet another class:
(not a speed demon, and not tested beyond what you see below ;-)
class Color(tuple): ... names = 'r g b'.split()
... def __new__(cls, *args, **kw):
... values = list(args)
... onames = kw.get('order','').split()
... names = onames or cls.names
... if len(names)>len(values): values.extend([0]*(len(names)-len(values)))
... assert len(names)<=len(values)
... for i, name in enumerate(names):
... if name in kw: values[i] = kw.get(name)
... inst = tuple.__new__(cls, values)
... if onames: inst.names=onames
... return inst
... def __getattr__(self, name):
... try: i = object.__getattribute__(self, 'names').index(name)
... except ValueError: raise AttributeError, 'No component named %r'%name
... return tuple.__getitem__(self, i)
... rgb = Color(1,2,3)
rgb (1, 2, 3) rgb.b, rgb.g, rgb.r #in reverse (3, 2, 1) c0 = Color()
c0 (0, 0, 0) zip(c0.names, c0) [('r', 0), ('g', 0), ('b', 0)] c2 = Color(b=33,g=22)
c2 (0, 22, 33) c3 = Color(red=111, alpha=.5, order='alpha red green blue')
c3 (0.5, 111, 0, 0) rgb (1, 2, 3) rgb.g 2 c3.green 0 c3.alpha

0.5

Maybe some ideas for what you really want ?;-)
Probably overlaps other super-tuples a fair amount. I didn't look.

Regards,
Bengt Richter
Jul 18 '05 #2
> Not sure what you are needing, but consider yet another class:
(not a speed demon, and not tested beyond what you see below ;-)


[snip]

That is all very nice but doesn't get around the fact that either you
declare your objects, or you suffer index access.

--
mvh Björn
Jul 18 '05 #3
BJörn Lindqvist <bj*****@gmail.com> wrote:
...
So why aren't there a tuple-with-named-attributes type in python? So
Good question. Tuple-like thingies with named attrs have been
introduced reasonably recently (e.g. as the return types for modules in
the stdlib such as time and os.stat) but not generalized.
you could write stuff like this:

return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)

Clearly, I must be thinking wrong or it would already be implemented
in python. Atleast there would have been a PEP for it. Maybe I'm just
I think it's just that nobody has yet bothered to write a PEP (and do
all the research and experimentation that goes with it).
using tuples incorrectly and that is why my code uses index access to
tuples? Someone must have already thought about this and they must
have discussed it and quickly realized that this is A Very Bad Thing.
But why? I'm new, so please dont get to angry if the answer is
obvious.


It's not obvious to _me_. In Python 2.5 (too late for 2.4) we COULD
conceivably have such a type, if somebody comes up with a _very_
convincing design for it (the use case is already pretty well
established by the precedents in os.stat and module time, we only need
an obviously great design;-). New syntax for it, I'd rule out (smells
like the language will be near-frozen in 2.4 -> 2.5, as it was in 2.2 ->
2.3 -- I could be guessing wrong on this, of course).

Something like tuple(r=10, g=20, b=30) won't wash because keyword args
are passed as a dict -- orderless. Pity, because apart from this it
would be neat... tuple would have to keep a cache of tuple subtypes
indexed by attrnames ('r', 'g', 'b') to avoid making a new type every
time, but that's OK, I think. Maybe an optional first parameter giving
the ordering, as in tuple(('r','g','b'), r=10,g=20,b=30)? It being an
exeception if a different ordering is specified for a set of attribute
names which already exists, and default being 'any order you please'...?
But it feels klunky...:-(. Anyway, this is why the PEP process exists
-- so, a Paladin of the new idea should ask Barry (I think he's still
Pep Czar) for a PEP number and start drafting one.

Use cases and implementation pretty obvious, nothing but a new design to
find... seems pretty simple, as PEPs go...
Alex
Jul 18 '05 #4

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

Similar topics

10
by: Ivan Voras | last post by:
Are there any performance/size differences between using tuples and using lists? -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke
3
by: Thorsten Kampe | last post by:
I found out that I am rarely using tuples and almost always lists because of the more flexible usability of lists (methods, etc.) To my knowledge, the only fundamental difference between tuples...
0
by: could ildg | last post by:
I want to retrieve all urls in a string. When I use re.fiandall, I get a list of tuples. My code is like below: url=unicode(r"((http|ftp)://)?((((+\.)+){3}+(/+)?)|(\w*((\.\w+)+){2,})(*)*)")...
2
by: Martin v. Löwis | last post by:
I've been working on PEP 353 for some time now. Please comment, in particular if you are using 64-bit systems. Regards, Martin PEP: 353 Title: Using ssize_t as the index type Version:...
11
by: Noah | last post by:
I have a list of tuples I want to reverse the order of the elements inside the tuples. I know I could do this long-form: q = y = for i in y: t=list(t)
5
by: fff_afafaf | last post by:
Do you know is it possible to put different kinds of tuples to one container? E.g. to a vector? (The lengths of the tuples are different, and also the types in the tuples are different.. -Is it...
10
by: rshepard | last post by:
While working with lists of tuples is probably very common, none of my five Python books or a Google search tell me how to refer to specific items in each tuple. I find references to sorting a list...
122
by: C.L. | last post by:
I was looking for a function or method that would return the index to the first matching element in a list. Coming from a C++ STL background, I thought it might be called "find". My first stop was...
27
by: seberino | last post by:
Please help me think of an example where immutable tuples are essential. It seems that everywhere a tuple is used one could just as easily use a list instead. chris
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: 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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.