473,326 Members | 2,127 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,326 software developers and data experts.

generic object - moving toward PEP

So I thought I'd try to summarize a few things here and maybe we can
move toward filing a PEP. I'm not really sure I'm the right person to
champion it because, as I've mentioned, I usually eventually replace
generic objects with concrete classes, but I'm certainly willing to do
some of the work writing it up, etc. If you're interested in helping
me, let me know (off-list).

Some quotes from this thread:

Hung Jung Lu wrote:
It seems odd that there is no standard generic object in Python.
Fernando Perez wrote: IPython has this fairly fancy Struct module, which is yet-another-shot
at the same thing. [snip] But if someone does add a fully functional contribution of this kind,
with enough bells and whistles to cover the more advanced cases, I'd
be +100 on that :)


Some arguments for a generic object:

(1) Allows a simple syntax for returning named results:
def f(x): .... return bunch(double=2*x, squared=x**2)
.... y = f(10)
y.double 20 y.squared 100

(2) Allows simple representation of hierarchical data:
x = bunch(a=bunch(b=1, c=10), d=100)
x.a.b 1 x.d 100

Note that without a generic object class of some sort this would
probably be written as something like:
class C1(object): .... def __init__(self, a, d):
.... self.a, self.d = a, d
.... class C2(object): .... def __init__(self, b, c):
.... self.b, self.c = b, c
.... x = C1(a=C2(b=1, c=10), d=100)
Because the generic object version requires only one class (called
'bunch' above), only this class would be needed for
unpickling/unserializing. If the generic object class was easily
available (e.g. in the standard library), this could simplify the
unpickling process somewhat.

(3) Allows simple conversion from dict-style access to attribute access:
d = {'a':2, 'b':4, 'c':16, 'd':256}
d['a'], d['d'] (2, 256) b = bunch(**d)
b.a, b.d (2, 256)

This could actually be supported recursively, if that seems useful:
d = {'a':2, 'b':4, 'c':{'d':16, 'e':256}}
b = bunch.frommapping(d)
b.c.d

16

I think that's most of the arguments I saw on the thread. If anyone
else has arguments for/against adding a generic object type to the
standard lib, now's the time to bring them up. =)

Steve
Jul 18 '05 #1
6 1427
Steven Bethard <st************@gmail.com> writes on Fri, 19 Nov 2004 21:38:14 GMT:
...
Some arguments for a generic object:

(1) Allows a simple syntax for returning named results:
>>> def f(x): .... return bunch(double=2*x, squared=x**2)
.... >>> y = f(10)
>>> y.double 20 >>> y.squared 100

(2) Allows simple representation of hierarchical data:
>>> x = bunch(a=bunch(b=1, c=10), d=100)
>>> x.a.b 1 >>> x.d 100
...
(3) Allows simple conversion from dict-style access to attribute access:
>>> d = {'a':2, 'b':4, 'c':16, 'd':256}
>>> d['a'], d['d'] (2, 256) >>> b = bunch(**d)
>>> b.a, b.d (2, 256)

This could actually be supported recursively, if that seems useful:
>>> d = {'a':2, 'b':4, 'c':{'d':16, 'e':256}}
>>> b = bunch.frommapping(d)
>>> b.c.d

16


How about:

class bunch:
def __init__(self, d__=None, **kw):
d = self.__dict__
if d__ is not None: d.update(d__)
d.update(kw)
You can drop the "d__" magic, when you do not need direct
"dict --> bunch" conversion (of the form "bunch(dict)")
but use a special method ("frommapping") for this.

--
Dieter
Jul 18 '05 #2
Steven Bethard wrote:
So I thought I'd try to summarize a few things here and maybe we can
move toward filing a PEP. I'm not really sure I'm the right person to
champion it because, as I've mentioned, I usually eventually replace
generic objects with concrete classes, but I'm certainly willing to do
some of the work writing it up, etc. If you're interested in helping
me, let me know (off-list).


+1 on this. Would be great (would it be possible to add to 2.4 still?)

Reinhold

--
[Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer
jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen
jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs-
mitteln inkompatibel. -- Florian Diesch in dcoulm
Jul 18 '05 #3
Reinhold Birkenfeld wrote:
Steven Bethard wrote:
So I thought I'd try to summarize a few things here and maybe we can
move toward filing a PEP. I'm not really sure I'm the right person to
champion it because, as I've mentioned, I usually eventually replace
generic objects with concrete classes, but I'm certainly willing to do
some of the work writing it up, etc. If you're interested in helping
me, let me know (off-list).

+1 on this. Would be great (would it be possible to add to 2.4 still?)


Not with a release candidate in distribution, no - only "must-fix"
changes will be made before 2.4 final.

regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
Jul 18 '05 #4
"Steven Bethard" <st************@gmail.com> wrote in message
news:aJtnd.118100$HA.81413@attbi_s01...
<snip>
(3) Allows simple conversion from dict-style access to attribute access:
>>> d = {'a':2, 'b':4, 'c':16, 'd':256}
>>> d['a'], d['d'] (2, 256) >>> b = bunch(**d)
>>> b.a, b.d (2, 256)

This could actually be supported recursively, if that seems useful:
>>> d = {'a':2, 'b':4, 'c':{'d':16, 'e':256}}
>>> b = bunch.frommapping(d)
>>> b.c.d

16


Steven -

This sounds *very* much like the ParseResults class that I implemented in
pyparsing. For a given set of results from a parsing operation, one can
access them:
- as a list (tokens[0], tokens[1], ...)
- as a dict (tokens["name"], tokens["phoneNum"], ...)
- as attributes (tokens.name, tokens.phoneNum, ...)

I started out just returning lists of tokens, but found that it was
important to support some level of naming to the returned tokens -
otherwise, maintenance in the face of modifying grammars became very
difficult. For example, if an optional token were inserted between name and
phoneNum, now one would need to do a lot of testing on number and types of
returned tokens - very messy! Instead, the tokens are given names as
defined in the grammar specification, so that intervening syntax doesn't
mess things up.

Then, I added the attributes-style access because it looks more Pythonic.

ParseResults can also be accessed recursively. If phoneNum were defined
with sub-fields, one could access tokens.phoneNum.areaCode or
tokens["phoneNum"]["areaCode"], for example.

As an afterthought, I then added an XML output format for this class, so
that tokens.asXML("PERSONAL_DATA") would generate:
<PERSONAL_DATA>
<name>John Doe</name>
<phoneNum>555-1212</phoneNum>
</PERSONAL_DATA>

ParseResults defines quite a number of operators for managing and
manipulating ParseResults objects. I think this class may give you some
ideas about your bunch class. I guess some of the code may appear kludgey,
such as the __new__ handling, but it seems to be holding up reasonably well.

HTH,
-- Paul
Jul 18 '05 #5
Steve Holden wrote:
Reinhold Birkenfeld wrote:
+1 on this. Would be great (would it be possible to add to 2.4 still?)


Not with a release candidate in distribution, no - only "must-fix"
changes will be made before 2.4 final.


Yeah, this is definitely targeted at 2.5.

The other Steve
Jul 18 '05 #6
Paul McGuire wrote:

This sounds *very* much like the ParseResults class that I implemented in
pyparsing. For a given set of results from a parsing operation, one can
access them:
- as a list (tokens[0], tokens[1], ...)
- as a dict (tokens["name"], tokens["phoneNum"], ...)
- as attributes (tokens.name, tokens.phoneNum, ...) [snip] As an afterthought, I then added an XML output format for this class, so
that tokens.asXML("PERSONAL_DATA") would generate:
<PERSONAL_DATA>
<name>John Doe</name>
<phoneNum>555-1212</phoneNum>
</PERSONAL_DATA>


Yeah, the last time I really wanted this, it was because I had an XML
document and wanted a somewhat more convenient access pattern than SAX
or DOM... I'll definitely check out your ParseResults class before I
try to submit a patch. Thanks!

Steve
Jul 18 '05 #7

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

Similar topics

17
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number....
11
by: westplastic | last post by:
This one is driving me insane. The script works perfect on Firefox, but Internet Explorer keeps complaining about "Error Object Expected" and stuff like that. I've run it through Firefox's Java...
15
by: David Lozzi | last post by:
Howdy, I have a function that uploads an image and that works great. I love ..Nets built in upload, so much easier than 3rd party uploaders! Now I am making a public function that will take the...
4
by: Charles Churchill | last post by:
I apologize if this question has been asked before, but after about half an hour of searching I haven't been able to find an answer online. My code is beloiw, with comments pertaining to my...
13
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an...
2
by: jehugaleahsa | last post by:
Hello: I was reading another post and saw an argument (sort of) that brought up a good question. I have written a fairly large library of algorithms that occur in programming all the time. It...
26
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic...
11
by: Scott Stark | last post by:
Hello, The code below represents a singly-linked list that accepts any type of object. You can see I'm represting the Data variable a System.Object. How would I update this code to use...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
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...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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...

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.