Re: __getattr__ Confusion

2013-02-04 Thread Saul Spatz
Thanks, Peter.  I realize this is getting sort of academic now, as I know how 
to do exactly what I want, but I'm still confused.  Is __getattr__ a special 
case then, even for classic classes?

class Adder(): # python 2.7, classic class
  def __init__(self, x):
self.x = x
self.__add__= lambda other: Adder(self.x+other.x)
self.__getattr__ = lambda name: self.test(name)

  def __str__(self):
return str(self.x)

  def test(self, name):
print("Hello from test")
raise AttributeError

x = Adder(3)
y = Adder(4)
print(x+y)
x.junk()

7
Traceback (most recent call last):
  File "C:\Users\Saul\Documents\PythonProjects\test.py", line 18
AttributeError: Adder instance has no attribute 'junk'

Why does this work for __add__ and not for __getattr__?

Of course, they both work if I write instead

def __add__self, other):
   return Adder(self.x+other.x)

def __getattr__(self, name):
   print(name)
   raise AttributeError

like a sensible person.

Saul  

On Monday, February 4, 2013 8:15:47 AM UTC-6, Peter Otten wrote:
> Saul Spatz wrote:
> 
> 
> 
> > Now I have another question.  If dunder methods are looked up only in the
> 
> > class, not the instance, why did defining __nonzero__ the way I did work? 
> 
> > Shouldn't I have had to define it with a def?  Is __nonzero__ a special
> 
> > case?
> 
> 
> 
> Unfortunately the situation is a bit more complex. Classic classes (like 
> 
> Tkinter.Frame) behave differently from newstyle classes (subclasses of 
> 
> object):
> 
> 
> 
> >>> def nz():
> 
> ... print "nonzero"
> 
> ... return 0
> 
> ... 
> 
> >>> class Classic: pass
> 
> ... 
> 
> >>> c = Classic()
> 
> >>> c.__nonzero__ = nz
> 
> >>> not c
> 
> nonzero
> 
> True
> 
> >>> class New(object): pass
> 
> ... 
> 
> >>> n = New()
> 
> >>> n.__nonzero__ = nz
> 
> >>> not n
> 
> False
> 
> 
> 
> So Steven is wrong here.
> 
> 
> 
> > Shouldn't I have had to define it with a def?
> 
> 
> 
> If you mean as opposed to a lambda, there is no difference between
> 
> 
> 
> f = lambda ...
> 
> 
> 
> and
> 
> 
> 
> def f(...): ...
> 
> 
> 
> other than that the last one gives you a nice name in a traceback.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattr__ Confusion

2013-02-04 Thread Saul Spatz
On Sunday, February 3, 2013 10:35:30 PM UTC-6, Steven D'Aprano wrote:
> On Sun, 03 Feb 2013 17:08:47 -0800, Saul Spatz wrote:
> 
> 
> 
> > I don't understand what's going on at all.  Can't I dynamically define
> 
> > __getattr__?  How should I go about it?  
> 
> 
> 
> Special "dunder" methods (DoubleUNDERscore) are looked up only on the 
> 
> class, not on instances. That means that if you try to dynamically 
> 
> provide a dunder method by assigning it to an instance, say with:
> 
> 
> 
> self.__nonzero__ = lambda self: True
> 
> 
> 
> it will *not* be automatically used by Python. The only way to 
> 
> dynamically add dunder methods is to add them to the class, but of course 
> 
> that means that all instances see the same method.
> 
> 
> 
> 
> 
> In your case, you try doing this inside the __init__:
> 
> 
> 
> self.__getattr__ = lambda x, name: getattr(self.canvas, name)
> 
> 
> 
> 
> 
> Why not just define a __getattr__ method the normal way? In your class, 
> 
> define a method:
> 
> 
> 
> def __getattr__(self, name):
> 
> return getattr(self.canvas, name)
> 
> 
> 
> This technique is called automatic delegation.
> 
> 
> 
> Even if this does not quite do what you are trying to do, you will 
> 
> eliminate one major stumbling block and be that much closer to a working 
> 
> solution.
> 
> 
> 
> 
> 
> > By the way, another thing that
> 
> > didn't work was calling the method delegate instead of __getattr__. 
> 
> > Then after the constructor call, I wrote self.__getattr__ =
> 
> > self.delegate.  This crashed as before on self.create_text.
> 
> 
> 
> It is pointless to tell us that Python "crashed" if you don't show us 
> 
> *exactly* what you did, by copying and pasting the *actual* code, 
> 
> complete with the full traceback. Otherwise we are just guessing what you 
> 
> did and what error you saw.
> 
> 
> 
> I'm pretty confident that Python didn't "crash", in the commonly accepted 
> 
> meaning of the word meaning a core dump or equivalent. I'm guessing you 
> 
> meant that Python raised a perfectly normal exception, like
> 
> 
> 
> 
> 
> Traceback (most recent call last):
> 
>   ...
> 
> NameError: name 'self' is not defined
> 
> 
> 
> 
> 
> If you pay attention to the exception messages that Python prints for 
> 
> you, you will not only find it easier to debug your code, but you can 
> 
> also ask more sensible questions using accepted terminology.
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven

Thanks.  The class versus instance lookup explains it.  

I didn't mean that python crashed, but that my app did.  

Now I have another question.  If dunder methods are looked up only in the 
class, not the instance, why did defining __nonzero__ the way I did work?  
Shouldn't I have had to define it with a def?  Is __nonzero__ a special case?
 
-- 
http://mail.python.org/mailman/listinfo/python-list


__getattr__ Confusion

2013-02-03 Thread Saul Spatz
To the good people on comp.lang.python:

I have the following Tkinter class (python 2.7.3):

from Tkinter import *

class ScrolledCanvas(Frame):
  def __init__(self, master, width, height, bg, cursor):
Frame.__init__(self, master)
self.__nonzero__ = lambda: True
canv = self.canvas = Canvas(self, bg=bg, relief=SUNKEN)
# self.__getattr__ = lambda x, name: getattr(self.canvas, name)
canv.config(width=width, height=height)   # display area size
canv.config(scrollregion=(0, 0, width, height))   # canvas size corners
canv.config(highlightthickness=0) # no pixels to border

ybar = Scrollbar(self)
ybar.config(command=canv.yview)   # xlink sbar and canv
canv.config(yscrollcommand=ybar.set)  # move one moves other

xbar = Scrollbar(self)
xbar.config(command=canv.xview)   # xlink sbar and canv
canv.config(xscrollcommand=xbar.set)  # move one moves other

canv.grid(row = 0, column = 0, sticky = 'news')
ybar.grid(row = 0, column = 1, sticky = 'ns')
xbar.grid(row = 1, column = 0, sticky = 'ew')
self.rowconfigure(0, weight = 1)
self.columnconfigure(0, weight = 1)

self.create_text(20, 20, text = 'Did it!', fill = 'red')

  def __getattr__(self, name):
return getattr(self.canvas, name)

root = Tk()
app = ScrolledCanvas(root, 400, 300, 'white', 'hand2')
app.pack()
root.mainloop()

I just added the __getattr__ method, and the program crashed in the Canvas 
constructor.  There is apparently a call to self.__nonzero__ somewhere in 
Tkinter.py, and since the constructor hasn't exited yet, sel.fcanvas isn't 
defined yet, so __getattr__ recurses indefinitely.

I fixed this as you see, by defining self.__nonzero__ before the call to the 
constructor.  Now, I have  two questions: 

1. I originally defined self.__nonzero__ = lambda x: True, on the assumption 
that when self.__nonzero__ was called, the interpreter would pass self as an 
argument.  Wrong.  No arguments were passed.  Why is this?

2. I find this solution rather unsatisfactory, since there's a rather obscure 
line of code here.  I tried eliminating the def of __gertattr__ and the 
definition of self.__nonzero__ and adding this line after the constructor:

self.__getattr__=  lambda name: getattr(self.canvas, name)   

This get through the constructor all right, but crashes with the message that a 
ScrolledCanvas object has no create_text attribute.  (I've tried passing two 
arguments to the lambda, but it makes no difference.)  

I don't understand what's going on at all.  Can't I dynamically define 
__getattr__?  How should I go about it?  By the way, another thing that didn't 
work was calling the method delegate instead of __getattr__.  Then after the 
constructor call, I wrote
self.__getattr__ = self.delegate.  This crashed as before on self.create_text.

I just tried a little experiment with __add__ and had no success, so I guess my 
problem is with overloaded operators in general.

I'd really appreciate an explanation, or a pointer to relevant documentation.
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pymysql only works under IDLE

2012-01-16 Thread Saul Spatz
Thanks a lot; I didn't know about sys.executable.  For the record, IDLE is 
running pythonw.exe.  I won't have a chance to test if this helps till 
tomorrow, unfortunately.
-- 
http://mail.python.org/mailman/listinfo/python-list


pymysql only works under IDLE

2012-01-16 Thread Saul Spatz
I've been using pymysql to connect to a database, and it has suddenly stopped 
working on the one machine (a virtual server) where I really need it to work.  
I have a function with hard-coded parameters to do the connection, and now I'm 
getting an error that says, "Can't connect to MySQL server on ...".  The 
strangest thing is that while I can't connect if I run the script from the 
command line, or from the shell under Wing IDE, I can connect if I run the 
script under the IDLE shell.

I noticed that the command line shell prints

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.

at startup, but the IDLE shell prints

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on 
win32
Type "copyright", "credits" or "license()" for more information.

So, while the first lines are identical, the second lines are different.  Is 
this a different interpreter then?  Can anyone tell me what the difference is?  
I'm hoping that may help me figure out what's gone wrong.  

I'm running on Windows 7.

I'll be grateful for any help you can give me.

Saul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
Thanks, that a great link.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
Yes, the tuple is certainly easier to read.

Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
That doesn't work, I'm being stupid,  The user might type anywhere in the 
string, not just at the end.  I need

return all([c in '1234567890abcdefABCDEF ' for c in after])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
Thanks so much, this is great.  I want to validate that the user is entering a 
string appropriate for bytes.fromhex.  Here's how I modified your validate 
funtion:

def validate(before, after):
print(before, "-->", after)
#return after.isdigit()
return after[-1] in '1234567890abcdefABCDEF '

I also had to change validate="all" to validate="key" in the Entry 
construction, since otherwise, I go an IndexError when the widget gets the 
focus.  (try...except also worked, but I only care about keystrokes.)

I didn't know about the register method; that's the key.

Thanks again,
Saul 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-24 Thread Saul Spatz
I want to interface to the native validation of tk.  If you don't know what 
that is, you're unlikely to be able to help me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Validating Entry in tkinter

2011-07-24 Thread Saul Spatz
In tcl/tk an Entry widget can be set to validate its contents with the validate 
option.  You have to give it a validatecommand (vcmd), which is a tcl script 
that runs when some action triggers validation.  Usually, the script would use 
"percent substitutions" so the script would be something like {ValidInt %P} 
where %P is the value of the widget should the proposed change occur.  

Can one do something like this in tkinter?  I've verified that with

e = Entry(master, validate = 'all', vcmd = validInt) 

the validInt function is called, but it isn't passed any parameters. I can't 
find that e has any attribute corresponding to the %P value above.

Is it not possible to do this in tkinter, or have I overlooked something? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode codepoints

2011-06-22 Thread Saul Spatz
Thanks very much.  This is the elegant kind of solution I was looking for.  I 
had hoped there was a way to do it without even addressing the matter of 
surrogates, but apparently not.  The reason I don't like this is that it 
depends on knowing that python internally stores strings in UTF-16.  I expected 
that there would be some built-in iterator that would return the code points.  
(Actually, this all started when I realized that s[k] wouldn't necessarily give 
me the kth character of the string s.)


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode codepoints

2011-06-22 Thread Saul Spatz
Thanks.  I agree with you about the generator.  Using your first suggestion, 
code points above U+ get separated into two "surrogate pair" characters 
fron UTF-16.  So instead of U=10 I get U+DBFF and U+DFFF.
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter/scrollbar/canvas question

2011-06-21 Thread Saul Spatz
It works if you change it like so:

from tkinter import *
class ShowList(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.grid()
self.draw_widgets()
def draw_widgets(self):
cframe = Frame(self)
cframe.grid(row=1, sticky=N+S+E+W)
canv = Canvas(cframe)
canv.grid(row=0, column=0, sticky=N+S+E+W)
vscroll = Scrollbar(cframe, orient=VERTICAL, command=canv.yview)
hscroll = Scrollbar(cframe, orient=HORIZONTAL, 
command=canv.xview)
vscroll.grid(row=0, column=1, sticky=N+S)
hscroll.grid(row=1, column=0, sticky=E+W)
canv["xscrollcommand"] = hscroll.set
canv["yscrollcommand"] = vscroll.set
aframe = Frame(canv)
id = canv.create_window(0,0,window=aframe, anchor=N+W)
for i in range(0,100):
Label(aframe, text=str(i), anchor=N+W).grid(row=i, 
column=0)
aframe.update_idletasks()
canv["scrollregion"]=canv.bbox(ALL)
root  = Tk()
m=ShowList(root)
root.mainloop()

You have to call update_idletasks to force the canvas to be mapped to screen; 
until it is mapped, its bounding box is (0,0,1,1).  You can call 
update_idletasks through any widget.

That said, I wonder if it wouldn't be better to put canvas objects directly on 
the canvas, instead of putting widgets in a frame on the canvas.  The way 
you're doing it, you can't give the widgets tags, which are what give the 
canvas its real power. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter/scrollbar/canvas question

2011-06-21 Thread Saul Spatz
This is the third time I've tried to post this reply.  If you see multiple 
answers from me, that's why.

Your script will work if you change it like so:

from tkinter import *
class ShowList(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.grid()
self.draw_widgets()
def draw_widgets(self):
cframe = Frame(self)
cframe.grid(row=1, sticky=N+S+E+W)
canv = Canvas(cframe)
canv.grid(row=0, column=0, sticky=N+S+E+W)
vscroll = Scrollbar(cframe, orient=VERTICAL, command=canv.yview)
hscroll = Scrollbar(cframe, orient=HORIZONTAL, 
command=canv.xview)
vscroll.grid(row=0, column=1, sticky=N+S)
hscroll.grid(row=1, column=0, sticky=E+W)
canv["xscrollcommand"] = hscroll.set
canv["yscrollcommand"] = vscroll.set
aframe = Frame(canv)
id = canv.create_window(0,0,window=aframe, anchor=N+W)
for i in range(0,100):
Label(aframe, text=str(i), anchor=N+W).grid(row=i, 
column=0)
aframe.update_idletasks()
canv["scrollregion"]=canv.bbox(ALL)
root  = Tk()
m=ShowList(root)
root.mainloop()

You need to call update_idletasks to force the canvas to be mapped to the 
screen before you compute the bounding box.  Until it's mapped, the bounding 
box is (0,0,1,1), and of course you need to put the widgets on before you 
compute the bounding box.  You can call update_idletasks through any widget.  

That said, I wonder if it wouldn't be better to put canvas objects directly on 
the canvas, instead of putting widgets in a frame.  The way you'r doing it, you 
can't give the widgets tags, and tags are what give the canvas its power.

Saul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter/scrollbar/canvas question

2011-06-21 Thread Saul Spatz
It works if you change it like so:

from tkinter import *
class ShowList(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.grid()
self.draw_widgets()
def draw_widgets(self):
cframe = Frame(self)
cframe.grid(row=1, sticky=N+S+E+W)
canv = Canvas(cframe)
canv.grid(row=0, column=0, sticky=N+S+E+W)
vscroll = Scrollbar(cframe, orient=VERTICAL, command=canv.yview)
hscroll = Scrollbar(cframe, orient=HORIZONTAL, 
command=canv.xview)
vscroll.grid(row=0, column=1, sticky=N+S)
hscroll.grid(row=1, column=0, sticky=E+W)
canv["xscrollcommand"] = hscroll.set
canv["yscrollcommand"] = vscroll.set
aframe = Frame(canv)
id = canv.create_window(0,0,window=aframe, anchor=N+W)
for i in range(0,100):
Label(aframe, text=str(i), anchor=N+W).grid(row=i, 
column=0)
aframe.update_idletasks()
canv["scrollregion"]=canv.bbox(ALL)
root  = Tk()
m=ShowList(root)
root.mainloop()

You need to do the update_idletasks to force the canvas to be mapped before you 
figure out the bounding box.  Until the canvas is mapped to the screen, the 
bounding box is (0,0,1,1) so there no scrolling possible.  (You can call 
update_ideltasks through any widget.)

That said, I wonder why you're putting widgets in the frame instead of putting 
objects directly on the canvas.  The way you're doing it you can't use tags, 
which are what really give the canvas its power.

Saul

   
-- 
http://mail.python.org/mailman/listinfo/python-list


Unicode codepoints

2011-06-21 Thread Saul Spatz
Hi,

I'm just starting to learn a bit about Unicode. I want to be able to read a 
utf-8 encoded file, and print out the codepoints it encodes.  After many false 
starts, here's a script that seems to work, but it strikes me as awfully 
awkward and unpythonic.  Have you a better way?

def codePoints(s):
''' return a list of the Unicode codepoints in the string s '''
answer = []
skip = False
for k, c in enumerate(s):
if skip:
skip = False
answer.append(ord(s[k-1:k+1]))
continue
if not 0xd800 <= ord(c) <= 0xdfff:
answer.append(ord(c))
else:
skip = True
return answer

if __name__ == '__main__':
s = open('test.txt', encoding = 'utf8', errors = 'replace').read()
code = codePoints(s)
for c in code:
print('U+'+hex(c)[2:])

Thanks for any help you can give me.

Saul


-- 
http://mail.python.org/mailman/listinfo/python-list


Where is the Demo Directory in Python 3.2?

2011-06-02 Thread Saul Spatz
The documentation refers to the Demo directory in the source.  I've downloaded 
the source tarball for python 3.2 and there's no such directory.  I downloaded 
the source for python 2.7 to check, and the Demo directory is present.  Has the 
directory been moved, renamed or eliminated in 3.2?  Thanks for any help you 
can give me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regexp matching end of line or comma

2010-11-25 Thread Saul Spatz
On Nov 25, 8:40 am, Jean-Michel Pichavant 
wrote:
> Hy guys,
>
> I'm struggling matching patterns ending with a comma ',' or an end of
> line '$'.
>
> import re
>
> ex1 = 'sumthin,'
> ex2 = 'sumthin'
> m1 = re.match('(?P\S+),', ex1)
> m2 = re.match('(?P\S+)$', ex2)
> m3 = re.match('(?P\S+)[,$]', ex1)
> m4 = re.match('(?P\S+)[,$]', ex2)
>
> print m1, m2
> print m3
> print m4
>
> <_sre.SRE_Match object at 0x8834de0> <_sre.SRE_Match object at 0x8834e20>
> <_sre.SRE_Match object at 0x8834e60>
> None
>
> My problem is that m4 is None while I'd like it to match ex2.
>
> Any clue ?
>
> JM

>From the Regular Expression Syntax documentation:
Special characters are not active inside sets. For example, [akm$]
will match any of the characters 'a', 'k', 'm', or '$';

so in m4, [,$] matches a comma or a literal dollar sign.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQt Installation Problem on Windows

2010-11-24 Thread Saul Spatz
Hi,

I've been trying to install PyQt on Windows XP Pro so that I can try
out eric ide.  I used the binary windows installer for PyQt.  I can
run eric as administrator, but not with my ordinary user account.  By
running eric.bat with the --debug flag, I found that he crux of the
problem is that if I type

 import PyQt4

in the python shell, it works for both users, but if I type

 import PyQt4.QtCore

it works for the administrator, but the non-privileged account gets
the message

ImportError: DLL load failed: The specified module could not be found.

In the file the file pyqtconfig.py from Python26\Lib\site-packages
\PyQt4 I have the line

'pyqt_config_args':  '--confirm-license -b C:\\Python26\\Lib\\site-
packages\\PyQt4\\bin',

I checked with a friend who uses eric, and his file does not have the
--confirm-license parameter.  As far as we can tell, we followed the
same installation procedures.

By the way, I have tried this with python 3.1 on the same machine with
similar results.

I've blown a whole day playing with this, so I'd really appreciate any
help you can give me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Double Clicking on .pyw File Doesn't Work in Windows 7

2010-10-05 Thread Saul Spatz
When I double-click on a file with a .pyw extension, nothing appears to
happen.  Control panel shows that pythonw is associated with this extension,
and if I right-click on the filename, the program suggested to open it is
pythonw.exe.  If I make a desktop shortcut with the target pythonw.exe
myScript.pyw, it works as expected.  Any ideas?

Thanks,
Saul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: after_cancel?

2009-04-18 Thread Saul Spatz

W. eWatson wrote:
I'm looking a program that I'm not real familiar with that uses an 
after_cancel method and after_id variable.  Are they related to some 
particular widget and what is there function? Perhaps they are related 
to a Cancel button on a widget?


http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write a simple shell loop in python?

2009-01-20 Thread Saul Spatz

Dietrich Bollmann wrote:

Hi,

I am trying to write a simple shell loop in Python.

My simple approach works fine - but the first output line after entering
something is always indented by one blank.  

Is there any logic explanation for this?  
How can I get rid of the blank?

Is there a smarter way to write a simple shell loop which would work
better?

Thanks, Dietrich


Here my approach:

$ python
Python 2.5.2 (r252:60911, Jan  4 2009, 17:40:26) 
[GCC 4.3.2] on linux2

Type "help", "copyright", "credits" or "license" for more information.
import sys
while (1):

... print "$ ",
... input = sys.stdin.readline()
... input = input.strip()
... print input
... print input
... print input
... 
$ one

 one
one
one
$ two
 two
two
two
$ three
 three
three
three
$ 
Traceback (most recent call last):

  File "", line 3, in 
KeyboardInterrupt


Strange.  I don't have an explanation, but experiment shows that if you 
change print "$ ", to print "$ " (that is, leave out the comma) then the 
leading blank is not printed.  This behavior doesn't depend on the 
"print input" statement's being in a loop.


By the way, you don't need parens around the loop guard in python:
while 1: (or as I prefer, while True:) work just fine.

Saul
--
http://mail.python.org/mailman/listinfo/python-list


Problem with 3.0 Install on Windows

2009-01-20 Thread Saul Spatz
I'm running python 2.5.x on Windows XP, and I installed 3.0, just to get 
familiar with it.  I have a directory with all my python projects in my 
PYTHONPATH variable.  When I try to run python 3.0, it detects a syntax 
error (a print statement) in the first file in this directory, and 
crashes.  I don't want to convert the files to 3.0 syntax, because I 
plan to keep using 2.5, at least for a while.


I don't know exactly why this translation is happening.  Is there a way 
to turn it off?


Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: recursion in Class-methods?

2008-06-26 Thread Saul Spatz

defn noob wrote:

if start == end:
return path
if not self.dictionary.has_key(start):

   if start not in self.dictionnary:


return None
for node in self.dictionary[start]:
if node not in path:
newpath = find_path(self.dictionary, node, end, path)

   newpath = self.find_path(...)

(snip remaining code - same problems, same solutions...)


it is to incoherent fo follow what you mean here(not meaning to sound
rude i appreciate the help).


I modified your code as shown below, and it seems to work fine.  (I 
didn't test the shortest path part, just the example you gave.)


class Graph(object):
def __init__(self, dictionary):
self.dictionary = dictionary

def find_path(self, start, end, path=None):
if not path:
path = []
path = path + [start]
if start == end:
return path
if not self.dictionary.has_key(start):
return None
for node in self.dictionary[start]:
if node not in path:
newpath = self.find_path(node, end, path)
if newpath: return newpath
return None

def find_all_paths(self, start, end, path=None):
if not path:
path = []
path = path + [start]
if start == end:
return [path]
if not self.dictionary.has_key(start):
return []
paths = []
for node in self.dictionary[start]:
if node not in path:
newpaths = self.find_all_paths(node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths

def find_shortest_path(self, start, end, path=None):
if not path:
path = []
path = path + [start]
if start == end:
return path
if not self.dictionary.has_key(start):
return None
shortest = None
for node in self.dictionary[start]:
if node not in path:
newpath = self.find_shortest_path(node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest

g = Graph({'A': ['B', 'C'],
 'B': ['C', 'D'],
 'C': ['D'],
 'D': ['C'],
 'E': ['F'],
 'F': ['C']})
print g.find_all_paths('A', 'C')

Output:
[['A', 'B', 'C'], ['A', 'B', 'D', 'C'], ['A', 'C']]

Here are the changes I made.
1) Inherit from object.  (Anticipation of 3.0)

2) Changed calls such as find_path(self.dictionary, node, end, path) to 
self.find_path(node, end, path).  In python, an objects methods have no

special privileges in calling its other methods.  They call it like
self.otherMethod(...).  Also, the first parameter is supposed to be a
Graph object.  I'm not sure what the effect of calling it with a 
dictionary would be.  BTW, "dictionary" seems like an uninformative

name. Why not call it "adjacent" or "neighbor", or "successor"?

3) Changed the default value of path to None, as suggested by Bruno 
Desthuilliers. What he's telling you is that the default object is 
created only once; when the method is defined.  If it's an int or a 
string, that doesn't matter.  You can't change it, and so you will 
always have the same default value if you need it.  If it's a mutable 
object, like a list, when your method changes it, as with

path = path + [start]
it changes the global default object; the next time you need it, it 
won't be [] but whatever you last changed it to.


This last is a tricky point.  I hope I've been clear.

Saul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question: How do I format printing in python

2008-06-23 Thread Saul Spatz

format the strings:
http://www.python.org/doc/2.1.3/lib/typesseq-strings.html



[EMAIL PROTECTED] wrote:

Hi All,

How do I format printed data in python?
I could not find this in the Python Reference Manual:
http://docs.python.org/ref/print.html
Nor could I find it in Matloff's great tutorial:
http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf


For example, how do I turn this:

512 Jun 5 2004 X11r6
22 Jan 17 2005 a2p
22 Jan 17 2005 acctcom
5374 Sep 15 2002 acledit
5664 May 13 2004 aclget
12020 May 13 2004 aclput
115734 Jun 2 2004 adb
46518 Jun 4 2004 admin
66750 Sep 16 2002 ali
1453 Sep 15 2002 alias
28150 Jun 4 2004 alog
15 May 12 2005 alstat

into this:

512Jun   5   2004X11r6
22 Jan   17  2005a2p
22 Jan   17  2005acctcom
5374   Sep   15  2002acledit
5664   May   13  2004aclget
12020  May   13  2004aclput
115734 Jun   2   2004adb
46518  Jun   4   2004admin
66750  Sep   16  2002ali
1453   Sep   15  2002alias
28150  Jun   4   2004alog
15 May   12  2005alstat

Thank you

--
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to Learn Packages

2008-06-22 Thread Saul Spatz

Cédric Lucantis wrote:

Le Sunday 22 June 2008 16:07:37 Saul Spatz, vous avez écrit :

Hi,

I'm making a project into my first package, mainly for organization, but
also to learn how to do it.  I have a number of data files, both
experimental results and PNG files.  My project is organized as a root
directory, with two subdirectories, src and data, and directory trees
below them.  I put the root directory in my pythonpath, and I've no
trouble accessing the modules, but for the data, I'm giving relative
paths, that depend on the current working directory.

This has obvious drawbacks, and hard-coding a directory path is worse.
Where the data files are numbers, I can simply incorporate them in
python scripts that initialize data structures , but what can I do with
the image files?


For a small project you can do the same with images or any kind of data, for 
instance by serializing your objects with pickle in ascii mode and putting 
the result in a string constant (well, I never did it and can't guarantee it 
will work, this is only an example of what people do in many situations)



What is the usual way of dealing with this?



A more conventional way is to provide a configure script to run before 
compiling/installing. That script should let the user choose where to install 
datafiles with a command line option such as --datadir=/path or provide a 
reasonable default value. Then it will auto-generate some code defining this 
value as a global variable, to make it accessible to the rest of your own 
code. Ideally, your app would also provide a command line option or an 
environment variable to override this hard-coded setting at runtime.


But maybe the distutils tools have some features for this, I don't know enough 
of them to tell that.



A couple of good ideas here.  Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Trying to Learn Packages

2008-06-22 Thread Saul Spatz

Hi,

I'm making a project into my first package, mainly for organization, but 
also to learn how to do it.  I have a number of data files, both 
experimental results and PNG files.  My project is organized as a root
directory, with two subdirectories, src and data, and directory trees 
below them.  I put the root directory in my pythonpath, and I've no 
trouble accessing the modules, but for the data, I'm giving relative 
paths, that depend on the current working directory.


This has obvious drawbacks, and hard-coding a directory path is worse. 
Where the data files are numbers, I can simply incorporate them in 
python scripts that initialize data structures , but what can I do with 
the image files?


What is the usual way of dealing with this?

Thanks,
Saul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python: Code critique please

2008-06-22 Thread Saul Spatz

macoovacany wrote:

http://macoovacany.wordpress.com/
When I tried to run it, I got all kinds of syntax errors because of 
non-ASCII characters; namely, you have fancy left and right single

and double quotes.  Once I replaced these with the ASCII equivalents,
it worked fine.  I suggest you use a plain ASCII text editor, like the
one that comes with IDLE.

HTH,
Saul
--
http://mail.python.org/mailman/listinfo/python-list