Monday, February 8, 2010

comp.lang.python - 25 new messages in 12 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* Modifying Class Object - 7 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/fd36962c4970ac48?hl=en
* Your beloved python features - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/599b3c9772421ece?hl=en
* timer for a function - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/a52c427850c5ef89?hl=en
* Ternary plus - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/05afedbd6dc66a2c?hl=en
* use strings to call functions - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/87c34eb48790eda2?hl=en
* ANN: obfuscate - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6374e775e474ee1a?hl=en
* Python Logic Map/Logic Flow Chart. (Example Provided) - 2 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/3c3ef3cbc908b872?hl=en
* Socket Error: Permission Denied - 3 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/102aeaff639c7e1d?hl=en
* come and join www.pakdub.com where u can find friends, classifieds, games,
music albums, events, blogs, chatrooms, video songs and lot more.... for free -
1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/26203e65d2a61cac?hl=en
* Tangling with mathplotlib(MPL) on XP and Win7 -- show() stopper - 1 messages,
1 author
http://groups.google.com/group/comp.lang.python/t/84b2f3125d4d3ab6?hl=en
* Python 3: Plist as OrderedDict - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/07b43686e015995c?hl=en
* xml.sax parsing elements with the same name - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6afb5c844891caeb?hl=en

==============================================================================
TOPIC: Modifying Class Object
http://groups.google.com/group/comp.lang.python/t/fd36962c4970ac48?hl=en
==============================================================================

== 1 of 7 ==
Date: Mon, Feb 8 2010 4:44 pm
From: "Alf P. Steinbach"


* alex23:
> "Alf P. Steinbach" <al...@start.no> wrote:
>> Hm. While most everything I've seen at effbot.org has been clear and to the
>> point, that particular article reads like a ton of obfuscation.
>
> Must. Resist. Ad hominem.
>
>> Python passes pointers by value, just as e.g. Java does.
>>
>> There, it needed just 10 words or so. :-)
>
> 10 words _plus_ an understanding of Java.

No, one only needs an understanding of "pointer".

"Pointer" is a mostly language independent concept.

The reference to the Java language spec, where that term is used for this, was
just an unsuccessful attempt to keep out word-play arguments based on the
incompatibility of some incompatible meaning of "pointer"...


Cheers & hth.,

- Alf


== 2 of 7 ==
Date: Mon, Feb 8 2010 9:31 am
From: MRAB


Steven D'Aprano wrote:
> On Mon, 08 Feb 2010 02:51:05 +0100, Alf P. Steinbach wrote:
>
>> Python passes pointers by value, just as e.g. Java does.
>
> How do I get a pointer in pure Python code (no ctypes)? I tried both
> Pascal and C syntax (^x and *x), but both give syntax errors.
>
In Pascal it's x^.

> For that matter, how do I get a pointer in Java code?
>
> If Python doesn't have pointers, then why are you talking about Python
> passing pointers? It's a vacuous truth, like saying that Python passes
> dinosaurs by name.
>

== 3 of 7 ==
Date: Mon, Feb 8 2010 9:33 am
From: MRAB


Alf P. Steinbach wrote:
> * Steve Holden:
>> Alf P. Steinbach wrote:
>>> * Steve Holden:
>> [...]
>>>> Alf:
>>>>
>>>> This topic was discussed at great, nay interminable, length about a
>>>> year
>>>> ago. I'd appreciate it if you would search the archives and read what
>>>> was said then rather than hashing the whole topic over again to
>>>> nobody's
>>>> real advantage.
>>> Well that's my point, and thanks for backing me up on that :-): it's
>>> very simple, and as demonstrated can be expressed in 10 words or less
>>> (plus perhaps a terminology reference, as I did above), so all that
>>> discussion and in particular the lengthy article at effbot serves as
>>> obfuscation and nothing else.
>>>
>> Please don't assume I was trying to support you. Your remarks showed
>> considerable ignorance of issue that were extremely nuanced. Whatever
>> point you were trying to make was lost in your self-aggrandizing
>> disrespect of Fredrik Lundh, a software engineer of some repute with a
>> long history of contribution to Python. The fact that your post was
>> basically a restatement of one of the several competing positions in
>> that thread makes it no more right than any of the others.
>
> What on Earth are you babbling about?
>
> Perhaps next you'll drag in the Pope, saying I've shown him some
> disrespect.
>
> News for you: the Pope ain't participating.
>
[snip]

The Pope isn't (as far as we know) a Pythonista.


== 4 of 7 ==
Date: Mon, Feb 8 2010 6:42 pm
From: Steve Holden


Stephen Hansen wrote:
[...]
> P.S. I couldn't resist. :(
>

And here I was, sitting on my hands ... but someone was wrong on the
Internet, so D'Aprano had to put them right. Your fatal weakness.

Of course this won't make the slightest difference. "'When I use a
word,' said Humpty ..."

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 5 of 7 ==
Date: Mon, Feb 8 2010 7:07 pm
From: MRAB


Stephen Hansen wrote:
> On Mon, Feb 8, 2010 at 6:42 PM, Steve Holden <steve@holdenweb.com
> <mailto:steve@holdenweb.com>> wrote:
>
> Stephen Hansen wrote:
> [...]
> > P.S. I couldn't resist. :(
> >
>
> And here I was, sitting on my hands ... but someone was wrong on the
> Internet, so D'Aprano had to put them right. Your fatal weakness.
>
> Of course this won't make the slightest difference. "'When I use a
> word,' said Humpty ..."
>
>
> This is getting out of hand.
>
> First, someone thought I was you.
>
> Now you think I'm D'Aprano.
>
> I'm just gonna go by Bob for now on.
>
> :)
>
> --B
>
Bruce would be less confusing. :-)


== 6 of 7 ==
Date: Mon, Feb 8 2010 8:01 pm
From: "Alf P. Steinbach"


* Stephen Hansen -> Alf P. Steinbach:
>
> [snip]
> To say, "pass by value" implies things to people. It describes a sort of
> world where I'm a function about to do some work, and on my desk I have
> a series of boxes with names on it. It describes an environment where
> someone comes over and drops something into each of my boxes. The
> contents of these boxes are mine alone!

Then, when the imprecision makes people misunderstand, one should not say that.

One should then be more precise.

One should say /what/ is passed by value.


[snip]

> >>> import copy
> >>> def doit(a):
> ... a += a
> ... return a
> ...
> >>> test1 = 1
> >>> test2 = doit(test1)
> >>> test1
> 1
> >>> test2
> 2
> >>> test3 = [1]
> >>> test4 = doit(test3)
> >>> test3
> [1, 1]
> >>> test4
> [1, 1]
>
> I know you already know this, but the point is: you're -hurting- other
> peoples understanding by using terms like this that don't apply to
> Python's specific nature.

The terms apply very well to Java. And Java has the identical parameter passing
mechanism for class type objects. Hence, the argument is bogus.


Cheers & hth.,

- Alf

PS: I cannot see any of your postings on Usenet. So I just sort of grabbed this
from GMane and posted to Usenet. Hopefully you'll see it back at the list. :-)


== 7 of 7 ==
Date: Mon, Feb 8 2010 8:25 pm
From: Terry Reedy


On 2/8/2010 2:10 PM, Alf P. Steinbach wrote:

> I apologize for assuming that "pointer" is a known word to [c.l.p.]
> denizens.

It is irrelevant.

Python calls Python functions by associating argument objects (or
objects derived therefrom) with paramenter names, very much like
assigment statements.

If one understands Python objects, names, and assignment statements,
which one must to understand Python, this completely explains the
function calls, function execution, and its effect on passed objects.

All Python expressions evaluate to an object. Call expressions evaluate
to the object returned by the function.

Different interpreters implement call and return differently. Certainly,
most humans do not use C pointers when they mentally execute Python code.

Terry Jan Reedy


==============================================================================
TOPIC: Your beloved python features
http://groups.google.com/group/comp.lang.python/t/599b3c9772421ece?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Feb 8 2010 5:31 pm
From: Steven D'Aprano


On Mon, 08 Feb 2010 18:07:56 +0100, mk wrote:

>> Threads are hard, and many people don't use them at all. You might
>> never get an answer, even without alienating people. Complaining after
>> six DAYS might be acceptable, if you do it with a sense of humour, but
>> after six minutes?
>
> Well, it's 4 days now. I would be happy to get 50% response rate.
> Apparently nobody is really using threads.

Please see my response to your post "timer for a function".

--
Steven

==============================================================================
TOPIC: timer for a function
http://groups.google.com/group/comp.lang.python/t/a52c427850c5ef89?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Feb 8 2010 5:36 pm
From: Steven D'Aprano


On Fri, 05 Feb 2010 18:23:09 +0100, mk wrote:

[...]
> On paramiko mailing list I got the suggestion to build a timer and then
> quit this by myself:
>
>> The timeout option in connect() is for the socket, not for the entire
>> operation. You are connected, so that timeout is no longer relevant.
>> You would probably have to wrap the transport.connect() method in a
>> timer to break out of this early.
>
> Question: how can I do that? Use another threaded class? Is there some
> other way?

I don't use threads enough (or at all) to answer that question directly,
but I can point you at these. Hopefully they will help, or at least give
you some ideas:

http://code.activestate.com/recipes/534115/
http://code.activestate.com/recipes/473878/

Found by googling for "python timeout any function".

> Additional snag is SSHClient() is a class that internally uses threads.
> How do I kill brutally its threads? Is there any way to do it?

You can't kill threads in Python. You have to ask them nicely to die.

Google on "python kill thread" for more.


--
Steven

==============================================================================
TOPIC: Ternary plus
http://groups.google.com/group/comp.lang.python/t/05afedbd6dc66a2c?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Feb 8 2010 5:49 pm
From: Steven D'Aprano


On Mon, 08 Feb 2010 21:59:18 +0100, Martin Drautzburg wrote:

> Just for the hell of it ...
>
> I can easily define __plus__() with three parameters. If the last one is
> optional the + operation works as expected. Is there a way to pass the
> third argument to "+"

How do you give three operands to a binary operator? Binary operators
only have two sides, a left and a right, so you can only fit two operands
around them.

Mathematicians solve this problem by using functions:

add(a, b, c, d)

In Python, you can do this:

>>> class F:
... def __add__(self, other, foo=None):
... print self, other, foo
... return 1
...
>>>
>>> F() + 3
<__main__.F instance at 0xb7f06f4c> 3 None
1
>>> F().__add__(3, 4)
<__main__.F instance at 0xb7f06d8c> 3 4
1

but if you do, people will laugh and point at you in the street.

*wink*


--
Steven


== 2 of 2 ==
Date: Mon, Feb 8 2010 6:46 pm
From: Carl Banks


On Feb 8, 12:59 pm, Martin Drautzburg <Martin.Drautzb...@web.de>
wrote:
> Just for the hell of it ...
>
> I can easily define __plus__() with three parameters. If the last one is
> optional the + operation works as expected. Is there a way to pass the
> third argument to "+"

If, for some reason, you wanted to define a type for which it makes
sense to "add" three objects, but not two, you can get the effect you
want, kind of.

(a + b + c) is useful
(a + b) is meaningless

You can have __add__ return a closure for the first addition, then
perform the operation on the second one. Example (untested):

class Closure(object):
def __init__(self,t1,t2):
self.t1 = t1
self.t2 = t2
def __add__(self,t3):
# whole operation peformed here
return self.t1 + self.t2 + t3

class MySpecialInt(int):
def __add__(self,other):
return Closure(self,other)


I wouldn't recommend it. Just use a function call with three
arguments.


Carl Banks

==============================================================================
TOPIC: use strings to call functions
http://groups.google.com/group/comp.lang.python/t/87c34eb48790eda2?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Feb 8 2010 5:51 pm
From: Steven D'Aprano


On Mon, 08 Feb 2010 14:43:46 -0800, Aahz wrote:

>>> WARNING: eval() is almost always the wrong answer to any question
>>
>>warning : it works !
>
> Works for what?

Code injection security bugs, of course.

http://en.wikipedia.org/wiki/Code_injection

It is surprisingly difficult to sanitize strings in Python to make them
safe to pass to eval. Unless you are prepared to trust the input data
explicitly, it's best to just avoid eval.

--
Steven


== 2 of 2 ==
Date: Mon, Feb 8 2010 5:50 pm
From: Jean-Michel Pichavant


Aahz wrote:
> In article <0efe23a6-b16d-4f92-8bc0-12d056bf599d@z26g2000yqm.googlegroups.com>,
> OdarR <olivier.darge@gmail.com> wrote:
>
>> and with eval(), did you try ?
>>
>
> WARNING: eval() is almost always the wrong answer to any question
>
Some say that eval is evil !

JM

==============================================================================
TOPIC: ANN: obfuscate
http://groups.google.com/group/comp.lang.python/t/6374e775e474ee1a?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Feb 8 2010 6:19 pm
From: Tim Chase


Steven D'Aprano wrote:
> obfuscate is a pure-Python module providing classical encryption
> algorithms suitable for obfuscating and unobfuscating text.
>
> obfuscate includes the following ciphers:
> - Caesar, rot13, rot5, rot18, rot47
> - atbash
> - Playfair, Playfair6 and Playfair16
> - Railfence (encryption only)
> - Keyword
> - Affine
> - Vigenere
> - frob (xor)

I prefer the strength of Triple ROT-13 for my obfuscation needs,
but I don't see it listed here. I guess I'll have to roll my own
despite the dire warnings against amateur cryptographers
authoring their own unvetted implementations. ;-)

-tkc


==============================================================================
TOPIC: Python Logic Map/Logic Flow Chart. (Example Provided)
http://groups.google.com/group/comp.lang.python/t/3c3ef3cbc908b872?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Feb 8 2010 6:55 pm
From: Carl Banks


On Feb 8, 12:20 pm, spike <pwashingto...@gmail.com> wrote:
> Has anyone been able to come across a Python logic map or Python logic
> flow chart?
>
> An example can be seen on the right under History:http://en.wikipedia.org/wiki/Usenet#History
>
> This would be very helpful for all users.


Begin
|
|
V
Start Editor
|
|
V
Write Code <----+
| |
| |
V |
Run Python |
| |
| | No.
V |
Did it do what you want?
|
| Yes.
|
V
Stop.


HTH.


Carl Banks


== 2 of 2 ==
Date: Mon, Feb 8 2010 6:57 pm
From: Carl Banks


On Feb 8, 1:35 pm, Gary Herron <gher...@islandtraining.com> wrote:
> spike wrote:
> > Has anyone been able to come across a Python logic map or Python logic
> > flow chart?
>
> > An example can be seen on the right under History:
> >http://en.wikipedia.org/wiki/Usenet#History
>
> > This would be very helpful for all users.
>
> Huh???  What aspect of Python were you thinking of mapping out?
>
> Your example us a bad ascii art graph of -- I've no clue what?

Usenet servers.

Back in the day people had these in their .sigfiles


Carl Banks

==============================================================================
TOPIC: Socket Error: Permission Denied
http://groups.google.com/group/comp.lang.python/t/102aeaff639c7e1d?hl=en
==============================================================================

== 1 of 3 ==
Date: Mon, Feb 8 2010 7:24 pm
From: "W. eWatson"


I'm using IDLE with winxp. It seems every day I get into the Subject
above. Usually, after 5-8 minutes I get past it. A msg appearing at the
same time say, "IDLE's subprocess didn't make connect. ... possible
firewall problem."

A resource for this is <http://bugs.python.org/issue6941>. There a
number of choices. Perhaps the most appealing is:

adgprogramming: first, bring up your task manager and make sure there
are no python processes running. 2.6.x subprocesses can get stuck.
Then make sure that your firewall isn't blocking socket access to
localhost. Then restart IDLE. IDLE 3.1.1 may work for you since it
has the recent enhancement that allows multiple copies of IDLE to run
simultaneously, but it still needs interprocess access via sockets.

How would I know the which Python processes or subprocesses are running?
I can kill the main one, but that seems to do no good.
pythonw.exe.

Comments?


== 2 of 3 ==
Date: Mon, Feb 8 2010 7:38 pm
From: "W. eWatson"


On 2/8/2010 7:24 PM, W. eWatson wrote:
> I'm using IDLE with winxp. It seems every day I get into the Subject
> above. Usually, after 5-8 minutes I get past it. A msg appearing at the
> same time say, "IDLE's subprocess didn't make connect. ... possible
> firewall problem."
>
> A resource for this is <http://bugs.python.org/issue6941>. There a
> number of choices. Perhaps the most appealing is:
>
> adgprogramming: first, bring up your task manager and make sure there
> are no python processes running. 2.6.x subprocesses can get stuck.
> Then make sure that your firewall isn't blocking socket access to
> localhost. Then restart IDLE. IDLE 3.1.1 may work for you since it
> has the recent enhancement that allows multiple copies of IDLE to run
> simultaneously, but it still needs interprocess access via sockets.
>
> How would I know the which Python processes or subprocesses are running?
> I can kill the main one, but that seems to do no good.
> pythonw.exe.
>
> Comments?
I'm using McAffee. I see it was pythonw.exe blocked in red. There are
several choices: Allow Access, Allow Outboubnd only
Block (current), Remove Prgrm permission, Learn More.

Outbound only seem reasonable, but why does the blocking keep returning
every many hours, or maybe when I reboot, which I've done several times
today?


== 3 of 3 ==
Date: Mon, Feb 8 2010 7:45 pm
From: "W. eWatson"


I decided to go with outbound. Now when I run the program, I get a long
of messabge about deprecations and NumpyTest will be removed in the
next release. please update code to nose or unittest.


==============================================================================
TOPIC: come and join www.pakdub.com where u can find friends, classifieds,
games, music albums, events, blogs, chatrooms, video songs and lot more....
for free
http://groups.google.com/group/comp.lang.python/t/26203e65d2a61cac?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Feb 8 2010 7:38 pm
From: babu lohar


come and join www.pakdub.com where u can find friends,
classifieds, games, music albums, events, blogs, chatrooms, video
songs and lot more.... for free

==============================================================================
TOPIC: Tangling with mathplotlib(MPL) on XP and Win7 -- show() stopper
http://groups.google.com/group/comp.lang.python/t/84b2f3125d4d3ab6?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Feb 8 2010 7:53 pm
From: "W. eWatson"


I'm doing most of this on a win7 machine. When I installed MPL, I had
two small dialogs appear that said something was missing, but I pressed
on. MPL seemed to generally work except for the show() problem. When it
was to be executed to show the output of plot(x,y), it did just that;
however, the shell window hung, and I had to upper right corner x my way
out of it--2 to 3 steps. The plot window and program easily went the
same way. IDLE is the tool of choice on both machines.

I'm in the process of bringing programs from my XP to the win7 machine,
and on the XP machine I decided to start using MPL with a 900 line Py
program that I'm revising. I had gotten stuck with the very same problem
there. However, last night I realized someone had added a MPL plot to it
years ago, and it does not fail on show(). I've put print stmts after
show() in the big program, but nothing is printed in either case when I
close the plot window. Tried in IDLE and executing from clicking on the
py file in its folder.

I brought some of this up on the MPL mailing list, and one respondent
said he had tried some of the examples with show(), and they had worked.

I noticed the dialog msgs mentioned above, and thought I made a mistake
in not installing numpy first, so tried to figure out a way to do it.
Three posts on different forums did not provide an answer. I
accidentally found the author of MPL's hidden away in one of MPL files.
He said it didn't make a difference and asked me not to use his address.
I though the warning msgs might be of interest to him, so wrote to him.
He had blocked me. Perhaps I need to file a bug report to get his
attention on that.

Anyway, I'm now stalled on the development of the big program. It's
possible this is an IDLE problem, but I ran the big program with a click
on the file, and the black window showed the same problem. This is all
on XP Pro.

I'm going to copy the two code segments here. Maybe someone can see a
difference.

=================OLD working code============
def light_curve( self ):
result = []
test = 1
for tup in self.subimages:
left,top,subimage = tup
total = 0
avg_total = 0
if (test == 1):
box = (left, top, left+128, top+128)
region = self.reference_image.crop(box)
self.reference_image.paste(subimage, box)
test = 2
else:
for x in range(left+43,left+82):
for y in range(top+43, top+82):
avg_total = avg_total +
self.reference_image.getpixel((x, y))
for x in range(43,82): #take the center 40 X 40 pixel
block
for y in range(43,82):
v = subimage.getpixel((x, y))
total = total + v
#for x in range(left, left+127):
# for y in range(top, top+127):
# avg_total = avg_total +
self.reference_image.getpixel((x, y))
#for x in range(0, 127):
# for y in range(0, 127):
# total = total + subimage.getpixel((x, y))
result.append(total - avg_total) #(average -
background average) gives pixel intensity above the background)
plotting_x = range(2, len(result)+2)
plot(plotting_x, result)
xlabel('Frame #')
ylabel('Pixel count above background count')
title('Light curve for selected subplot')
show()

===========New Code with show problem
def get_point_trail_stats(self): # Simple track statistics
xy = array(self.xya)[:,0:2] # creates a two column array for x,y
pt2pt_dist = []
pt_dist = []
for k in arange(0,len(xy)-1):
distance = sqrt((xy[k+1,0]-xy[k,0])**2 +
(xy[k+1,1]-xy[k,1])**2)
pt_dist.append(distance)
# wtw print "k ",k, (xy[k,0], xy[k,1]), " distance: ",
distance
# wtwfor k in arange(0, len(xy)-50):
# wtw print "k: %3i dist: %6.2f (x,y) (%4.1f,%4.1f)" % (k,
pt_dist[k], xy[k,0], xy[k,1])
per_tile25 = stats.scoreatpercentile(pt_dist,25.0)
per_tile50 = stats.scoreatpercentile(pt_dist,50.0)
per_tile75 = stats.scoreatpercentile(pt_dist,75.0)
mean = stats.mean(pt_dist)
std = stats.std(pt_dist)
#sys.exit()
amin = min(pt_dist)
amax = max(pt_dist)
print " mean: %7.2f std: %7.2f min: %7.2f max: %7.2f" %
(mean, std, amin, amax)
print " quartiles (25-per: %7.2f, 50-per: %7.2f, 75-per:
%7.2f): " % (per_tile25, per_tile50, per_tile75)
#print " Extended stats"
#print " min: %7.2f max: %7.2f mean: %7.2f std: %7.2f" % \
# (min, max, mean, std)
#print " p25: %7.2f p50: %7.2f p75: %7.2f" % (per_tile25,
per_tile50, per_tile75)
trk_stats = (amin, amax, mean, std, per_tile25, per_tile50,
per_tile75)
fig = figure()
ax1 = fig.add_subplot(111)
v = (0, 640, 0, 480)
print "shapes: ", xy[:,0].shape, xy[:,1].shape
fig.close()
ax1.plot(xy[:,0], xy[:,1]) #,100*s, c , picker=True)
ax1.axis(v)
#x = (0,1,3,20,20);y=(5,7, 9, 22,90)
#col = ax1.plot(x,y)
show()

print "something for wtw plot"
print
return trk_stats

==============================================================================
TOPIC: Python 3: Plist as OrderedDict
http://groups.google.com/group/comp.lang.python/t/07b43686e015995c?hl=en
==============================================================================

== 1 of 3 ==
Date: Mon, Feb 8 2010 8:02 pm
From: Gnarlodious


I am trying to read a *.plist into Python 3's OrderedDict but can't
figure it out. Saying something like this:

from plistlib import readPlist
dict=readPlist('/path/file.plist')
--> arbitrarily ordered dictionary compared to the XML file

from collections import OrderedDict
OrderedDict(readPlist('/path/file.plist'))
--> essentially does the same thing as the previous
readPlist seems to do the scrambling, is this a non-implementation in
Python 3.1?

I "upgraded" to Py3 to have OrderedDict, so please don't say it is
impossible...

-- Gnarlie


== 2 of 3 ==
Date: Mon, Feb 8 2010 8:17 pm
From: Ben Finney


Gnarlodious <gnarlodious@gmail.com> writes:

> from plistlib import readPlist
> dict=readPlist('/path/file.plist')
> --> arbitrarily ordered dictionary compared to the XML file

Right. The items in a dict are unordered, and when serialised to a list
they will appear in an arbitrary, unpredictable order.

>>> foo = dict(
... [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
>>> foo
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

> from collections import OrderedDict
> OrderedDict(readPlist('/path/file.plist'))
> --> essentially does the same thing as the previous

Yes, because you are initialising an OrderedDict instance from a dict.
That accesses the dict items as an iterable, which of course is going to
retrieve the items in an arbitrary, unpredictable order.

>>> foo.items()
dict_items([('a', 1), ('c', 3), ('b', 2), ('e', 5), ('d', 4)])

The OrderedDict then faithfully remembers the arbitrary ordering of the
items.

>>> from collections import OrderedDict
>>> OrderedDict(foo.items())
OrderedDict([('a', 1), ('c', 3), ('b', 2), ('e', 5), ('d', 4)])

> readPlist seems to do the scrambling

Nothing "does" the scrambling; the order is forgotten by the dict as
soon as the items go in.

> I "upgraded" to Py3 to have OrderedDict, so please don't say it is
> impossible...

What you'll need to do is insert the items into the OrderedDict instance
in the desired order. You will, of course, need to define what that
desired order is.

>>> sorted(foo.items(), key=(lambda item: item[0]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
>>> OrderedDict(sorted(foo.items(), key=(lambda item: item[0])))
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

--
\ "When we talk to God, we're praying. When God talks to us, |
`\ we're schizophrenic." —Jane Wagner, via Lily Tomlin, 1985 |
_o__) |
Ben Finney


== 3 of 3 ==
Date: Mon, Feb 8 2010 8:21 pm
From: Benjamin Kaplan


On Mon, Feb 8, 2010 at 11:02 PM, Gnarlodious <gnarlodious@gmail.com> wrote:
> I am trying to read a *.plist into Python 3's OrderedDict but can't
> figure it out. Saying something like this:
>
> from plistlib import readPlist
> dict=readPlist('/path/file.plist')
> --> arbitrarily ordered dictionary compared to the XML file
>
> from collections import OrderedDict
> OrderedDict(readPlist('/path/file.plist'))
> --> essentially does the same thing as the previous
> readPlist seems to do the scrambling, is this a non-implementation in
> Python 3.1?
>
> I "upgraded" to Py3 to have OrderedDict, so please don't say it is
> impossible...
>
> -- Gnarlie

readPlist returns a dict. That dict is unordered. Wrapping the call in
OrderedDict() doesn't suddenly make readPlist use an ordered dict
instead, it just takes the (unordered) dict and sticks it in a new
OrderedDict. I suppose you could dig into the plistlib source code and
change that to use the OrderedDict if you really need it.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

==============================================================================
TOPIC: xml.sax parsing elements with the same name
http://groups.google.com/group/comp.lang.python/t/6afb5c844891caeb?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Feb 8 2010 8:40 pm
From: dontcare


If you are using jython, then you might also want to consider VTD-XML,
which is
a lot easier to use and faster than SAX, native XPath support may be
useful too

http;//vtd-xml.sf.net

On Jan 12, 12:13 am, Stefan Behnel <stefan...@behnel.de> wrote:
> amadain, 11.01.2010 20:13:
>
>
>
>
>
> > I have an event log with 100s of thousands of entries with logs of the
> > form:
>
> > <event eventTimestamp="2009-12-18T08:22:49.035"
> > uniqueId="1261124569.35725_PFS_1_1340035961">
> >    <result value="Blocked"/>
> >       <filters>
> >           <filter code="338" type="Filter_Name">
> >               <diagnostic>
> >                    <result value="Triggered"/>
> >               </diagnostic>
> >           </filter>
> >           <filter code="338" type="Filter_Name">
> >               <diagnostic>
> >                    <result value="Blocked"/>
> >               </diagnostic>
> >           </filter>
> >       </filters>
> > </event>
>
> > I am usingxml.saxto parse the event log.
>
> You should give ElementTree's iterparse() a try (xml.etree package).
> Instead of a stream of simple events, it will give you a stream of
> subtrees, which are a lot easier to work with. You can intercept the event
> stream on each 'event' tag, handle it completely in one obvious code step,
> and then delete any content you are done with to safe memory.
>
> It's also very fast, you will like not loose muchperformancecompared toxml.sax.
>
> Stefan- Hide quoted text -
>
> - Show quoted text -

==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate