Hello All,
How does one make an arbitrary class (e.g. class myclass(object)) behave like
a list in method calls with the "*something" operator? What I mean is:
myobj = myclass()
doit(*myobj)
I've looked at getitem, getslice, and iter. What is it if not one of these?
And, how about the "**something" operator?
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/ 11 1283
James Stroud wrote: Hello All,
How does one make an arbitrary class (e.g. class myclass(object)) behave like a list in method calls with the "*something" operator? What I mean is:
You need to base myclass on a list if I understand your question.
class myclass(list):
def __init__(self, *items):
# change items if needed
# initate other attributes if needed
list.__init__(self, *items)
Then the line below should work. Of course it won't do much with out
something in it. ;-)
myobj = myclass()
doit(*myobj)
I've looked at getitem, getslice, and iter. What is it if not one of these?
And, how about the "**something" operator?
James
A dictionary would be pretty much the same except subclassed from a
dictionary of course.
Cheers,
Ron
Ron Adam <rr*@ronadam.com> wrote: James Stroud wrote:
Hello All,
How does one make an arbitrary class (e.g. class myclass(object)) behave like a list in method calls with the "*something" operator? What I mean is:
You need to base myclass on a list if I understand your question.
Not necessary, all you need is __iter__: def f(*a): print a
.... class X(object):
.... def __iter__(self): return iter(xrange(4))
.... f(*X())
(0, 1, 2, 3)
I've looked at getitem, getslice, and iter. What is it if not one of these?
Obviously James hadn't looked at __iter__ in the RIGHT way!
And, how about the "**something" operator?
James
A dictionary would be pretty much the same except subclassed from a dictionary of course.
I believe this one is correct (but I have not checked in-depth!).
Alex
James Stroud wrote: Hello All,
How does one make an arbitrary class (e.g. class myclass(object)) behave like a list in method calls with the "*something" operator? What I mean is:
myobj = myclass()
doit(*myobj)
Make it iterable: class Foo(object):
... def __iter__(self):
... yield 1
... yield 2
... yield 3
... def bar(*args):
... print args
... bar(*Foo())
(1, 2, 3)
And, how about the "**something" operator?
Use a dictionary.
Alex Martelli wrote: Ron Adam <rr*@ronadam.com> wrote:
James Stroud wrote:
And, how about the "**something" operator?
James
A dictionary would be pretty much the same except subclassed from a dictionary of course.
I believe this one is correct (but I have not checked in-depth!).
Alex
A quick test shows the error message to be very specific in this case,
where as the *something error message requests a more general sequence. def foo(**b): pass
.... class a: pass
.... foo(**a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: foo() argument after ** must be a dictionary
Ron
On Monday 07 November 2005 20:36, Alex Martelli wrote: I've looked at getitem, getslice, and iter. What is it if not one of these?
Obviously James hadn't looked at __iter__ in the RIGHT way!
I was attempting to re-define iter of a subclassed list, to find the "magic"
method, but it didn't work. I'm not sure if "wrong" and "right" apply here:
py> class NewList(list):
.... def __iter__(self):
.... return iter([8,9,10])
....
py>
py> n = NewList([1,2,3])
py>
py> def doit(*args):
.... print args
....
py> doit(*n)
(1, 2, 3)
py> for x in iter(n):
.... print x
....
8
9
10
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
James Stroud wrote: I was attempting to re-define iter of a subclassed list, to find the "magic" method, but it didn't work. class List(list):
.... def __iter__(self): return iter("abc")
.... a = List([1,2,3]) list(a)
['a', 'b', 'c'] tuple(a)
(1, 2, 3)
list-to-tuple conversion is optimized for performance -- basically a
memcopy() of the internal data. As with a similar peculiarity with
file.write() and the print statement, the problem could be shunned if
python would check for the exact class instead of a test that is equivalent
to isinstance().
Peter
On Monday 07 November 2005 20:36, Alex Martelli wrote: Ron Adam <rr*@ronadam.com> wrote: James Stroud wrote: Hello All,
How does one make an arbitrary class (e.g. class myclass(object)) behave like a list in method calls with the "*something" operator? What I mean is:
[snip] A dictionary would be pretty much the same except subclassed from a dictionary of course.
I believe this one is correct (but I have not checked in-depth!).
Does anyone else find the following annoying:
py> from UserDict import UserDict
py> aud = UserDict({"a":1, "b":2})
py> def doit(**kwargs):
.... print kwargs
....
py> aud
{'a': 1, 'b': 2}
py> doit(**aud)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: doit() argument after ** must be a dictionary
UserDict should be isomorphic with a dict. The fact that it is not in this
case seems terribly un-pythonic to me.
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
James Stroud wrote: Does anyone else find the following annoying:
py> from UserDict import UserDict py> aud = UserDict({"a":1, "b":2}) py> def doit(**kwargs): ... print kwargs ... py> aud {'a': 1, 'b': 2} py> doit(**aud) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: doit() argument after ** must be a dictionary
UserDict should be isomorphic with a dict. The fact that it is not in this case seems terribly un-pythonic to me.
UserDict only exists for backwards compatibility with old code that used
it before one could subclass from dict directly. Don't use it if you can
avoid it. UserDict only ever exposed the Python-side interface of dicts.
It couldn't expose the C-side interface, and it's the C-side interface
that **kwds is using.
--
Robert Kern rk***@ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
On Tuesday 08 November 2005 22:54, Robert Kern wrote: James Stroud wrote: Does anyone else find the following annoying:
py> from UserDict import UserDict py> aud = UserDict({"a":1, "b":2}) py> def doit(**kwargs): ... print kwargs ... py> aud {'a': 1, 'b': 2} py> doit(**aud) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: doit() argument after ** must be a dictionary
UserDict should be isomorphic with a dict. The fact that it is not in this case seems terribly un-pythonic to me.
UserDict only exists for backwards compatibility with old code that used it before one could subclass from dict directly. Don't use it if you can avoid it. UserDict only ever exposed the Python-side interface of dicts. It couldn't expose the C-side interface, and it's the C-side interface that **kwds is using.
That **kwargs insists on using the C-side interface is precisely the annoyance
to which I am referring. I should be able to write a dictionary-like
interface in python and **kwargs should in turn be able to use it. If the
retort is that the C-side interface is used for performance, my retort to the
retort is that an isinstance() is already being called somewhere, so no
additional tests would need to be made to make **kwargs more generalized.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
Robert Kern wrote: James Stroud wrote:
Does anyone else find the following annoying:
py> from UserDict import UserDict py> aud = UserDict({"a":1, "b":2}) py> def doit(**kwargs): ... print kwargs
UserDict only exists for backwards compatibility with old code that used it before one could subclass from dict directly. Don't use it if you can avoid it. UserDict only ever exposed the Python-side interface of dicts. It couldn't expose the C-side interface, and it's the C-side interface that **kwds is using.
Which means that you can't subclass dict with, say, a lazy dictionary
(that doesn't retrieve values until they're looked up) and use it with
**kwargs. That bit me last year: http://groups.google.com/group/comp....b7e17bb395494e
It would be useful in some situations to be able to do this (especially
where getting the dictionary values is time-consuming and the function
you're calling doesn't use all the values in the dictionary). For my
particular case I had a fairly easy workaround.
James Stroud wrote: That **kwargs insists on using the C-side interface is precisely the annoyance to which I am referring. I should be able to write a dictionary-like interface in python and **kwargs should in turn be able to use it. If the retort is that the C-side interface is used for performance, my retort to the retort is that an isinstance() is already being called somewhere, so no additional tests would need to be made to make **kwargs more generalized.
Well, the test is in Python/ceval.c (grep for the error message) and the
function that needs a bona fide dictionary is PyObject_Call in
Objects/abstract.c . If you can work up a patch, Guido will probably
consider it although I would suggest searching python-dev for previous
discussions first.
--
Robert Kern rk***@ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Terje Slettebų |
last post by:
To round off my trilogy of "why"'s about PHP... :) If this subject have been
discussed before, I'd appreciate a pointer to it. I again haven't found it
in a search of the PHP groups.
The PHP...
|
by: |
last post by:
Hi all,
I've been using C++ for quite a while now and I've come to the point where I need to overload new
and delete inorder to track memory and probably some profiling stuff too. I know that...
|
by: JaSeong Ju |
last post by:
I would like to overload a C function. Is there any easy way to do this?
|
by: james b |
last post by:
Hi all,
I'm trying to do something with method overloading and I can't seem to
get it to work
my code is along the lines of
public int method1(int a, int b, int c){
//method body
}
public...
|
by: |
last post by:
Hi,
Why can I not overload on just the return type?
Say for example.
public int blah(int x)
{
}
|
by: Massimo Soricetti |
last post by:
Hello,
recently I wrote a little class which has to wrap two different type of
data, showing the same external interface.
I used operator overloading, but the same result I could eventually...
|
by: Achim Domma |
last post by:
Hi,
I want to use Python to script some formulas in my application. The user
should be able to write something like
A = B * C
where A,B,C are instances of some wrapper classes. Overloading...
|
by: y-man |
last post by:
Hi,
I am trying to get an overloaded operator to work inside the class it
works on. The situation is something like this:
main.cc:
#include "object.hh"
#include "somefile.hh"
object obj,...
|
by: Pramod |
last post by:
I have one question. Can I catch exception in function overloading.In
my programm i want to create two function with same signature and same
return type. I know its not possible...can i use...
|
by: Matthew |
last post by:
Am I correct in thinking there is no method/function overloading of any
kind in any version of PHP?
Thanks,
Matthew
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
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...
|
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...
|
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,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
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...
|
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...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
| |