Please help me understand this code....
Hello, I am a programmer, but not a python guy. So I am a little confused with the following python code. Specifically what does the ":" do in the array arithmetic? new_page = map[opage] old_page = map[opage^1] center = new_page[1:-1,1:-1] origcenter = array(center) center[:] = old_page[2:,2:] center += old_page[1:-1,2:] center += old_page[:-2,2:] center += old_page[2:,1:-1] center += old_page[:-2,1:-1] center += old_page[2:,:-2] center += old_page[1:-1,:-2] center += old_page[:-2,:-2] center >>= 2 center -= origcenter center -= (center>>density) Thanks!! Randy -- http://mail.python.org/mailman/listinfo/python-list
Re: When should I use "parent=None" in __ini__ and "parent" in super()
Those are contradictory for what you are trying to accomplish unless it is a
Parent - Child relationship (MainWindow - Window):
When you super() an object, it enherits all the properties from its parent
object.
Source:
https://www.w3schools.com/python/python_inheritance.asp
If what you want is 2 windows, you can define 2 instances of both Classes and
run both at the end.
```
class User1(object):
def __init__(self, fname, age, parent=None):
self.fname = fname
self.age = int(age)
# Calling the return function that prints the details
self.return_user()
def return_user(self):
print(self.fname)
print(self.age)
class User2(object):
def __init__(self, lname, height, parent=None):
self.lname = lname
self.height = float(height)
self.return_user()
def return_user(self):
print(self.lname)
print(self.height, "CM")
print((self.height / 2.54), "IN")
User1("Hugh", 21)
User2("Janus", 175.26)
```
--
https://mail.python.org/mailman/listinfo/python-list
how best to split into singleton and sequence
>>> l = []
>>> s = 'a|b'
>>> t, l = s.split('|')
>>> t
'a'
>>> l
'b'
>>> s = 'a|b|c|d'
>>> t, l = s.split('|')
Traceback (most recent call last):
File "", line 1, in ?
ValueError: too many values to unpack
>>>
so, i imagine what is happening is the lhs, t,l, is really
(t, (l)), i.e. only two items.
so how should i have done this readably and simply?
randy
--
http://mail.python.org/mailman/listinfo/python-list
Re: What is Expresiveness in a Computer Language?
Keith Thompson wrote (in article <[EMAIL PROTECTED]>): >\/| |\| __\,,\ /,,/__ > \||/ | | | jgs (__Y__) > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ > == Out of curiosity, does anyone remember who 'jgs' refers to above? -- Randy Howard (2reply remove FOOBAR) -- http://mail.python.org/mailman/listinfo/python-list
dict duplicity
a dict written as pKey = (prefix, pLen, origin) val = dict.get(pKey) if val == None: dict[pKey] = (timeB, timeB) else: if val[0] > timeB: val[0] = timeB if val[1] < timeB: val[1] = timeB dict[pKey] = val and read back as for pKey, pVal in dict.iteritems(): print \ pKey[0], hash(pKey[0]), \ pKey[1], hash(pKey[1]), \ pKey[2], hash(pKey[2]), \ "hash=", hash(pKey), \ pVal[0], hash(pVal[0]), \ pVal[1], hash(pVal[1]) when run with | sort, produces 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 917088000 917088000 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 917088000 917088000 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 917088000 917088000 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 917088000 917088000 12.0.0.0 -2054516913 9 -1293912648 7018 329707286 hash= -1578430040 917088000 917088000 917088000 917088000 12.0.0.0 -2054516913 9 -1293912648 7018 329707286 hash= -1578430040 917088000 917088000 917088000 917088000 not that there are two entries with the same hash= i am utterly confused randy -- http://mail.python.org/mailman/listinfo/python-list
Re: dict duplicity
>> a dict written as
>>
>>pKey = (prefix, pLen, origin)
>>
>>val = dict.get(pKey)
>>if val == None:
>> dict[pKey] = (timeB, timeB)
>>else:
>> if val[0]> timeB: val[0] = timeB
>> if val[1] < timeB: val[1] = timeB
>> dict[pKey] = val
>>
>> and read back as
>>
>>for pKey, pVal in dict.iteritems():
>> print \
>> pKey[0], hash(pKey[0]), \
>> pKey[1], hash(pKey[1]), \
>> pKey[2], hash(pKey[2]), \
>> "hash=", hash(pKey), \
>> pVal[0], hash(pVal[0]), \
>> pVal[1], hash(pVal[1])
>>
>> when run with | sort, produces
>>
>> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000
>> 917088000 917088000
>> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000
>> 917088000 917088000
>> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000
>> 917088000 917088000
>> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000
>> 917088000 917088000
>> 12.0.0.0 -2054516913 9 -1293912648 7018 329707286 hash= -1578430040
>> 917088000 917088000 917088000 917088000
>> 12.0.0.0 -2054516913 9 -1293912648 7018 329707286 hash= -1578430040
>> 917088000 917088000 917088000 917088000
>>
>> not that there are two entries with the same hash=
>>
>> i am utterly confused
>>
>> randy
>>
> I'm not sure I got your question but having the same hash(key) is not
> having the same key for a dict.
>
> >>> {-1:0,-2:0}
> {-2: 0, -1: 0}
> >>> hash(-1)!=hash(-2)
> False
>
> A key lookup in a dict involve real keys comparisons via '==' among the
> keys of the bin identified by the hash of the key.
ack. my point was the key touple and its hash are identical for
each pair of entries.
i executed the write section 55953 times. the iteritems gets me
111906 entries.
while it did not charge extra, it kinda spoils my code :-)
randy
--
http://mail.python.org/mailman/listinfo/python-list
Re: dict duplicity
> Firstly, to remove one possible source of confusion, change the name of > your dictionary ... "mydict" or "fred" ... anything but "dict" > > Next, after you have created the dictionary and added items to it, do this: > print len(fred) > print len(fred.items()) > nitems = 0 > for k, v in fred.iteritems(): > nitems += 1 > print nitems > > If by this stage you haven't worked out what you are doing wrong, post > an exact copy/paste of the MINIMAL code that exhibits the "multiple > instances of same key in .iteritems()" problem i did not work out what i was doing wrongly. but now it works. i hate ing magic! but thanks for making me permute. randy -- http://mail.python.org/mailman/listinfo/python-list
Re: loop in python
computers are cheap. i am expensive. give me clear and maintainable code every time. randy -- http://mail.python.org/mailman/listinfo/python-list
list insertion
i am trying to insert into a singly linked list hold = self.next self.next = DaClass(value) self.next.next = hold but i suspect (from print statement insertions) that the result is not as i expect. as the concept and code should be very common, as i am too old for pride, i thought i would ask. mahalo, randy -- http://mail.python.org/mailman/listinfo/python-list
Re: list insertion
>> hold = self.next >> self.next = DaClass(value) >> self.next.next = hold > shouldn't that last line be this? > self.next.prev = hold single threaded list > What did you expect, and what did you ovserve? i will try to distill a case randy -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
i left the usenet in the latter half of the '80s. a few weeks ago i decided i wanted to do a new project with a new language, and chose python. so i joined this mailing list, which is gated to the usenet. i am impressed that the s:n has not gotten significantly worse than when i left, about 0.25, this message being my contribution to the noise. the s here is pretty darn good. but the n is pretty silly. randy -- http://mail.python.org/mailman/listinfo/python-list
Re: need a little help with time
i am doing disgusting looking junk based on calendar. example
now = calendar.timegm(time.gmtime())
aWeek = 7*24*60*60
print time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(now + aWeek))
randy
--
http://mail.python.org/mailman/listinfo/python-list
Re: Experience regarding Python tutorials?
> There is also a python tutor newsgroup at gmane > (gmane.comp.python.tutor). is there a mailing list to which it is gated? randy -- http://mail.python.org/mailman/listinfo/python-list
Re: list insertion
>>hold = self.next >>self.next = DaClass(value) >>self.next.next = hold >> >> but i suspect (from print statement insertions) that the result >> is not as i expect. as the concept and code should be very >> common, as i am too old for pride, i thought i would ask. > I think you're fine. indeed. the bug was elsewhere. i got confused and tried to look-ahead too far when i could have just recursed. i threw away the too-clever code and replaced it with one line. i love it when that happens. randy -- http://mail.python.org/mailman/listinfo/python-list
trictionary?
i have some code which looks kinda like
bin = {}
for whatever:
for [a, b] in foo:
x = 42 - a
y = 42 - b
if bin.has_key(x):
bin[x] += 1
else:
bin[x] = 1
for i, j in bin.iteritems():
print i, j
now i want to add a second count column, kinda like
bin = {}
for whatever:
for [a, b] in foo:
x = 42 - a
if bin.has_key(x):
bin[x.b] += 1
else:
bin[x.b] = 1
bin[x.not b] = 0
for x, y, z in bin.iteritems():
print x, y, z
should the dict value become a two element list, or is
there a cleaner way to do this?
randy
--
http://mail.python.org/mailman/listinfo/python-list
Re: trictionary?
>> bin = {}
>> for whatever:
>>for [a, b] in foo:
>>x = 42 - a
>>if bin.has_key(x):
>> bin[x.b] += 1
>>else:
>> bin[x.b] = 1
>> bin[x.not b] = 0
>> for x, y, z in bin.iteritems():
>>print x, y, z
>>
>> should the dict value become a two element list, or is there a
>> cleaner way to do this?
> It would probably help if you explained what the real problem is
> you're trying to solve.
actually, that code fragment was meant to do that. it's pretty much
what i needed to do at that point, just the variable names made
simple.
> Using a two element list to store a pair of counts has a bad code
> smell to me.
exactly. which is why i was asking.
> That said, you could write your code something like:
> bin = {}
> for whatever:
> # NOTE: brackets are unnecessary
> for a, b in foo:
> x = 42 - a
># NOTE: 'in' is generally faster than has_key()
> if x in bin
>bin[x][0] += 1
> else:
> bin[x] = [1, 0]
> # NOTE: extra parens necessary to unpack count list
> for x, (y, z) in bin.iteritems():
> print x, y, z
so, to do this using the real names, it looks like
for [start, end, AS, full] in heard:
week = int((start-startDate)/aWeek)
if week in bin:
if full:
bin[week][0] += 1
else:
bin[week][1] += 1
else:
if full:
bin[week] = [1, 0]
else:
bin[week] = [0, 1]
...
for i, (j, k) in bin.iteritems():
if j == 0:
print str(i) + ",," + str(k)
elif k == 0:
print str(i) + "," + str(j)
else:
print str(i) + "," + str(j) + "," + str(k)
which is still pretty darned grotty and unexpressive. of course,
i could be a bit more obscure and do
if week in bin:
bin[week][not full] += 1
else:
bin[week] = [ full, not full ]
except i probably have to coerce the types or something. less
code but less obvious.
randy
--
http://mail.python.org/mailman/listinfo/python-list
Re: trictionary?
> bin = {}
> for start, end, AS, full in heard:
>week = int((start-startDate)/aWeek)
>counters = bin.setdefault(week, [0, 0])
>if full:
> counters[0] += 1
>else:
> counters[1] += 1
yes! thanks!
> Using an idea you used earlier, you could get smaller code by saying:
> for start, end, AS, full in heard:
>week = int((start-startDate)/aWeek)
>counters = bin.setdefault(week, [0, 0])
>counters[not full] += 1
> Or
> for start, end, AS, full in heard:
>week = int((start-startDate)/aWeek)
>bin.setdefault(week, [0, 0])[not full] += 1
> Or even
> for start, end, AS, full in heard:
> bin.setdefault(int((start-startDate)/aWeek), [0, 0])[not full] += 1
as you say, too clever.
> Using lists to represent structs is perfectly fine if the list doesn't
> live longer than about one screen of code.
i can definitely see that. in last weeks installment, i buried a
complex trinary tree in a class.
thanks for the advice!
randy
--
http://mail.python.org/mailman/listinfo/python-list
Re: trictionary?
> So I'm going to try to pump you for a little more information here. Is > your goal to count, for each week, how many times it's "full" and how > many times it's "not full"? What do you use the counts for? What does > "full" mean? Is it always a 0 or 1? What's the importance of the > output formatting? 'full' is boolean. it says whether a particular bgp announcement was for the entire ip address allocation, or is a longer prefix. e.g., if an allocation was for 666.42.0.0/16 and we heard a bgp announcement for 666.42.1.0/24 that is !full, while an announcement for the prefix 666.42.0.0/16 is full. you asked :-) > for start, end, AS, full in heard: > week = int((start-startDate)/aWeek) > if week in bin: > bin[week][not full] += 1 > else: > # I'm assuming "full" takes the values 0 or 1 > # but if not, you can coerce it with bool() > bin[week] = [full, int(not full)] hmmm. this also reads well. as an old pascal and modula-2 bondage and discipline type, i gotta say is it a breath of fresh air to be in a language and community which care about how code reads more than how clever it is. randy -- http://mail.python.org/mailman/listinfo/python-list
Re: Arguement error
> I am wondering why I am getting this error. when I try to run a script. > TypeError: translate() takes at most 3 arguments (10 given) > but the thing is the method translate actually accepts 10 arguements. without code, how is anyone to know? -- http://mail.python.org/mailman/listinfo/python-list
Re: OpenSource documentation problems
> I'm very sorry to say, that the Python doc is one of the worst possible > in the industry. you are entitled to a full refund -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] Tkinter Question
In article , [email protected] says... [snip] > Anyway, I am happy with the outcome even though I have > not found a way to detect when the program is force > killed. It is unlikely that would ever occur as long When your peogram starts, have it create a small file. As part of your graceful shutdown, delete the file. Any subsequent processes can test for the existence of the file; if it exists, your program did not exit gracefully. --- news://freenews.netfront.net/ - complaints: [email protected] --- -- https://mail.python.org/mailman/listinfo/python-list
2.7.9: PhotoImage get/put
I'm writing a simple image manipulation
on a PhotoImage (tkinter), and running
into an odd problem. The code below works,
except for one thing:
As the image is scanned, I'd like to
observe the pixels getting inverted on
the image (as a kind of progress bar).
What happens is that the code runs the
complete loop before refreshing the
photo. I've tried various forms of
refresh(), update(), etc., within the
loop, but so far no luck. Am I
missing something simple?
def process(): # Ordinarily this would be process(photo,wdth,hgt)
global wdth # but I ran into problems calling it from a button
global hgt #command with parameters...
global photo # the PhotoImage displayed by the calling code
# indents set to 1 to avoid word wrap
# Loop through rows and columns of the image
v=wdth
z=0
a=-1
for y in range (0,hgt):
w=v
v=z # swap v and z so rows are scanned l/r r/l l/r
z=w
a=-a # set our inc/dec step for lr->rl scan
for x in range(v,z,a):
pix = photo.get(x,y) if pix == u'0 0 0' :
#pixel_turn_on()
photo.put("#%02x%02x%02x" % (255,255,255), (x,y))
else:
#pixel_turn_off()
photo.put("#%02x%02x%02x" % (0,0,0), (x,y))
--- news://freenews.netfront.net/ - complaints: [email protected] ---
--
https://mail.python.org/mailman/listinfo/python-list
Re: 2.7.9: PhotoImage get/put
In article , [email protected] says... [snip] > If you want to pass arguments to a command called when a button is > clicked, you have to use 'lambda' in tkinter. Thanks. I just skimmed over lambda before now... > You can't expect a delay to happen during the mainloop() of the > program. To interrupt the mainloop(), use: parent.after(n,someCommand) > Where 'n' is some amount of milliseconds. Just have the parent widget > or the root frame call it. When I read your post, I realized I'm doing a crude animation. After a bit of searching on 'python canvas animation', I found a reference to how it's done: I made my 'root' Tk instance global, and call root.update_idletasks() after the .put It works great! Now back to the lambdas (Ralph the Wonder Lambda, Earl J Lambda, Mike Q Lambda III, et al?). --- news://freenews.netfront.net/ - complaints: [email protected] --- -- https://mail.python.org/mailman/listinfo/python-list
Re: 2.7.9: PhotoImage get/put
In article , [email protected] says... [snip] > I have no idea why, but here are some ideas I'd try out. > So is it refreshing upon completion of the loop, or upon exit from > process()? It turns out I need to call root.update_idletasks() for my root Tk object to get it to refresh after I put the pixel. It works great now. --- news://freenews.netfront.net/ - complaints: [email protected] --- -- https://mail.python.org/mailman/listinfo/python-list
Re: 2.7.9: PhotoImage get/put
In article , [email protected] says... [snip] > > I made my 'root' Tk instance global, and > > call root.update_idletasks() after the > > .put > I did not see the original post, but the alternative way to animate is > to use root.after(milliseconds, callback, *args) at the end of callbacks > to allow the event loop to process other events before re-calling the > same or another callback. I could see that being useful for creating a steady frame rate in longer animations. I'll put that one in my Python toolbox as well. --- news://freenews.netfront.net/ - complaints: [email protected] --- -- https://mail.python.org/mailman/listinfo/python-list
Redirecting both stdout and stderr to the same file
Can stdout and stderr be redirected to the same file? I would like to redirect both to the same file but I'm not sure how to do it. Currenting I'm redirectiong stdout using the following code:
saveout = sys.stdout fsock = open('runtime.log', 'w') sys.stdout = fsock
The problem is that when en error occurs that my program was not written to handle that error message is being sent to the cmd window and not my log file. My program may simply need to be more robust however I'm still a python novice.
Thanks
--
http://mail.python.org/mailman/listinfo/python-list
Python 2.4 online certification - new items available for Beta testing
There is a free Beta test of a Python 2.4 Certification test available at Brainbench.com. They are a provider of skills-based certification exams. Go to the link below to find the test. It is free to take the test. http://www.brainbench.com/xml/bb/common/testcenter/betatests.xml -- http://mail.python.org/mailman/listinfo/python-list
Maintaining leading zeros with the lstrip string function?
I need just the file name from a string containing the path to a file. The name of the file starts with zeros. This is problematic because the lstrip function strips them leaving this as the result: 6128.jpg How do I strip the path without losing the leading zeros in the file name? ―- import sys, os, win32com.client, string teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg' print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\') -- http://mail.python.org/mailman/listinfo/python-list
RE: Maintaining leading zeros with the lstrip string function?
Thanks for the basename suggestion. That almost works. I'm running into a problem with some of the directory names when they include \800x\ see below. ―- import sys, os, string teststring = 'C:\shoreline\dvd\prep area\800x\060623_1.jpg' print os.path.basename(teststring) ―- Results in 800x0623_1.jpg But it needs to be 060623_1.jpg -- http://mail.python.org/mailman/listinfo/python-list
Translating Event.time from pyhook
I use pyhook to monitor user usage of keyboard and mouse. According to pyhook specs, event.time hold the number of seconds since the epoch. However, when I use the example source code I get numbers like 358054093, which translates to 07 May 1981.. Can anyone explain to me what am I doing wrong? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
TkInter: Problem with propagation of resize events through geometry manager hierarchy?
Hi! I'm looking for help with a Tkinter program's handling of resize.
I'm trying to do a fairly simple widget that shows a cropped part of a
larger image, and let's you navigate within the larger image through a
variety of methods. The widget hierarchy is:
root
ImageWidget (my class)
Label (contains the image)
Horizontal Scroll Bar
Vertical scroll bar
The cropping and scrolling works fine. But when I try to add
responding to resize events, I get into trouble. Specifically:
* When I naively change the size of the image shown to be borderwidth
less than the size indicated in the configure event, the size of the
image shown grows gradually but inexorably when I start the test
app. (Sorta scary, actually :-})
* When I fiddle a bit to figure out what the actual difference in size
is between the Configure event and the image that can be displayed,
I get a vibrating, jagged display of the image.
Investigation suggests that multiple configure events are hitting the
label in response to each user resize with different sizes. I'm
guessing that when I resize the image in response to those different
events, that creates new resize events propagating through the window
manager hierarchy, which creates new configure events, which means my
handler changes the image size, which ... you get the idea. However,
everything seems to work fine if I leave out the scroll bars and just
have a label in a frame inside the root window; the image resizes
fine. If the scroll bars are in place but I don't have the image
resize bound to the configure event, I get two sets of resize events
propagaing through the system on startup; without, I just get one.
Event lists and code included below. Any help would be appreciated.
Thanks!
-- Randy Smith
-- Event list on startup with scroll bars:
: width height
root : 220 220
root : 1 1
iwidget : 220 220
root : 220 220
vscroll : 16 204
root : 16 204
hscroll : 204 16
root : 204 16
ilabel : 204 204
root : 204 204
vscroll : 15 205
root : 15 205
hscroll : 205 15
root : 205 15
ilabel : 205 205
root : 205 205
root : 219 219
ilabel : 205 205
root : 205 205
hscroll : 205 15
root : 205 15
vscroll : 15 205
root : 15 205
iwidget : 219 219
root : 219 219
vscroll : 15 204
root : 15 204
hscroll : 204 15
root : 204 15
ilabel : 204 204
root : 204 204
-- Event list on startup without scroll bars
root : 204 204
root : 1 1
iwidget : 204 204
root : 204 204
ilabel : 204 204
root : 204 204
-- Code, without image resize. If you want to see the vibration,
uncomment the line
self.label.bind("", self.reconfigure, "+")
To actually run it you'll need an image "test.tiff" in the current
directory (any image of size > 200x200 will do) and access to the
python imaging library (PIL), but I hope the code is pretty clear
(other than the math transforming between various coordinate
systems, which I don't believe is relevant; focus on
reconfigure(), refresh, and __init__).
#!/usr/bin/python
import traceback
from Tkinter import *
from PIL import Image
import ImageTk
debug = 4
def display_args(*args):
print "Args: ", args
def display_event(event):
print event.__dict__
def display_tag_and_size(tag, event):
print tag, ": ", event.width, event.height
class NotYetImplemented(Exception): pass
def mapnum(x, fromrange, torange):
assert fromrange[0] <= x < fromrange[1], (fromrange[0], x,
fromrange[1])
assert torange[0] < torange[1], (torange[0], torange[1])
## Need to force floating point
x *= 1.0
return (x - fromrange[0]) / (fromrange[1] - fromrange[0]) *
(torange[1] - torange[0]) + torange[0]
class ImageWidget(Frame):
def __init__(self, parent, gfunc, image_size,
starting_zoom=1,
starting_ul=(0,0),
starting_size = None):
"""Create an Image Widget which will display an image based
on the
function passed. That function will be called with the
arguments
(zoom_factor, (xstart, xend), (ystart, yend)) and must return a
TkInter PhotoImage object of size (xend-xstart, yend-ystart).
IMAGE_SIZE describes the "base size" of the image being
backed by
gfunc.
starting_* describes the starting window on the image."""
## Default starting size to whole image
if not starting_size: starting_size = image_size
## Init parent
Frame.__init__(self, parent)
self.bind("",
lambda e, t="iwidget": display_tag_and_size(t, e))
## Base image parameters
self.generator_func = gfunc
self.isize = image_size
## Modifier of base image size for coords currently working in
self.zoom = starting_zo
__init__ vs. __del__
Hi, I was reading a book on Python-3 programming recently and the book stated that, while there is an __init__ method for initializing objects, there was a __del__ method but the __del__ method is not guaranteed to be called when an object is destroyed. If there is code in the __init__ method that allocates resources (memory, file opens, etc.), how do these resources get cleaned up when an object is destroyed? Custom method? At the moment, this architecture seems a bit asymmetric if the __del__ method is not called. Thanks, Randy -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ vs. __del__
There are a number of use-cases for object "cleanup" that are not covered by a generic garbage collector... For instance, if an object is "caching" data that needs to be flushed to some persistent resource, then the GC has no idea about this. It seems to be that for complex objects, clients of these objects will need to explictly call the objects "cleanup" routine in some type of "finally" clause, that is if the main "thread" of execution is some loop that can terminate either expectedly or unexpectedly Relying on a generic GC is only for simple object cleanup...at least based on what I've read so far. Someone mentioned a "context manager" earlier...I may see what this is about as well, since I'm new to the language. Thanks! Randy From: Albert Hopkins To: [email protected] Sent: Saturday, March 21, 2009 6:45:20 PM Subject: Re: __init__ vs. __del__ On Sat, 2009-03-21 at 17:41 -0700, Randy Turner wrote: > Hi, > > > I was reading a book on Python-3 programming recently and the book > stated that, while there is an __init__ method for initializing > objects, there was a __del__ method but the __del__ method is not > guaranteed to be called when an object is destroyed. > > > If there is code in the __init__ method that allocates resources > (memory, file opens, etc.), how do these resources get cleaned up when > an object is destroyed? Custom method? > __del__ is called when the garbage collector is about to destroy an object. There are times when it may not be called like IIRC when the interpreter exits before an object is garbage collected or when there is an exception that causes the object's reference count to stay >0, however... In practice you rarely need to implement a __del__ method. Memory is handled by the garbage collector. Most of the time you need not deal with it and in the rare chance that you do there is a module to interface with the interpreter's garbage collector. File descriptors, network connections and the like are usually handled either with an explicit .close() on the object or by implementing/using context managers[1]. And of course if you don't do so yourself then when the interpreter exits the OS closes them implicitly. 1. http://docs.python.org/library/stdtypes.html#context-manager-types -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Compiling Python 2.5.2 on AIX 5.2
I'm investigating the possible use of Mecurial SCM as a replacement for CVS. Mecurial is written in Python. I have a background in GNU/ Linux, Solaris, sparc and Perl. However AIX, powerpc and Python are new to me. --uname output-- $ uname -rvp 2 5 powerpc --end uname output-- I used this script to compile Python: --script-- export PATH=/usr/bin:/usr/vacpp/bin export CC=xlC_r export OBJECT_MODE=32 gunzip -c Python-2.5.2.tar.gz | tar xvf - cd Python-2.5.2 ./configure --with-gcc="xlc_r" --with-cxx="xlC_r" \ --disable-ipv6 AR="ar" --prefix=$HOME make --end script-- My concern is when I run make test I get this output: --make test output-- 275 tests OK. 2 tests failed: test_mmap test_wait4 45 tests skipped: test_aepack test_al test_applesingle test_bsddb test_bsddb185 test_bsddb3 test_bz2 test_cd test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_ctypes test_curses test_dl test_gdbm test_gl test_gzip test_imgfile test_largefile test_linuxaudiodev test_macfs test_macostools test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_scriptpackages test_socket_ssl test_socketserver test_sqlite test_startfile test_sunaudiodev test_tcl test_timeout test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 test_zipimport test_zlib 2 skips unexpected on aix5: test_largefile test_ctypes make: *** [test] Error 1 --end make test output-- My question are: (a) Have you successfully compiled Python 2.5.2 on AIX 5.2? If so, which options did you place in the environment and send to ./ configure? (b) Given the choice between xlc and gcc 4.2.2 (which we have on the platform) which one is considered more suitable? (c) I am concerned about the two failing test cases: test_mmap and test_wait4. Are there good reasons why these failures can be safely ignored? (d) Should I be concerned with the skips of test_largefile and test_ctypes? Much thanks in advance. Kind regards, -Randy Galbraith -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling Python 2.5.2 on AIX 5.2
On Apr 14, 7:01 am, "M.-A. Lemburg" <[EMAIL PROTECTED]> wrote: > On AIX 5.3, Python 2.5.2 should build out of the box using gcc. > > We've successfully build Python 2.3, 2.4 and 2.5 on AIX 5.3 > using the gcc compiler suite and tools installed from the > AIX Linux Toolbox: > > http://www-03.ibm.com/systems/p/os/aix/linux/toolbox/altlic.html > > ./configure --enable-unicode=ucs2 --with-gcc > > For 2.3 and 2.4 you need to patch pyconfig.h after the > configure run: Marc-Andre, Thanks so much for responding. I had to add --disable-ipv6 to ./ configure to prevent this problem: checking getaddrinfo bug... buggy Fatal: You must get working getaddrinfo() function. or you can specify "--disable-ipv6". When I checked pyconfig.h to make the patch you suggested I noticed line 60 already reads like this: #define HAVE_BROKEN_POSIX_SEMAPHORES 1 When ran make I immediately ran into problems. I'll investigate and post back the results. Any comments and direction here is appreciated. $ make gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -o Modules/python.o ./Modules/python.c In file included from Include/Python.h:83, from ./Modules/python.c:3: Include/unicodeobject.h:73:2: error: #error Must define Py_UNICODE_SIZE What is Py_UNICODE_SIZE and why was it not defined? There are current questions I have. Kind regards, -Randy Galbraith ps. Based on uname -rvp output of "2 5 powerpc" I'm assuming my OS is AIX 5.2 on PowerPC. I noticed you said you're on AIX 5.3. I'm not 100% sure I'm understanding uname output correctly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling Python 2.5.2 on AIX 5.2
On Apr 15, 11:33 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > What is Py_UNICODE_SIZE and why was it not defined? There are current
> > questions I have.
>
> Py_UNICODE_SIZE is the number of bytes that a Py_UNICODE value should
> have in the interpreter. With --enable-unicode=ucs2, it should be 2.
Martin,
Thanks for your reply. I feel like a dummy, when I was following Marc-
Andre's instructions I incorrectly typed "--enable-
unicode=ucs24" (note the "4"). Once I fixed that the Py_UNICODE_SIZE
issue went away.
Alas, I still am having problems compiling and getting a clean run
through make test. I got this error:
Python-2.5.2/Modules/bz2module.c:12:19: error: bzlib.h: No such file
or directory
Which I solved by copying bzlib.h I have on the system to Python-2.5.2/
Include/.
The run of make test resulted in this error:
test_ctypes
find_library('c') -> None
find_library('m') -> None
make: *** [test] Segmentation fault (core dumped)
An examination of the core with gdb shows this:
$ gdb python core
GNU gdb 6.0
Copyright 2003 Free Software Foundation, Inc.
[snip]
This GDB was configured as "powerpc-ibm-aix5.2.0.0"...
Core was generated by `python'.
Program terminated with signal 11, Segmentation fault.
#0 0xdebccc5c in ffi_closure_helper_DARWIN (closure=0xdebcd050,
rvalue=0x2ff20230, pgr=0x2ff20258, pfr=0x2ff201c8)
at Python-2.5.2/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c:
626
626 avalue = alloca(cif->nargs * sizeof(void *));
(gdb) bt
#0 0xdebccc5c in ffi_closure_helper_DARWIN (closure=0xdebcd050,
rvalue=0x2ff20230, pgr=0x2ff20258, pfr=0x2ff201c8)
at Python-2.5.2/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c:
626
#1 0xdebcd2bc in ffi_closure_ASM () from build/lib.aix-5.2-2.5/
_ctypes.so
#2 0xdebcd458 in ffi_call_AIX () from build/lib.aix-5.2-2.5/
_ctypes.so
#3 0xdebccf24 in ffi_call (cif=0xdebcd050, [EMAIL PROTECTED]:
0x2ff20350,
rvalue=0x2ff20258, avalue=0x2ff201c8)
at Python-2.5.2/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c:
421
#4 0xdebcb5e8 in _CallProc ([EMAIL PROTECTED]: 0xdebcd248
,
argtuple=0x20d5e9ac, flags=4097, argtypes=0x20d5eb2c,
restype=0x20e7dc44,
checker=0x0)
at Python-2.5.2/Modules/_ctypes/callproc.c:668
[snip frames #5 to #55]
#56 0x10063a70 in PyEval_EvalCode (co=0xdebcd050, globals=0x2ff20230,
locals=0x2ff20258) at Python/ceval.c:494
cals=0x2ff20258) at Python/ceval.c:494
(gdb) print cif
$1 = (ffi_cif *) 0x140
(gdb) print *cif
$3 = {abi = 1600485481, nargs = 1946157056, arg_types = 0x0, rtype =
0x400a,
bytes = 1, flags = 0}
Thus it would seem use cif here resulted in a segment violation. I'll
continue to research this issue and report back to the group as I know
more. Perhaps solving the issue with the 'c' and 'm' libraries
(whatever they might be) will make the core dump go away. However,
for tonight, I'll need to stop here.
Kind regards,
-Randy Galbraith
--
http://mail.python.org/mailman/listinfo/python-list
Re: Compiling Python 2.5.2 on AIX 5.2
On Apr 20, 10:17 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > I recommend you disable compilation of ctypes (by removing the call > to detect_ctypes from setup.py). It's fairly unlikely that you can > manage to make ctypes work on your system. Martin, Thanks again. I'm much closer now. Here is the script I'm using to compile Python on AIX: --begin script-- cp /path/to/include/bzlib.h Include/. cat <: [Errno 22] Invalid argument and for wait4: test test_wait4 failed -- Traceback (most recent call last): File "Python-2.5.2/Lib/test/fork_wait.py", line 75, in test_wait self.wait_impl(cpid) File "Python-2.5.2/Lib/test/test_wait4.py", line 28, in wait_impl self.assertEqual(spid, cpid) AssertionError: 0 != 6840386 What do these failures indicate? Not sure of course, but will research and report back. Kind regards, -Randy Galbraith "We seem to be made to suffer. It's our lot in life." - C3PO of Star Wars -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling Python 2.5.2 on AIX 5.2
On Apr 22, 11:17 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > > test test_mmap crashed -- : [Errno > > 22] Invalid argument > > You should run this with -v. This is too little detail to know what > exactly failed. Sorry it took so long to get back to you. At this point, I'm going to attempt to use python on AIX 5.2 even with the mmap and wait4 failures. My main requirement running Mercurial SCM, so hopefully the python binary I have will do the job. Nonetheless, I wanted to quickly dump out the expanded results you suggested might help. Running this: ./python Lib/test/test_mmap.py -v Resulted in this: --results-- Position of foo: 1.0 pages Length of file: 2.0 pages Contents of byte 0: '\x00' Contents of first 3 bytes: '\x00\x00\x00' Modifying file's content... Contents of byte 0: '3' Contents of first 3 bytes: '3\x00\x00' Contents of second page: '\x00foobar\x00' Regex match on mmap (page start, length of match): 1.0 6 Seek to zeroth byte Seek to 42nd byte Seek to last byte Try to seek to negative position... Try to seek beyond end of mmap... Try to seek to negative position... Attempting resize() Creating 10 byte test data file. Opening mmap with access=ACCESS_READ Ensuring that readonly mmap can't be slice assigned. Ensuring that readonly mmap can't be item assigned. Ensuring that readonly mmap can't be write() to. Ensuring that readonly mmap can't be write_byte() to. Ensuring that readonly mmap can't be resized. Opening mmap with size too big Opening mmap with access=ACCESS_WRITE Modifying write-through memory map. Opening mmap with access=ACCESS_COPY Modifying copy-on-write memory map. Traceback (most recent call last): File "Lib/test/test_mmap.py", line 393, in test_both() File "Lib/test/test_mmap.py", line 247, in test_both m.flush() EnvironmentError: [Errno 22] Invalid argument --end results-- btw I'm not sure if -v was required in this direct run. Running w/o - v gave the same results. Now, over to wait4. Your comment was: > That suggests a bug in wait4: apparently, it fails to correctly return > the PID. Could be an OS bug, but more likely, it's a type problem in > Modules/posixmodule.c. Running this: ./python Lib/test/test_wait4.py Resulted in this: --results-- test_wait (__main__.Wait4Test) ... FAIL == FAIL: test_wait (__main__.Wait4Test) -- Traceback (most recent call last): File "//Python-2.5.2/Lib/test/fork_wait.py", line 75, in test_wait self.wait_impl(cpid) File "Lib/test/test_wait4.py", line 28, in wait_impl self.assertEqual(spid, cpid) AssertionError: 0 != 8417358 -- Ran 1 test in 12.066s FAILED (failures=1) Traceback (most recent call last): File "Lib/test/test_wait4.py", line 37, in test_main() File "Lib/test/test_wait4.py", line 33, in test_main run_unittest(Wait4Test) File "//Python-2.5.2/Lib/test/test_support.py", line 451, in run_unittest run_suite(suite, testclass) File "//Python-2.5.2/Lib/test/test_support.py", line 436, in run_suite raise TestFailed(err) test.test_support.TestFailed: Traceback (most recent call last): File "//Python-2.5.2/Lib/test/fork_wait.py", line 75, in test_wait self.wait_impl(cpid) File "Lib/test/test_wait4.py", line 28, in wait_impl self.assertEqual(spid, cpid) AssertionError: 0 != 8417358 --end results-- Thanks for taking your time to respond. It is truly appreciated at this end. Kind regards, -Randy Galbraith -- http://mail.python.org/mailman/listinfo/python-list
Executing a DOS program from within Python
This is probably a newbie question but I need a kick start to get going. I need to run a DOS (sdetable) program from within a Python program. I'll use command line switches so I will not need to interact with the program however it would be nice if I could capture its exit code. Thanks Randy Kreuziger (360) 902-2495 Voice (360) 902-2940 Fax ArcSDE Administrator Wash Dept of Fish and Wildlife -- http://mail.python.org/mailman/listinfo/python-list
Trying to set up dictionary to map to functions
Hi,
I have a small test program written trying to set up a dictionary that
points keys to functions. It is working. However, in the process of
creating it I noticed a weird problem. The problem is that this IS WORKING
and I think it shouldn't be.
~ Here is the input config file code ~ its called config.file and is
referenced from the script.
[MAPS]
relmap = 1
posmap = 1
asnmap = 1
~ Here is the code that is working but I feel that it shouldn't be ~
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.file")
sections = config.sections()
print config.options('MAPS')
def posmap():
print "posmap function"
def relmap():
print "relmap function"
def asnmap():
print "asnmap function"
for value in config.options('MAPS'):
value
map_library = {
'posmap': posmap()
,'relmap': relmap()
,'asnmap': asnmap()
}
~ Output ~
['posmap', 'relmap', 'asnmap']
posmap function
relmap function
asnmap function
~ The reason I'm confused is because when I change the code (Take away the
map_library dictionary)
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.file")
sections = config.sections()
print config.options('MAPS')
def posmap():
print "posmap function"
def relmap():
print "relmap function"
def asnmap():
print "asnmap function"
for value in config.options('MAPS'):
value
~ The output is the following ~
['posmap', 'relmap', 'asnmap']
Is this defaulting to the dictionary and making it work? In the first set
of code I don't reference the map at all but it still seems to know where to
look? I am considerably new to Python
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 87, Issue 122
ZS On Dec 19, 2010 6:05 AM, wrote: > Send Python-list mailing list submissions to > [email protected] > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > [email protected] > > You can reach the person managing the list at > [email protected] > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 87, Issue 122
as On Dec 19, 2010 6:05 AM, wrote: > Send Python-list mailing list submissions to > [email protected] > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > [email protected] > > You can reach the person managing the list at > [email protected] > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." -- http://mail.python.org/mailman/listinfo/python-list
GUI Tools for Python 3.1
Lots of stuff for 2.6 and 2.7 -- what GUI tools are there for 3.1? Randy -- http://mail.python.org/mailman/listinfo/python-list
looking for a book on python
Hello and thank you for taking your time to read this. I was interested in learning about python. In the long ago past I did learn some programing but I have not used any of it for years. I do remember some basics however so the book does not have to be for a total beginner. (C, C++, BASIC, Visual BASIC, Pascal and some ADA) I have been using Linux for a while and overall still don't know much about it but I can find my way. I have my system dual boot with windows vista. I do realize that everyone is different but I would like to see some suggestions and maybe reasons why you think it is good. I have looked for/searched and found a few different books but as my means are a bit limited right now I don't really want to buy several just one or maybe two books. Oh and if someone knows a place to find some used books of this sort that would be great (ebay I guess :) Thanks for your thoughts Randy theslayers9 gmail -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a book on python
OdarR wrote: On 27 juin, 02:48, Randy Foiles wrote: Hello and thank you for taking your time to read this. I was interested in learning about python. In the long ago past I did learn some programing but I have not used any of it for years. I do remember some basics however so the book does not have to be for a total beginner. (C, C++, BASIC, Visual BASIC, Pascal and some ADA) I have been using Linux for a while and overall still don't know much about it but I can find my way. I have my system dual boot with windows vista. I do realize that everyone is different but I would like to see some suggestions and maybe reasons why you think it is good. I have looked for/searched and found a few different books but as my means are a bit limited right now I don't really want to buy several just one or maybe two books. Oh and if someone knows a place to find some used books of this sort that would be great (ebay I guess :) Thanks for your thoughts Randy theslayers9 gmail "Learning Python" http://oreilly.com/catalog/9780596513986/ new issue soon, covering 2.6 and 3 http://oreilly.com/catalog/9780596158064/?CMP=AFC-ak_book&ATT=Learning+Python%2c+Fourth+Edition%2c the best book I read concerning Py understanding, well written. I would start with web content, then later would buy the fourth edition of "Learning Python". enjoy, Olivier Thank you. I was thinking of that book and a few others. I am not sure at this point what the difference is in 2.6 and 3? Randy -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a book on python
Aahz wrote: In article , Randy Foiles wrote: I do realize that everyone is different but I would like to see some suggestions and maybe reasons why you think it is good. I have looked for/searched and found a few different books but as my means are a bit limited right now I don't really want to buy several just one or maybe two books. You could get the book I co-wrote (Python for Dummies), but honestly, I think you should try using some of the online tutorials first. The standard Python tutorial is aimed at people with some programing experience: http://docs.python.org/tutorial/index.html I had not thought about the "dummies" books for this I will look and see if my local B&N has it. -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a book on python
[email protected] wrote: On Jun 26, 8:48 pm, Randy Foiles wrote: Hello and thank you for taking your time to read this. I was interested in learning about python. In the long ago past I did learn some programing but I have not used any of it for years. I do remember some basics however so the book does not have to be for a total beginner. (C, C++, BASIC, Visual BASIC, Pascal and some ADA) I have been using Linux for a while and overall still don't know much about it but I can find my way. I have my system dual boot with windows vista. I do realize that everyone is different but I would like to see some suggestions and maybe reasons why you think it is good. I have looked for/searched and found a few different books but as my means are a bit limited right now I don't really want to buy several just one or maybe two books. Oh and if someone knows a place to find some used books of this sort that would be great (ebay I guess :) Thanks for your thoughts Randy theslayers9 gmail The Oreilly "Python in a Nutshell" (2006, 2nd ed.) book is very good and will get you up to speed in short order. This is one of the books I see around and it does seem that O'Reilly is where most people go for them :) What is it that you like about this one? -- http://mail.python.org/mailman/listinfo/python-list
search term parsing like Google/Gmail
I am looking for a string parser that works kind of like Google's or Gmail's advanced search capabilities. So it would turn something like this: (subject:"hi there" from:[tim, tom, -fred]) or (subject:foobar from:sam) into a python structure that could be used. I don't really care so much about the search syntax except that easy and intuitive is best for users. Does something like this exist? -- ------ Randy Syring Intelicom 502-644-4776 "Whether, then, you eat or drink or whatever you do, do all to the glory of God." 1 Cor 10:31 -- http://mail.python.org/mailman/listinfo/python-list
software installation problems
Good morning, when I run the Python program after installing the latest version, I get this message (attached file), I have already reinstalled the program several times and the same message keeps appearing; What solution could you give me, thank you! -- https://mail.python.org/mailman/listinfo/python-list
