I've noticed that there's a few functions that return what appears to
be a tuple, but that also has attributes for each item in the tuple.
For example, time.localtime() returns a time.time_struct, which looks
like a tuple but also like a struct. That is, I can do: time.localtime()
(2006, 1, 18, 21, 15, 11, 2, 18, 0) time.localtime()[3]
21 time.localtime().tm_hour
21
Anyway, I guess there's a few of ways to do this. In the case above,
it would seem reasonable to override __getitem__() and other things to
get that result.
To my question... It seems like a useful but very simple way to
accomplish the above (that is, to have your return value accessible as
both a sequence and a struct) is to subclass tuple. Something like
this:
def foo():
class NewTuple(tuple): pass
x = NewTuple((1,2))
x.a, x.b = x
return x
And so I can do:
x = foo()
print x
print x.a
print x.b
And the result is:
(1, 2)
1
2
So, the question I have is just a style and/or pattern question...
Does anyone do this? Does is seem reasonably intuitive, or ugly? Is
there a better way? Thoughts?
-bri 6 1669 gr*****************@spamgourmet.com wrote: I've noticed that there's a few functions that return what appears to be a tuple, but that also has attributes for each item in the tuple. For example, time.localtime() returns a time.time_struct, which looks like a tuple but also like a struct. That is, I can do:
time.localtime() (2006, 1, 18, 21, 15, 11, 2, 18, 0) time.localtime()[3] 21 time.localtime().tm_hour
21
Anyway, I guess there's a few of ways to do this. In the case above, it would seem reasonable to override __getitem__() and other things to get that result.
To my question... It seems like a useful but very simple way to accomplish the above (that is, to have your return value accessible as both a sequence and a struct) is to subclass tuple. Something like this:
def foo(): class NewTuple(tuple): pass x = NewTuple((1,2)) x.a, x.b = x return x
And so I can do:
x = foo() print x print x.a print x.b
And the result is:
(1, 2) 1 2
So, the question I have is just a style and/or pattern question... Does anyone do this? Does is seem reasonably intuitive, or ugly? Is there a better way? Thoughts?
-bri
I think stylistically better might be
class NewTuple(tuple):
def __new__(self, atup):
self.a, self.b = atup[:2]
return tuple.__new__(self, atup)
x = NewTuple((1, 2, 3, 4, 5))
print x
print x.a
print x.b gr*****************@spamgourmet.com wrote: time.localtime() (2006, 1, 18, 21, 15, 11, 2, 18, 0) time.localtime()[3] 21 time.localtime().tm_hour 21
Anyway, I guess there's a few of ways to do this. In the case above, it would seem reasonable to override __getitem__() and other things to get that result.
I have a generic solution for this (never submitted to the cookbook... should
I?)
import operator
def NamedTuple(*args, **kwargs):
class named_tuple_class(tuple):
pass
values = []
idx = 0
for arg in args:
for name in arg[:-1]:
setattr(named_tuple_class, name,
property(operator.itemgetter(idx)))
values.append(arg[-1])
idx += 1
for name,val in kwargs.iteritems():
setattr(named_tuple_class, name, property(operator.itemgetter(idx)))
values.append(val)
idx += 1
return named_tuple_class(values) t = NamedTuple(("x", 12), ("y", 18)) t
(12, 18) t[0]
12 t.x
12 t[1]
18 t.y
18 t.z
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'named_tuple_class' object has no attribute 'z'
t = NamedTuple(("p", "pos", "position", 12.4)) t
(12.4,) t.p
12.4 t.pos
12.4 t.position
12.4
t = NamedTuple(("p", "pos", 12.4), length="foo") t
(12.4, 'foo') t.p
12.4 t.pos
12.4 t.length
'foo'
--
Giovanni Bajo
On Thu, 18 Jan 2006 gr*****************@spamgourmet.com wrote: Is there a better way? Thoughts?
I was thinking along these lines:
class NamedTuple(tuple):
def __init__(self, indices, values):
"indices should be a map from name to index"
tuple.__init__(self, values)
self.indices = indices
def __getattr__(self, name):
return self[self.indices[name]]
colourNames = {"red": 0, "green": 1, "blue":2}
plum = NamedTuple(colourNames, (219, 55, 121))
The idea is that it's a tuple, but it has some metadata alongside (shared
with other similarly-shaped tuples) which allows it to resolve names to
indices - thus avoiding having two references to everything.
However, if i try that, i get:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: tuple() takes at most 1 argument (2 given)
As far as i can tell, inheriting from tuple is forcing my constructor to
only take one argument. Is that the case? If so, anyone got any idea why?
If i rewrite it like this:
class NamedTuple(tuple):
def __init__(self, values):
tuple.__init__(self, values)
def __getattr__(self, name):
return self[self.indices[name]]
class ColourTuple(NamedTuple):
indices = {"red": 0, "green": 1, "blue":2}
plum = ColourTuple((219, 55, 121))
Then it works. This is even an arguably better style. Changing the
constructor to take *values rather than values, and to validate the length
of the value tuple against the length of the index tuple, would be good,
but, since i'm lazy, is left as an exercise to the reader.
tom
--
Throwin' Lyle's liquor away is like pickin' a fight with a meat packing
plant! -- Ray Smuckles gr*****************@spamgourmet.com wrote: I've noticed that there's a few functions that return what appears to be a tuple, but that also has attributes for each item in the tuple. For example, time.localtime() returns a time.time_struct, which looks like a tuple but also like a struct. That is, I can do:
time.localtime()(2006, 1, 18, 21, 15, 11, 2, 18, 0) time.localtime()[3]21 time.localtime().tm_hour21
Ah, but it ISN'T really a tuple: import time t = time.localtime() type(t)
<type 'time.struct_time'> str(t)
'(2006, 1, 21, 22, 49, 32, 5, 21, 0)'
It's a class object. The __repr__ method returns a string that LOOKS the
same as a tuple.
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Tom Anderson wrote: On Thu, 18 Jan 2006 gr*****************@spamgourmet.com wrote:
Is there a better way? Thoughts?
I was thinking along these lines:
class NamedTuple(tuple): def __init__(self, indices, values): "indices should be a map from name to index" tuple.__init__(self, values) self.indices = indices def __getattr__(self, name): return self[self.indices[name]]
colourNames = {"red": 0, "green": 1, "blue":2} plum = NamedTuple(colourNames, (219, 55, 121))
The idea is that it's a tuple, but it has some metadata alongside (shared with other similarly-shaped tuples) which allows it to resolve names to indices - thus avoiding having two references to everything.
However, if i try that, i get:
Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: tuple() takes at most 1 argument (2 given)
As far as i can tell, inheriting from tuple is forcing my constructor to only take one argument. Is that the case? If so, anyone got any idea why?
This error message is not coming from __init__, but from __new__. See http://www.python.org/2.2/descrintro.html#__new__
James This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: John Hunter |
last post by:
I am writing a python extension module and have a reference counting
question
My function looks like
static PyObject *
pokereval_seven_cards(PyObject *self, PyObject *args)
{
int i;
|
by: fedor |
last post by:
Hi all, happy new year,
I was trying to pickle a instance of a subclass of a tuple when I ran
into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should
I rewrite my class so I can...
|
by: Bob Hollness |
last post by:
Hi all. I know this is basic but it is something that i have never learnt!
I have a function that returns a True or False to the Sub. But what i
actually want to do is return True or False and...
|
by: Nuno Morgadinho |
last post by:
Hello all,
I'm messing around with the Server Programming Interface and the
particular example presented at:
http://www.postgresql.org/docs/current/interactive/spi-examples.html
Ideally, I...
|
by: Karl O. Pinc |
last post by:
I want to return multiple values, but not a set, only a single row,
from a
plpgsql function and I can't seem to get it to work. (I suppose I'd be
happy to return a set, but I can't seem to make...
|
by: bullockbefriending bard |
last post by:
Given:
class Z(object):
various defs, etc.
class ZList(list):
various defs, etc.
i would like to be able to replace
|
by: Mohitz |
last post by:
is pair<fine for returning two values?
What about more than two values?
PS: Values may be of different types.
Opinions?
Thank you
Mohit
|
by: eros |
last post by:
CREATE OR REPLACE FUNCTION f_customerlogininfo(varchar, varchar, varchar) RETURNS public.v_customerlogininfo AS '
DECLARE
p_schm ALIAS FOR $1;
p_contact ALIAS FOR $2;
p_status ALIAS...
|
by: satyanarayan sahoo |
last post by:
Can we write a method which returns multiple values?
|
by: Cromulent |
last post by:
Okay I'm having a few issues with this and I can't seem to get it
sorted out (most likely due to my inexperience with Python).
Here is my Python code:
def fileInput():
data =
s =...
|
by: Rina0 |
last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: erikbower65 |
last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps:
1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal.
2. Connect to...
|
by: linyimin |
last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
|
by: erikbower65 |
last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA:
1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
|
by: DJRhino1175 |
last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this -
If...
|
by: Rina0 |
last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
|
by: DJRhino |
last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer)
If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _
310030356 Or 310030359 Or 310030362 Or...
|
by: lllomh |
last post by:
How does React native implement an English player?
| |