Re: Please help - Tkinter not doing anything

2008-05-04 Thread Protected
Good thinking. It was indented with spaces, so I replaced them with tabs.
Now I'm getting a SyntaxError: invalid syntax in root = Tk(). If I split the
code in two parts (with the second one beginning in that line) and run them
separately, I get no errors, but still nothing happens.

class Application(Frame):
def say_hi(self):
print "hi there, everyone!"

def createWidgets(self):
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"]   = "red"
self.QUIT["command"] =  self.quit

self.QUIT.pack({"side": "left"})

self.hi_there = Button(self)
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.say_hi

self.hi_there.pack({"side": "left"})

def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()

var root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

On Sun, May 4, 2008 at 12:33 PM, Q4 <[EMAIL PROTECTED]> wrote:

> On Sun, 4 May 2008 02:23:37 -0700 (PDT), Protected <[EMAIL PROTECTED]>
> wrote:
> > Hello. I'm a complete newbie trying to learn Python. I decided to try
> > some Tkinter examples, including the one from the library reference,
> > but they don't seem to do anything! Shouldn't there be, like, a
> > dialog?
> >
> > I'm running Windows XP and using IDLE. You can assume my version of
> > Python is the latest.
> > --
> > http://mail.python.org/mailman/listinfo/python-list
>
> If you just copy the code from the python doc the indentation might be
> broken.
> Send the code and I'll take a look at it.
>
> Do you get any errors?
>
> --
> My website:
>  http://www.riddergarn.dk/koder/
>
>
--
http://mail.python.org/mailman/listinfo/python-list

Please help - Tkinter not doing anything

2008-05-04 Thread Protected
Hello. I'm a complete newbie trying to learn Python. I decided to try
some Tkinter examples, including the one from the library reference,
but they don't seem to do anything! Shouldn't there be, like, a
dialog?

I'm running Windows XP and using IDLE. You can assume my version of
Python is the latest.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help - Tkinter not doing anything

2008-05-04 Thread Protected
I had previously ran the import line. I prepended it to the example
code I'm trying to run every time but it did not help, still nothing
happens. With or without var before 'root'. I'm pasting the code in
IDLE and using Windows XP as written in the first post.

On May 4, 11:04 am, "Chuckk Hubbard" <[EMAIL PROTECTED]>
wrote:
> Try adding:
>
> from Tkinter import *
>
> at the beginning, and you don't need "var" in front of root=Tk(), just
> "root = Tk()"   (<-without the quotes of course)
> What OS are you on?  Are you running "python testapp.py" or similar to
> make it run?
>
> -Chuckk
>
>
>
> On Sun, May 4, 2008 at 12:39 PM, Protected <[EMAIL PROTECTED]> wrote:
> > Good thinking. It was indented with spaces, so I replaced them with tabs.
> > Now I'm getting a SyntaxError: invalid syntax in root = Tk(). If I split the
> > code in two parts (with the second one beginning in that line) and run them
> > separately, I get no errors, but still nothing happens.
>
> > class Application(Frame):
> > def say_hi(self):
> > print "hi there, everyone!"
>
> > def createWidgets(self):
> > self.QUIT = Button(self)
> > self.QUIT["text"] = "QUIT"
> >  self.QUIT["fg"]   = "red"
> > self.QUIT["command"] =  self.quit
>
> > self.QUIT.pack({"side": "left"})
>
> > self.hi_there = Button(self)
> >  self.hi_there["text"] = "Hello",
> > self.hi_there["command"] = self.say_hi
>
> > self.hi_there.pack({"side": "left"})
>
> > def __init__(self, master=None):
> >  Frame.__init__(self, master)
> > self.pack()
> > self.createWidgets()
>
> > var root = Tk()
> > app = Application(master=root)
> > app.mainloop()
> > root.destroy()
>
> > On Sun, May 4, 2008 at 12:33 PM, Q4 <[EMAIL PROTECTED]> wrote:
>
> > > On Sun, 4 May 2008 02:23:37 -0700 (PDT), Protected <[EMAIL PROTECTED]>
> > > wrote:
>
> > > > Hello. I'm a complete newbie trying to learn Python. I decided to try
> > > > some Tkinter examples, including the one from the library reference,
> > > > but they don't seem to do anything! Shouldn't there be, like, a
> > > > dialog?
>
> > > > I'm running Windows XP and using IDLE. You can assume my version of
> > > > Python is the latest.
> > > > --
> > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > If you just copy the code from the python doc the indentation might be
> > > broken.
> > > Send the code and I'll take a look at it.
>
> > > Do you get any errors?
>
> > > --
> > > My website:
> > >  http://www.riddergarn.dk/koder/
>
> > --
> >  http://mail.python.org/mailman/listinfo/python-list
>
> --http://www.badmuthahubbard.com

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


Re: Please help - Tkinter not doing anything

2008-05-04 Thread Protected
On May 4, 12:18 pm, [EMAIL PROTECTED] wrote:
> On May 4, 5:22 am, Protected <[EMAIL PROTECTED]> wrote:
>
> > I had previously ran the import line. I prepended it to the example
> > code I'm trying to run every time but it did not help, still nothing
> > happens. With or without var before 'root'. I'm pasting the code in
> > IDLE and using Windows XP as written in the first post.
>
> Tkinter doesn't work if you type the statements in IDLE. I don't
> remember the specifics of it, but essentially it doesn't work because
> IDLE is itself a Tkinter app. You have to type it at the Python
> command line or save it in a file. BTW, if you're on Windows, you
> should definitely check wxPython. I used to work with Tkinter,
> struggling with it all the time only to get a lame result most of the
> time. Then I switched to wxPython, and in the same week I was learning
> it I did a better GUI than I ever did in Tkinter (with months of
> work!). I feel it makes it easier to make your program have a better
> structure and design, and thus lets you focus on the actual task of
> the program, rather than in the GUI itself. Plus, on Windows, you'll
> get the widgets to look more natively, like any good quality
> application there is on Windows.

Ah, but is it cross platform?

(Thanks for letting me know about IDLE.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Character Sequence Generation

2005-09-22 Thread [EMAIL PROTECTED]

Jeff Schwab wrote:
> What's the best way to generate a sequence of characters in Python?  I'm
> looking for something like this Perl code: 'a' .. 'z' .

>>> import string

>>> print string.ascii_lowercase
abcdefghijklmnopqrstuvwxyz


Others:

ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
letters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv...\xcd\xce...
lowercase =
'abcdefghijklmnopqrstuvwxyz\x83\x9a\x9c\x9e\xaa\xb5\xba\xd...
octdigits = '01234567'
printable =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU...
punctuation = '!"#$%&\'()*+,-./:;<=>[EMAIL PROTECTED]|}~'
uppercase =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ\x8a\x8c\x8e\x9f\xc0\xc1\xc2\xc...
whitespace = '\t\n\x0b\x0c\r '

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


Re: subprocess.Popen and replacing the shell pipe line

2005-09-23 Thread [EMAIL PROTECTED]
by the way, you're re-inventing the wheel somewhat, check out the
stdlib pipes module (http://docs.python.org/lib/module-pipes.html)

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


Re: File processing

2005-09-23 Thread [EMAIL PROTECTED]
The ConfigParser class is designed for this task, see
http://docs.python.org/lib/module-ConfigParser.html

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


Re: batch mkdir using a file list

2005-09-23 Thread [EMAIL PROTECTED]

Jeremy Jones wrote:
> DataSmash wrote:
>
> >Hello,
> >I think I've tried everything now and can't figure out how to do it.
> >I want to read in a text list from the current directory,
> >and for each line in the list, make a system directory for that name.
> >
> >My text file would look something like this:
> >1144
> >1145
> >1146
> >1147
> >
> >I simply want to create these 4 directories.
> >It seems like something like the following
> >code should work, but it doesn't.
> >
> >import os
> >
> >file = open("list.txt", "r")
> >read = file.read()
> >print "Creating directory " + str(read)
> >os.mkdir(str(read))
> >
> >Appreciate any help you can give!
> >R.D.  Harles
> >
> >
> >
> Untested code:
>
> import os
> for line in open("list.txt", "r"):
> os.mkdir(line)

That won't work (in Windows at least) because you have
to remove the "\n" from the line before you pass it to
os.mkdir.


> 
> 
> - JMJ

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


HTML to LaTeX RE pattern and sub

2005-09-23 Thread [EMAIL PROTECTED]
Hi,

trying to make a small script which would translate wiki file into
LaTeX and when trying to translate possible HTML elements into LaTeX I
did this:

def latexEnvironments(matchobj):
print >>sys.stderr,str(matchobj.groups())
inStr = matchobj.group(1)
translDict = {'dl': ('\\begin{description}','\\end{description}'),
'ol': ('\\begin{enumerate}','\\end{enumerate}'),
'ul': ('\\begin{itemize}','\\end{itemize}'),
'blockquote': ('\\begin{quote}','\\end{quote}'),
'center': ('\\begin{center}','\\end{center}'),
'li': ('\\item',''),
'pre': ('\\begin{ttfamily}','\\end{ttfamily}')}
if translDict.has_key(inStr):
retTuple = translDict[inStr]
else:
retTuple = ('','')
if matchobj.group(0) == '/':
return retTuple[1]
else:
return retTuple[0]

def latexHeadings(matchobj):
print >>sys.stderr,str(matchobj.groups())
inStr = matchobj.groups[1]
translDict = {'h1': '\\section{}',
'h2': '\\subsection{}',
'h3': '\\subsubsection{}',
'h4': '\\subsubsubsection{}',
'h5': '\\paragraph{}'}
if translDict.has_key(inStr) and (matchobj.groups[0] != '/'):
return translDict[inStr]
else:
return ''

def latexEmptyElements(matchobj):
retString = ""
print >>sys.stderr,str(matchobj.groups())
inStr = matchobj.group(0)
translDict = {'br//': '',
'hr': '\\par{}\\hrulefill{}\\par{}'}
if translDict.has_key(inStr):
return translDict[inStr]
else:
return ''



[... snip ...]

# Remove superfluous HTML elements
reEnvironments =
re.compile(r'<(/?)(dl|ol|ul|address|blockquote|center|del\
|ins|div|isindex|noscript|p|pre)>',re.IGNORE)
reHeadings = re.compile(r'<(/?)(h1|h2|h3|h4|h5|h6)>',re.IGNORE)
reEmpty = re.compile(r'<(hr|br)\s*/?>',re.IGNORE)
body = reEnvironments.sub(latexEnvironments,body)
body = reHeadings.sub(latexHeadings,body)
body = reEmpty.sub(latexEmptyElements,body)

The problem is that apparently RE never matches (and no function is
thus called). Can anybody tell me what's wrong with my REs, please?

Thanks for any help,

Matej

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


Re: Help installing Python 2.3 on Win2K

2005-09-23 Thread [EMAIL PROTECTED]

D.S. Hein wrote:
> I have installed python 2.3 on my Windows 2K laptop and I can run python
> from the command prompt.
>
> I have tried various ways to set PYTHONPATH with the various directories
> where I have python programs (i.e. xx.py) but no matter how I set
> PYTHONPATH I keep getting a message that python can't open the python
> file. If I try to specify the full pathname by typing: python
> c:\Documents and Settings\-rest of path- I get an error message that
> python can't open c:\Documents.

Put the path inside quotation marks just as you would any other
command.

C:\>dir C:\documents and settings\a*
The system cannot find the file specified.

C:\>dir "C:\documents and settings\a*"
 Volume in drive C is PXXABA
 Volume Serial Number is 90C0-740E

 Directory of C:\documents and settings

07/16/2001  08:40aAdministrator
07/29/2005  08:20aAll Users
   0 File(s)  0 bytes
   2 Dir(s) 772,973,568 bytes free

>
> The ways I have set PYTHONPATH are by directly changing the registry
> entry for Python 2.3, by setting the environment variable by
> right-clicking on My Computer and by adding set PYTHONPATH=-various
> pathnames-.
> 
> I'd be grateful for any guidance on how to organize my system.

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


RE + UTF-8

2005-09-24 Thread [EMAIL PROTECTED]
Working on extension of genericwiki.py plugin for PyBlosxom and I have
problems with UTF-8 and RE. When I have this wiki line, it does break
URL too early:

[http://en.wikipedia.org/wiki/Petr_Chelcický Petr Chelcický's]
work(s) into English.

and creates

[http://en.wikipedia.org/wiki/Petr_Chel";>http://en.wikipedia.org/wiki/Petr_Chelcický
Petr Chelcický's]

The RE genericwiki uses for parsing this:

# WikiName pattern used in your wiki
wikinamepattern = r'\b(([A-Z]\w+){2,})\b' # original
mailurlpattern = r'mailto\:[\"[EMAIL PROTECTED]'
newsurlpattern = r'news\:(?:\w+\.){1,}\w+'
fileurlpattern =
r'(?:http|https|file|ftp):[/-_.\w-]+[\/\w][?&+=%\w/-_.#]*'

[...]

# Turn '[xxx:address label]' into labeled link
body = re.sub(r'\[(' +
   fileurlpattern + '|' +
   mailurlpattern + '|' +
   newsurlpattern + ')\s+(.+?)\]',
   r'\2', body,re.U)

I have tried to test RE and UTF-8 in Python generally and the results
are even more confusing (done with locale cs_CZ.UTF-8 in konsole):

>> locale.getpreferredencoding()
'UTF-8'
>>> print re.sub("(\w*)","X","[Chelcický]",re.L)
X[X?Xý]
>>> print re.sub("(\w*)","X","[Chelcický]",re.UNICODE)
X[X?X?X]X
>>>

I would expect that both print commands should give just plain X, but
apparently Python doesn't undestand that. What's the problem?

Thanks for any reply,

Matej

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


py2exe and OpenGL problem

2005-09-25 Thread [EMAIL PROTECTED]
I am using the new py2exe and python 24. When I run my setup.py, the
dist seems to generate just fine. However run I run the resulting exe,
I get an error:

IOError: [Errno 2] No such file or directory
'c:\\app\\dist\\library.zip\\OpenGL\\version'

Now I've tried the recommended route with older py2exes, where I
exclude OpenGL and copy the entire directory over to my dist, but that
didn't work. I included "version" into the "OpenGL" directory via my
setup.py script, and it is there right in the library.zip, but I still
get the same error.

Anyone have any ideas or suggections?

Thanks,
Patrick

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


Re: Alternatives to Stackless Python?

2005-09-25 Thread [EMAIL PROTECTED]
Honestly I am not knowledgeable about either option but mainly I was
specifically targetting my feature set towards the things that a higher
level game engine would need such as the one described here:
http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/
Which I guess the main difference that I see between stackless and
NanoThreads is the ability to communicate between threads through
channels and other methods. This is very important in games where the
actors need to communicate among each other to create interactive and
interesting gameplay.

And perhaps scheduling overhead, memory costs and slow thread creation
could be otherh areas where the two differ (but I am unsure). And
finally, how good is NanoThreads at non-preemptive multithreading and
event-driven control? These are more areas that I see the two possibly
differing.

Also, Greenlets look really interesting, I will have to evaluate these
more closely.

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


Re: good exercises for Beginner

2005-09-26 Thread [EMAIL PROTECTED]
try this...
http://www.awaretek.com/tutorials.html

Cheers,
pujo

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


Python batching on XP

2005-09-27 Thread [EMAIL PROTECTED]
Hi !

I want to write a program that backup some databases in the night.

Pseudo like this:

try:
if cmd('net stop dbservice'):
   s=c://backup'+str(time.time())+'.zip'
   if cmd('zipit c:\\database '+s):
  if cmd('map drive backupdrive\\c$ y -user BACKUP -pwd SECRET'):
 if cmd('copy '+s+' y:\\'):
LogSucc()
finally:
  cmd('net start dbservice')

I'm trying with os.system() commands.
But that is printing the result message to the screen, not to a tuple, 
like commands.|getstatusoutput().
I need to store this message, because I want to log everything that this 
program do/print; every of the messages.

So: how to I capture the screen, or how to I use 
|commands.|getstatusoutput() to access the Windows batch/cmd commands, 
and get their errors/statuses ?

Please help me !

Thanks for it: dd
|
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python batching on XP

2005-09-28 Thread [EMAIL PROTECTED]
Hi !

I have Py 2.3.5, and subprocess is placed in version 2.4.

The os.popen is not good, because it is not get return value. I can read 
the return value, but the message is os dependent (XP, 2k, NT).
I create this function. It is not too good, but it is working:

def Cmd(cmd,tmpdir="./"):
outfn='%s/_out.msg'%tmpdir
errfn='%s/_err.msg'%tmpdir
post="1>%s 2>%s"%(outfn,errfn)
cmd2='%s %s'%(cmd,post)
r=os.system(cmd2)
f=open(outfn,"r")
try:
   s1=f.read()
finally:
   f.close()
f=open(errfn,"r")
try:
   s2=f.read()
finally:
   f.close()
s="\n".join([s1,s2]).strip()
return (r,s)

Anyone have a better idea ?

Thanks for it: dd



Larry Bates wrote:

>You should take a look at the subprocess module
>http://www.python.org/dev/doc/devel/lib/module-subprocess.html
>
>-Larry Bates
>
>[EMAIL PROTECTED] wrote:
>  
>
>>Hi !
>>
>>I want to write a program that backup some databases in the night.
>>
>>Pseudo like this:
>>
>>try:
>>if cmd('net stop dbservice'):
>>  s=c://backup'+str(time.time())+'.zip'
>>  if cmd('zipit c:\\database '+s):
>> if cmd('map drive backupdrive\\c$ y -user BACKUP -pwd SECRET'):
>>if cmd('copy '+s+' y:\\'):
>>   LogSucc()
>>finally:
>> cmd('net start dbservice')
>>
>>I'm trying with os.system() commands.
>>But that is printing the result message to the screen, not to a tuple,
>>like commands.|getstatusoutput().
>>I need to store this message, because I want to log everything that this
>>program do/print; every of the messages.
>>
>>So: how to I capture the screen, or how to I use
>>|commands.|getstatusoutput() to access the Windows batch/cmd commands,
>>and get their errors/statuses ?
>>
>>Please help me !
>>
>>Thanks for it: dd
>>|
>>
>>

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


Re: Human readable number formatting

2005-09-28 Thread [EMAIL PROTECTED]

MrJean1 wrote:
> No, I didn't.  See the references at the bottom.
>
> /Jean Brouwers

So when I say "I'm sorta busy" it means I'm REALLY busy.

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


How to increment a date, and how to convert it ?

2005-09-29 Thread [EMAIL PROTECTED]
Hi !

1.
I have a code. I want to convert from wx.DatePickerCtrl.Value to 
mx.DateTime.
But I don't know, how to do it simply.

2.
I need to increment this date by 6 days.
How to do it ? (I search for a simple way, like Delphi-s d2:=d1+6)


The code section is:

from mx import DateTime as mxDT
v=self.datePickerCtrl1.GetValue()
print type(v),v # wx._misc.DateTime
d1=mxDT.Date(2005,01,01)
print type(d1),d1  # DateTime

Thanks for advance: dd



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


getattr

2005-09-30 Thread [EMAIL PROTECTED]
This question is regarding the __getattr__ function defined for every
object.
Consider the following example

Assume that foo is an instance of class Foo, and the following are
references to foo's field "bar" which is an instance of class Bar

a) foo.bar
b) foo.bar.spam - spam is a member of "bar"

I want the above references to be handled by __getattr__. Hence I do
not have an entry for the 'bar' in foo.__dict__

Is there any  way by which the __getattr__(self,attr) method can
determine that in
case a) attr == 'bar' is the final component in the reference unlike in
case b) where attr=='bar' is NOT the ultimate(final) component of
reference and is an intermediate component in the reference.

tia

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


Re: MS Word mail merge automation

2005-09-30 Thread [EMAIL PROTECTED]

Steve M wrote:
> I'm trying to do invoke the mail merge functionality of MS Word from a
> Python script. The situation is that I have a template Word document,
> and a record that I've generated in Python, and I want to output a new
> Word .doc file with the template filled in with the record I've
> generated.
>
> (To refresh your memory, in Word a mailmerge is achieved by a) under
> Tools -> Letters and Mailings, check off Show Mail Merge Toolbar; b)
> open a document with template-style variables in the form of
> <>; c) on Toolbar select Open Data Source and select
> appropriate Access or Excel or CSV file (with column headers
> corresponding to the FIELD_NAME's in your template variables); and then
> d) on Toolbar select Merge To New Document to create a new document
> with the template variables replaced with the value from the
> corresponding column in the data source - here, you can make one
> document per row of data source, or just one document for a given row.
> Don't forget to save the new document.)
>
> Using various online sources*, I have been able to piece together all
> but (what I hope is) the final missing piece, viz., the name of the
> method that corresponds to "Merge to New Document" command from within
> the Word interface.
>
> Here is the basic code, if anyone can provide the missing piece I (and
> others, I suspect) would appreciate it:
>
>
> import os, win32com.client
> doc_template_name = os.path.abspath('template.doc')
> data_source_name = os.path.abspath('record23.csv')
> doc_final_name = os.path.abspath('record23.doc')
>
> app = win32com.client.Dispatch("Word.Application")
> doc = app.Documents.Open(doc_template_name)
>
> #attach data source to template
> doc.MailMerge.OpenDataSource(data_source_name)
>
> #merge to new document - THIS RAISES ATTRIBUTE ERROR, HOW TO FIX?
> new_doc = doc.MailMerge.MergeToNewDocument()

In VBA, it would be .Execute.

>From the VBA Help file:

This example executes a mail merge if the active document is a main
document
with an attached data source.

Set myMerge = ActiveDocument.MailMerge
If myMerge.State = wdMainAndDataSource Then MyMerge.Execute



>
> #save out result
> new_doc.SaveAs(doc_final_name)
>
> #cleanup
> doc.Close()
> new_doc.Close()
> app.Quit()
>
>
>
>
> *I found some information here:
> http://64.233.161.104/search?q=cache:V-xpWKigqVQJ:coderforums.com/archive/topic/1514-1.html+win32com+merge+to+new+document&hl=en
>
> and here:
> http://www.brunningonline.net/simon/blog/archives/001299.html
>
> as well as here:
> http://www.win32com.de/index.php?option=com_content&task=category§ionid=7&id=86&Itemid=192
>
> I also have the Hammond and Robinson book on Python on Win32 but it
> hasn't helped me to discover the method name.

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


Re: OT: Phases of the moon [was Re: A Moronicity of Guido van Rossum]

2005-09-30 Thread [EMAIL PROTECTED]

Steven D'Aprano wrote:
> On Fri, 30 Sep 2005 18:02:14 -0400, Sherm Pendley wrote:
>
> > [EMAIL PROTECTED] writes:
> >
> >> I wonder if his postings are related to the phases of the moon? It
> >> might explain a lot.
> >
> > Yes, it would. Note that the word lunatic is derived from the Latin word
> > luna, meaning moon.
>
> Yes, lunatic is derived from luna, but that doesn't mean the two are
> connected. The ancients believed a lot of crap (the world is flat, black
> people aren't human, thunder is the sound of god's fighting, buying
> over-valued dot-com stock is a good investment) and "phases of the moon
> affecting behaviour" was one of them.
>
> People are really bad at connecting cause and effect. See this thread for
> a simple example:
>
> http://msgboard.snopes.com/cgi-bin/ultimatebb.cgi?ubb=get_topic;f=42;t=000228;p=1
>
> A skeptical policeman who says he doesn't actually believe the moon
> affects behaviour nevertheless reports that "last weekend" things were
> really crazy, and it was a full moon. Somebody writes in to correct him:
> no, the full moon is actually "tomorrow".
>
> This shows how cognitive biases can fool us. Even though he was skeptical,
> the cop noticed the extra crazy behaviour on this particular weekend, and
> manged to fool himself into thinking it matched a full moon.
>
> See here for more details, plus references to research:
>
> http://skepdic.com/fullmoon.html

But correlations can exist even if the cause does not. There is a
correlation between the equinox and balancing an egg. But not
_because_ of the equinox, but because people only try it on the
equinox. Hence, egg balancing only happens on the equinox is a
true assertion.

> 
> 
> -- 
> Steven.

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


Re: A Moronicity of Guido van Rossum

2005-09-30 Thread [EMAIL PROTECTED]
I have an excellent idea. Create your own programming language and do
whatever you want with it. Until then, I'm thinking that Guido can do
whatever he wants with his. But I'm guessing that your programming
skills will be in the same place as your greatness - in your own head.

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


Re: Printing and prompting adds a mysterious extra space

2005-10-01 Thread [EMAIL PROTECTED]

Christoph Haas wrote:
> Evening...
>
> I'm writing a simple interactive program to maintain a database.
> The goal was to print "> " at the beginning of the line, wait for
> user input and then deal with it. Minimal test program:
>
> import sys; print ">", ; print sys.stdin.readline()
>
> However when I run the program and enter "foobar" it looks like this:
>
> ./test.py
> >foobar
>  foobar
> ^--- where does this space come from?
>
> I wonder where the space comes from in the line where I print what the
> user typed. Does it have to do with the "," after the print which I use
> to suppress the newline? Any ideas?

Another question you could ask is: why is there NO space after
the '>'? Have a look at this.

import sys

print ">",

s = sys.stdin.readline()

print len(s)
print s
for i in s:
print ord(i),i

Instead of printing the input, I'm assigning it to a variable.
Notice that the extra space appears on the next print statement
and is not part of the input. this is verified by showing that
the input has exactly 4 characters and is "huh\n".

>>>
>huh
 4
huh

104 h
117 u
104 h
10


So it looks like the space was sitting in the output buffer.

>
> Regards
>  Christoph
> --
> I'm still confused - just on a higher level now.
> ~
> ~
> ".signature" [Modified] 1 line --100%--1,48 All

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


Re: how to send a SIGINT to a Python process?

2005-10-02 Thread [EMAIL PROTECTED]
AFAIK there isn't. You could browse through this
http://starship.python.net/crew/tmick/ to get an idea on how to kill on
both platforms.

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


Re: Python for search engine development

2005-10-02 Thread [EMAIL PROTECTED]
Well, Google applies some Python in their implementation, see
http://www-db.stanford.edu/~backrub/google.html

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


Re: "no variable or argument declarations are necessary."

2005-10-02 Thread [EMAIL PROTECTED]
The easiest way to avoid this problem (besides watching for NameError
exceptions) is to use an editor that has automatic name completion.
Eric3 is a good example. So, even though in theory it could be an
issue, I rarely run into this in practice. 

-Don

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


Re: forum

2005-10-02 Thread [EMAIL PROTECTED]
is there any forum writen by python like vbb...phped

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


Py2Exe + kinterbasdb

2005-10-03 Thread [EMAIL PROTECTED]
Hi !

I compile an application (that working good in native python) to exe 
with py2exe.
In native mode (python.exe ReportApp.py) it is working, the reports are 
created good.
But when I try to create a report from the compiled exe, it is show an 
error:

Traceback (most recent call last):
  File "Report01.pyc", line 164, in OnButton1Button
  File "report_01.pyc", line 12, in OpenDBForReport
  File "report_db.pyc", line 11, in OpenDB
  File "kinterbasdb\__init__.pyc", line 472, in connect
  File "kinterbasdb\__init__.pyc", line 558, in __init__
  File "kinterbasdb\__init__.pyc", line 367, in _ensureInitialized
  File "kinterbasdb\__init__.pyc", line 315, in init
ImportError: No module named typeconv_backcompat

The OpenDB is do this:

def OpenDB(paramdb):
dsn=paramdb.get('PATH','')
usr=paramdb.get('USER','sys'+'dba')
pwd=paramdb.get('PASSWORD','any')
global DB
DB=kim.connect(dsn=dsn, user=usr,password=pwd)
return DB

It seems to be that the problem occured in __init__.pyc.
How to I prevent it ?

Please help me !
Thanks. For any help.

K. O. R. : dd



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


Re: Idle

2005-10-04 Thread [EMAIL PROTECTED]
If you are compiling python and you want to build idle/tkinter, you
need to have the development packages for tcl and tk. The python build
scripts will only build tkinter should they find the libraries
(libtk8.4.so and libtcl8.4.so) and the header files (tk.h and tcl.h).
If you don't have the development packages installed, you most likely
do not have the header files.

If you install the development packages and recompile, test by
importing _tkinter. If that is successful, idle should run just fine.

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


Re: While and If messing up my program?

2005-10-05 Thread [EMAIL PROTECTED]
hi,

to get howmany element list appear you can code:
ttllst=[4,3,45,3]
for x in ttllst:
print x, ttllst.count(x)
pass

to get non duplicate element list you can code:
ttllst=[4,3,45,3] 
print list(set(ttllst))

Cheers,
pujo

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


Quick help needed: how to format an integer ?

2005-10-05 Thread [EMAIL PROTECTED]
Hi !

I need to convert some integer values.

"1622" ->"1 622"

or

"10001234" -> ""10.001.234""

So I need thousand separators.

Can anyone helps me with a simply solution (like %xxx) ?

Thanx for it: dd

Ps:
Now I use this proc:

def toths(i):
s=str(i)
l=[]
ls=len(s)
for i in range(ls):
c=s[ls-i-1]
if i%3==0 and i<>0:
   c=c+"."
l.append(c)
l.reverse()
return "".join(l)



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


Can Python replace TCL/Expect

2005-10-05 Thread [EMAIL PROTECTED]
Hi

I'm learning Python. I don't know whether Python can do something like
Expect can do. If yes, please show me how to do it.
I want to do something automatically: open connection to a ftp server,
get the welcome message on the screen (not in the packet). I can do it
easily with Expect but I still don't have any idea with Python.
If possible, can you introduce me some book or website that I can get
infor about automation programming with Python

Thanks

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


Re: non descriptive error

2005-10-07 Thread [EMAIL PROTECTED]
You should tell us more about DutyShift.py, without the code it is very
difficult for other people to guess what's going on.

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


Re: Python interpreter bug

2005-10-07 Thread [EMAIL PROTECTED]
Your __cmp__ method will always return 0, so all objects will be equal
when you add the method, as Simon and Steve pointed out. The result is
all objects will pass the test of being a member of excluded.
If you do not add a __cmp__ method objects will be compared on identy -
call the id() function to see the identity of an object. An alternative
would be Steve's proposal to compare on the id attribute instead of the
allocated attribute

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


Re: Python interpreter bug

2005-10-07 Thread [EMAIL PROTECTED]
Your __cmp__ method will always return 0, so all objects will be equal
when you add the method, as Simon and Steve pointed out. The result is
all objects will pass the test of being a member of excluded.
If you do not add a __cmp__ method objects will be compared on identy -
call the id() function to see the identity of an object. An alternative
would be Steve's proposal to compare on the id attribute instead of the
allocated attribute

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


Re: Python interpreter bug

2005-10-07 Thread [EMAIL PROTECTED]
For this, you can also define the __eq__ method, which will be
preferred to __cmp__ for equallity tests while still using __cmp__ for
searching / comparisons.

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


GUI on Macintosh

2005-10-07 Thread [EMAIL PROTECTED]
I am using Python 2.3.3 on an Mac OS9 system.  I am looking for a build
of Python 2.3.3+ with a built in GUI, since Tk is missing.  One day I
hope to upgrade to a new Mac with OSX on it, so a GUI that is available
on OS9 and OSX is preferable.  I don't want to write my GUI code from
scratch if I ever manage to upgrade.

Any suggestions?

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


Re: noob question Letters in words?

2005-10-07 Thread [EMAIL PROTECTED]

Ivan Shevanski wrote:
> Alright heres another noob question for everyone.  Alright, say I have a
> menu like this.
>
> print "1. . .Start"
> print "2. . .End"
> choice1 = raw_input("> ")
>
> and then I had this to determine what option.
>
>
> if choice1 in ('1', 'Start', 'start'):
> #do first option
> if choice1 in ('2', 'End', 'end'):
> #do second option
>
> Is there a way (I searched for a module but didnt find one) that I can do
> something like this?
>
> if choice1 in ('1', 'S', 's'):
> #do first option
> if choice1 in ('2', 'E', 'e'):
> #do second option

Why not just look at the first letter the user types instead of
the whole string?

 if choice1[0] in ('1', 'S', 's'):
 #do first option
 if choice1[0] in ('2', 'E', 'e'):
 #do second option


>
>
> For instance I could type in Stop and would get the first option since it
> had an "s" in it?
> Anyone heard of any way to do this?
>
> Thanks,
> -Ivan
>
>
>
> By the way, if anyone gets tired of my persistant noob questions please tell
> me I don't want to bother anyone =D
>
> _
> Express yourself instantly with MSN Messenger! Download today - it's FREE!
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-07 Thread [EMAIL PROTECTED]

Luis M. Gonzalez wrote:
> Grant Edwards ha escrito:
> > While we're off this topic again topic, I was watching a BBC
> > series "Space Race" the other night.  The British actors did a
> > passable job with the American accents in the scenes at Fort
> > Bliss in Texas, but the writers wrote British English lines for
> > them to speak in their American accents...
>
>
> Continuing with this off-topic thread about british accent and
> movies...
> I've always asked myself why do Hollywood movies about the Roman Empire
> show the Emperors and all the nobles speaking with british accent?
> They were italians for God's sake!
>
> Anyway, I can't imagine Julius Caesar speaking like Vito Corleone...

Of course not! Vito Corleone was Sicilian.

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


Re: Contest snub?

2005-10-08 Thread [EMAIL PROTECTED]

Will McGugan wrote:
> [EMAIL PROTECTED] wrote:
> > Notice anything strange here? The Python entry seems to have edged the PHP
> > entries, but is not declared the victor. Source is missing as well (the 
> > archive
> > is empty.)
> >
> > http://www.apress.com/promo/fractal/seesource.html
> >
> > H... an irrational fear of snakes perhaps?
>
> Its not irrational if you are a gator!

Furthermore, just because you're paranoid doesn't mean people aren't
out
to get you.

>
> Will McGugan
> --
> http://www.willmcgugan.com
> "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in
> "jvyy*jvyyzpthtna^pbz")

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


"import socket" error

2005-10-09 Thread [EMAIL PROTECTED]
Hi,

I am following this tutorial
https://www14.software.ibm.com/webapp/iwm/web/preLogin.do?source=dw-linux-pysocks&S_TACT=105AGX59&S_CMP=GR&ca=dgr-lnxw07PythonSockets
( free reg. req. )

The article told me to do this:

[camus]$ python
Python 2.4 (#1, Feb 20 2005, 11:25:45)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more
   information.
>>> import socket
>>> socket.gethostbyname('www.ibm.com')
'129.42.19.99'
>>>

When I try it, I get this error:
>>> import socket
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.4/socket.py", line 1, in ?
# Wrapper module for _socket, providing some additional facilities
  File "/usr/lib/python2.4/SocketServer.py", line 274, in ?
class TCPServer(BaseServer):
  File "/usr/lib/python2.4/SocketServer.py", line 317, in TCPServer
address_family = socket.AF_INET
AttributeError: 'module' object has no attribute 'AF_INET'
>>>


Why? Thank you.

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


The missing ingredient?

2005-10-09 Thread [EMAIL PROTECTED]
Python is a great programming language, and it seems there was a sense
of fun in developing it -- as far as I can ascertain, it wasn't exactly
brought to life to comply with Government tax regulations; or to assist
a consigliere with covering up ghastly mob crimes ala "Godfather".

Though there is some guy named Guido involved... [and not neccesarily
Father Guido Sarducci...]


Is Python still as fun to develop (develop, not develop in)?  Can the
pioneers weigh in on this?

"Fun" is held by many to be the (or one of the) most creative,
inventive, and productive frames of mind.

For example I suspect, despite all the varied things they may be
exposed to, very few patents are filed by IRS agents; unless, perhaps,
they get ideas while unwinding late at night watching Monty Python
reruns (which activity may be career limiting in Government service!)


Is developing the next iteration/step-forward in Python still as fun as
the old days?  Is it fun?

What can we do to keep Python (development of and development in) as
fun as possible?

[this post triggered by reading this article on "-Ofun" here:
http://www.oreillynet.com/pub/wlg/7996]


EP

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


Re: Comparing lists

2005-10-10 Thread [EMAIL PROTECTED]
try to use set.
L1 = [1,1,2,3,4]
L2 = [1,3, 99]
A = set(L1)
B = set(L2)

X = A-B
print X

Y = B-A
print Y

Z = A | B
print Z

Cheers,
pujo

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


Let My Terminal Go

2005-10-10 Thread [EMAIL PROTECTED]
Hello,

A user of my application points me to a behavior in gVim,
the text editor, that I would like to implement in my
application.

When gVim is launched from a shell terminal, it completely
frees the terminal. You can continue to use the terminal for
whatever purpose you wish, including closing and exiting it,
without any effect on the running gVim instance.

How do I implement this in my application written in python?
I would like to believe it does not involve me forking my
application in a new process. Maybe there is signal I can
send to the operating system to achieve this, right?

Your help is appreciated.

Thanks

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


Re: datetime and daylight savings problem

2005-10-11 Thread [EMAIL PROTECTED]
When working with timezones datetime objects are represented in the
tzinfo object you supply, eg. when you define these classes (and run
them on a system set to  Paris time):

from datetime import tzinfo, timedelta, datetime
import time

class UTC(tzinfo):
"""UTC timezone"""
def utcoffset(self, dt):
return timedelta(0)

def tzname(self, dt):
return "UTC"

def dst(self, dt):
return timedelta(0)

class CET(tzinfo):
"""CET timezone"""
def utcoffset(self, dt):
return timedelta(seconds = -time.timezone)
def dst(self, dt):
return timedelta(0)
def tzname(self, dt):
return "CET"


class CEST(tzinfo):
"""CET timezone with DST"""
def utcoffset(self, dt):
return timedelta(seconds = -time.altzone)
def dst(self, dt):
return timedelta(seconds = -time.altzone) - \
timedelta(seconds = -time.timezone)
def tzname(self, dt):
return "CEST"

And you create these objects:

utc = UTC()
cet = CET()
cest = CEST()
d = datetime(2005,06,01,16,59,tzinfo=utc)

This statement
print 'UTC %s' % d
Will print:
UTC 2005-06-01 16:59:00+00:00

And this one:
print 'As CET %s' % d.astimezone(cet)
Will print:
As CET 2005-06-01 17:59:00+01:00

And this one:
print 'As CET with DST %s' % d.astimezone(cest)
Will print:
As CET with DST 2005-06-01 18:59:00+02:00

Additional:
This:
d = datetime(2005,06,01,16,59,tzinfo=cet)
print cet, d

Will print:
<__main__.CET object at 0xb7d3aaac> 2005-06-01 16:59:00+01:00

And this:
d = datetime(2005,06,01,16,59,tzinfo=cest)
print cest, d
Will print:
<__main__.CEST object at 0xb7d3aaec> 2005-06-01 16:59:00+02:00

So at least with these tzinfo objects everything is as expected, I'm
not sure where your actual problem is, is it in the pytz module (with
which I do not have experience)?

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


Re: Parser suggestion

2005-10-11 Thread [EMAIL PROTECTED]
Take a look at PLY.
There is an example lexer in the download for parsing fortran.

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


Bad magic no. in python zipfile

2005-10-12 Thread [EMAIL PROTECTED]
I've been experimenting with the python zipfile module, and have run
into a snag.

I'm able to create a new zipfile with the module's ZipFile class and
add files to it.  After closing the file, I'm able to view the contents
of it with WinZip.  I can also confirm that it is a python zip file by
using the is_zipfile() method.  All good so far.  However, under some
circumstances, I am unable to later read the file and extract its
contents.  As soon as a I attempt to instantiate a new ZipFile
instance, I receive an error regarding Bad Magic number.   In the past,
I've seen that when trying to use a .pyc module, created with one
Python version, using another Python version.  But in this case, I
created the zip file under Python 2.4.2 and tried to open it under
Python 2.4.2 as well.  Any ideas on what to do?  (apart from giving up
on Python and using winzip?)

On a separate topic, zipfile wasn't available under Python 1.5.2. I
need to create zip files using that old version, since it's the only
one installed on a remote server.  Any suggestions on what to do?

thanks
S

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


how to make this code faster

2005-10-12 Thread [EMAIL PROTECTED]
def f(x,y):
return math.sin(x*y) + 8 * x
I have code like this:

def main():
n = 2000
a = zeros((n,n), Float)
xcoor = arange(0,1,1/float(n))
ycoor = arange(0,1,1/float(n))


for i in range(n):
for j in range(n):
a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x

print a[1000,1000]
pass

if __name__ == '__main__':
main()


I try to make this run faster even using psyco, but I found this still
slow, I tried using java and found it around 8x faster...


public class s1 {


/**
 * @param args
 */
public static int n = 2000;
public static double[][] a = new double[n][n];
public static double [] xcoor = new double[n];
public static double [] ycoor = new double[n];


public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=0; ihttp://mail.python.org/mailman/listinfo/python-list


Re: how to make this code faster

2005-10-13 Thread [EMAIL PROTECTED]
hello,

I found that scipy only works with python 2.3 or?

I don't know if the logic is correct:
1. loop inside loop uses a lot of resources
2. Numeric or Numpy can make program faster
3. It use kind of Array/Matrix analysis style
4. We have to change our algorithms so that Numeric or Numpy can help
us, Matrix style

Best Regards,
pujo

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


Re: Bad magic no. in python zipfile

2005-10-13 Thread [EMAIL PROTECTED]
okay, I've figured out the problem - the zip file was being mangled by
a file transfer.  I was fetching a remote python-generated zip file in
8k chunks, and then writing those chunks to a file.  At first I was
using an array to store the data in, and had the 'bad magic number'
problem.  This may have been due to writing the chunks out to a local
file as strings, which would definitely have corrupted the file; I also
noticed that the local copy was several kb larger, probably due to the
line endings being added.  When I took care to write the file as a
binary file, all was well. case closed.

BTW, regarding using zipfile under Python 1.5.2... I found zipfile.py
in Python 1.6, but it wouldn't run.  You need to build Python 1.5 with
the binascii.c and zlibmodule.c from Python 1.6, since a CRC32 method
has been added to those modules.  This was more trouble than it was
worth, in the end. 

S

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


Re: UI toolkits for Python

2005-10-14 Thread [EMAIL PROTECTED]
I find wxPython to pro fill my GUI needs from python in a pretty good
way.
To show off it's capabilities - I am building a GUI editor and it
currently converts from windows forms (visual studio c# forms) to
wxPython code.
When I started programming this editor I thought I'd have major
incompatibility problems, thinking wxPython is extremely weaker than
the windows forms.
However, coding the conversion between the two proved wxPython to be
highly capable.
BTW, this GUI editor can be found here:
http://farpy.holev.com

I believe this also provides an answer to gsteff's post about not
having a normal GUI editor.

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


Re: UI toolkits for Python

2005-10-14 Thread [EMAIL PROTECTED]
sure it is, but since this is a Python list, you'd also need PyQt to go
along with it, and there's no version of PyQt yet compatible with Qt4.

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


Re: Problems with properties

2005-10-14 Thread [EMAIL PROTECTED]
If you change it to this it works. You should provide a get and a set
function for a property.

class Task:
   def __init__(self, value):
 self._command = value

   def setCommand(self, value):
 self._command = value


   def getCommand(self):
 return self._command

   command=property(getCommand, setCommand)

class taskTest(TestCase):
 def testTask(self):
 t = Task("dir c:")
 c = t.command
 self.assertEquals("dir c:", c)

 # should fail, but doesn't
 t.command = "foo Bar"
 self.assertEquals("dir c:", t.command)


if __name__ == "__main__": 
 unittest.main()

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


Re: Problems with properties

2005-10-14 Thread [EMAIL PROTECTED]
If you change it to this it works. You should provide a get and a set
function for a property.

class Task:
   def __init__(self, value):
 self._command = value

   def setCommand(self, value):
 self._command = value


   def getCommand(self):
 return self._command

   command=property(getCommand, setCommand)

class taskTest(TestCase):
 def testTask(self):
 t = Task("dir c:")
 c = t.command
 self.assertEquals("dir c:", c)

 # should fail, but doesn't
 t.command = "foo Bar"
 self.assertEquals("dir c:", t.command)


if __name__ == "__main__": 
 unittest.main()

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


Re: Python's garbage collection was Re: Python reliability

2005-10-14 Thread [EMAIL PROTECTED]
Paul Rubin wrote:
> This correctly describes difficulties of using a copying GC in
> CPython.  Note that the Boehm GC is mark-and-sweep.  As Alex mentions,
> that usually means there's a pause every so often while the GC scans
> the entire heap, touching all data both live and dead (maybe the Boehm
> GC got around this somehow).

>From the docs:

void GC_enable_incremental(void)
Cause the garbage collector to perform a small amount of work every few
invocations of GC_MALLOC or the like, instead of performing an entire
collection at once. This is likely to increase total running time. It
will improve response on a platform that either has suitable support in
the garbage collector (Linux and most Unix versions, win32 if the
collector was suitably built) or if "stubborn" allocation is used (see
gc.h).

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


Good news and bad news!!

2005-10-14 Thread [EMAIL PROTECTED]
The Bad news is i am an IT Recruiter..The good news is that i have
a great role for a developer with strong Python skills.

Ideally along with that they will have Java and either an understanding
of Agile development or experience in using Ruby.

£35 - £45k, London

Contact me for more information
01189897601
[EMAIL PROTECTED]

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


Re: Microsoft Hatred FAQ

2005-10-14 Thread [EMAIL PROTECTED]
Hm... What does this have to do with Perl?

Why did you post this in comp.lang.perl.misc?

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


Accessing Parallel Port in Python Error : Priviledged Instruction

2005-10-14 Thread [EMAIL PROTECTED]
Hello

When I use Pyparallel to access the parallel port in WinXP with Python
I get an error saying that this is a priviledged instruction

Any clue ?

Mike

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


subtle side effect of generator/generator expression

2005-10-16 Thread [EMAIL PROTECTED]
Hi,

I initially thought that generator/generator expression is cool(sort of
like the lazy evaluation in Haskell) until I notice this side effect.

>>>a=(x for x in range(2))
>>>list(a)
[1,2]
>>>list(a)
[]

Would this make generator/generator expression's usage pretty limited ?
As when the program/system goes beyond a single module, this behaviour
can cause subtle bugs ?

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


Re: subtle side effect of generator/generator expression

2005-10-16 Thread [EMAIL PROTECTED]
That is exactly what I meant, in fact. These IO thing are expected to
have side effects so they are not subtle. Generator on the other hand,
is sort of "clever iteratables".

Now that I notice that, Of course I can be sure I would be careful. But
what about the following situation :

I import some function from some third party module which said, "oh, my
function returns a iteratable". Then I can only list(o) if I want to
pass it around or I consume it in only one and only one place. turning
it into a list completely negate what generator is intended
for(generate as much as you need) and using it in only one and only one
place(like your fread example) would IMO means its usage is pretty
limited.

Beside, I can do a fseek to rewind a file handle but not a generator
object.

Fredrik Lundh wrote:
>
> > As when the program/system goes beyond a single module, this behaviour
> > can cause subtle bugs ?
>
> sure, in the same way as
>
> >>> f = open(filename)
> >>> f.read()
> 'hello world\n'
> >>> f.read() # oops!
> ''
> 
> causes subtle bugs (that is, almost never)
> 
> 

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


Re: tuple versus list

2005-10-16 Thread [EMAIL PROTECTED]
In this particular case, it seems that (width,height) looks nicer. But
I think otherwise, list constuct is easier to read, even though it is
supposed to be slower.

With list you can :
[a] + [ x for x in something ]

With tuple it looks like this :
(a,) + tuple(x for x in something)

I think the list looks cleaner. And since you cannot concat tuple with
list, I think unless it looks obvious and natural(as in your case), use
list.

Xah Lee wrote:
> suppose i'm going to have a data structure like this:
>
> [
> [imgFullPath,(width, height)],
> [imgFullPath,(width, height)],
> [imgFullPath,(width, height)],
> [imgFullPath,(width, height)],
> ...
> ]
>
> should i use (width,height) or [width,height]?
> what advantage i get to use n-tuple instead of the generic list?
> 
> Thanks.
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/

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

Re: subtle side effect of generator/generator expression

2005-10-16 Thread [EMAIL PROTECTED]
True. That is why I have now reverted back to use list whenever
possible. As while list can also be modified(say in a multi-thread
situation), at least if I don't do the update(coding policy, practice
or whatever), they are sort of "guaranteed".

I would only use generator as IO monad in Haskell, i.e. don't use it
unless I absolutely need to.

Diez B. Roggisch wrote:
>
> Its a question of protocol. A iterator only guarantes that you can fetch
> items from it until it is possibly exhausted. In the same way, a stream
> may only guarantee you that you can  read from it. If you need more, you
> have tgo use a different protocol. Lists are one that allows you to
> randomly access it. Files allow to seek, in addition to stream semantics.
>
> And given that python is an imperative language with side-effects, you
> don't know what sideeffects  a generator can cause - which makes a
> "rewind" or copy-semantics to make it work several time impossible (in
> the general case, that is). So it has to focus on what it _can_ guarantee.
>
> Haskell and other FP languages canwork differently here, as sideeffects
> are made excplicit using e.g. monads or other means - which allows for
> re-use of a generator-like construct. But there is no way to make this
> work in pythons paradigm.
> 
> Diez

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


Re: subtle side effect of generator/generator expression

2005-10-16 Thread [EMAIL PROTECTED]
thanks. I was looking for scanl in itertools but can't find it so I
implement my own then run into some subtle bugs which first made me
think my scanl is the problem. Then notice my wrong perception about
generator(and iterable in general, though the built-in iterables like
list, dict don't seem to have this characteristic).

Simon Percivall wrote:
> If you find that you want to iterate over an iterable multiple times,
> have a look at the solution that the tee() function in the itertools
> module provides (http://docs.python.org/lib/itertools-functions.html).
> (Have a look at the rest of the itertools module as well, for that
> matter.)

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


Re: subtle side effect of generator/generator expression

2005-10-16 Thread [EMAIL PROTECTED]
> Are you saying that the bugs it causes aren't subtle? *wink*

Exactly. Destructive generator problems are caught almost immediately.

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


generic xmerge ?

2005-10-17 Thread [EMAIL PROTECTED]
Hi,

I was reading this recipe and am wondering if there is a generic
version of it floating around ? My list is a tuple (date, v1, v2, v3)
and I would like it to sort on date. The documentation doesn't mention
how the items are compared and the example only use integers.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/141934

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


Re: generic xmerge ?

2005-10-17 Thread [EMAIL PROTECTED]
oops, sorry. I meant

l1=[(date,v1,v2,v3), ...]
l2=[ another set of tuples ]


Thanks. so I have to concat the multiple lists first(all of them are
sorted already) ?

Alex Martelli wrote:
> I'm not sure what "my list is a tuple" mean (list and tuple being
> different types) nor what this has to do with the recipe.  Anyway...
> sequences are compared lexicographically -- first items first, then
> second items if the first items are equal, and so on.  So, if you have a
> list X whose items tuples and want X sorted on the tuples' first items,
> X.sort() will suffice -- if the tuples never have equal first-items, or
> if you're OK with second-items getting compared when the first-items are
> equal.  If you want to sort on first-items ONLY, leaving the tuples in
> the same order in the list when their first-items are equal:
> 
> import operator
> X.sort(key=operator.itemgetter(0))
> 
> 
> Alex

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


Re: generic xmerge ?

2005-10-17 Thread [EMAIL PROTECTED]
million thanks. So the default compare funcion of heapq also do it like
sort ?

The size of the list is not very large but has the potential of being
run many times(web apps). So I believe second one should be faster(from
the app perspective) as it goes into the optimized code quickly without
all the overheads in the merge case.

Alex Martelli wrote:
> You can do it either way -- simplest, and pretty fast, is to concatenate
> them all and sort the result (the sort method is very good at taking
> advantage of any sorting that may already be present in some parts of
> the list it's sorting), but you can also try a merging approach.  E.g.:
>
>
> import heapq
>
> def merge_by_heap(*lists):
>   sources = [[s.next(), i, s.next]
> for i, s in enumerate(map(iter,lists))]
>   heapq.heapify(sources)
>   while sources:
> best_source = sources[0]
> yield best_source[0]
> try: best_source[0] = best_source[-1]()
> except StopIteration: heapq.heappop(sources)
> else: heapq.heapreplace(sources, best_source)
>
> Now, L=list(merge_by_heap(l1, l2, l3)) should work, just as well as,
> say, L = sorted(l1+l2+l3).  I suspect the second approach may be faster,
> as well as simpler, but it's best to _measure_ (use the timeit.py module
> from the standard library) if this code is highly speed-critical for
> your overall application.
> 
> 
> Alex

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


Re: Vim IS a capable IDE [was Re: Vim capable IDE?]

2005-10-18 Thread [EMAIL PROTECTED]
Chris Lambacher wrote:
> > * Usage tips/tooltips: Also something I found in PythonWin. During the
> > writing of the method, a little tip box pops up advising me what the
> > inputs are for a method or an instance construction for a class. Very
> > nice, very productive.
> VIm 7 may support that out of the box since there were a lot of supporter
> votes for it:
> http://www.vim.org/sponsor/vote_results.php

It will, Omni Complete (akin to "Intellisense" and such) is already in
the Vim 7 tree.

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


Re: how best to split into singleton and sequence

2005-10-18 Thread [EMAIL PROTECTED]
what you wrote is the most readable to me:

just asign the first 2 element to t, l respectively and forget about
the rest. I assume that is what you want. I think perl may do it this
way.

A solution which I think looks uglier is :

t, l = s.split('|')[:2]

Randy Bush wrote:
> >>> 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: bug in os.system?

2005-10-18 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> OK, I give up.  Why does workaround #2 work?

Well, there was a time when the cmd prompt treated all
spaces as delimiters, so

>cd My Documents

would fail. Nowadays you can do that successfully and even

>cd My Documents\My Pictures

works.

In the old days, if a directory had a space, you had to
enclose it in quotes

>cd "My Documents"

But you didn't actually need to include the trailing quote,
so you could get away with

>cd "My Documents

I'm sure if you looked it up, Microsoft would say

This behaviour is by design.


>
> Also, I didn't realize this before, but when you call os.spawnv, the
> argument list you pass starts with the name of the executable you're
> calling!  When you call a program from cmd.exe, that program name is
> the first parameter automatically.  But with spawnv, you do that
> manually!
> 
> Anyway, thanks for your help!

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


Re: Upgrading 2.4.1 to 2.4.2

2005-10-18 Thread [EMAIL PROTECTED]
Not sure that is a good idea on a linux system. MS should be fine, but
I actually tried that on linux. Didn't realize how much on a linux
system depends on Python.

Basically ended up doing a full re-install.

I'll never do that again.

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


Re: write a loopin one line; process file paths

2005-10-18 Thread [EMAIL PROTECTED]
what do you mean by one line ? Using map/filter, I believe it is
possible.

Somthing like:

map(lambda (s,f): os.path.exists(f) and f or s,
map(lambda x: (x, re.replace(x, "-s","")), imgPaths)

My regex is a bit rusty but I hope you got the idea of what I am trying
to do. If there is a way to make the re return without destroying x,
the outer map is not needed I believe(that is run it twice, once for
getting the filename to do the testing, then again based on the testing
result).

Xah Lee wrote:
> is there a way to condense the following loop into one line?
>
> # -*- coding: utf-8 -*-
> # python
>
> import re, os.path
>
> imgPaths=[u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2059m-s.jpg',
> u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2062m-s.jpg',
> u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2097m-s.jpg',
> u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2099m-s.jpg',
> u'/Users/t/web/Icons_dir/icon_sum.gif']
>
> # change the image path to the full sized image, if it exists
> # that is, if image ends in -s.jpg, find one without the '-s'.
> temp=imgPaths[:]
> imgPaths=[]
> for myPath in temp:
> p=myPath
> (dirName, fileName) = os.path.split(myPath)
> (fileBaseName, fileExtension)=os.path.splitext(fileName)
> if(re.search(r'-s$',fileBaseName,re.U)):
> p2=os.path.join(dirName,fileBaseName[0:-2]) + fileExtension
> if os.path.exists(p2): p=p2
> imgPaths.append(p)
>
> temp=[]
> print imgPaths
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/

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

Re: write a loopin one line; process file paths

2005-10-18 Thread [EMAIL PROTECTED]
it will be added in 2.5 I beleve. At the moment, you can:

predicate and  or 

like :
>>> os.paths.exists(something) and "print it is there" or "file not found"

I am practicing FP in python and it is in general doable with the help
of itertools and add the needed functions as needed, like scanl/scanl1
etc.

A few things I don't like about python for FP is that it relies heavily
on exception which make these one liners not possible in many case.

Example:

a=[]
a[0] would raise exception

I usually prefer None as a special value which can be handled in normal
flow(filter out, may be "x is None and something or otherthing"). But
the liberal use of Exception force you to structure the program either
in a very odd way(test with hasattr/haskey etc. before use) or needs
lots of try/except blocks. I am using a python XHTML template Kid which
relies on one-liner and found it very difficult.

However, if you don't really need one-liner but just FP style to
shorten the program, it is fine but I just find the try/except block
quite ugly.

Then there is the side effect of iterators/generators which unless you
know can burn you badly(especially when you are chaining these objects
in these multiple map/filter calls), as mentioned in another post.

Xah Lee wrote:
> Thanks. Here's how the inner loop should be:
>
> imgPaths2=map(lambda x: (x, re.sub( r"^(.+?)-s(\.[^.]+)$",r"\1\2", x)),
> imgPaths)
>
> though, now i just need something like
>
> map( lambda x: os.path.exists(s)? x[1]:x[0],impPaths2)
>
> but Pyhton doesn't support the
> test ? trueResult : falseResult
> construct.
>
> (the semantic of this construct, of a conditional that RETURNS A
> EXPRESSION, all in one line, is important in functional programing.
> Perl supports it. In Mathematica, it's simply the form If[testExpr,
> trueExpr, falseExpr]. In lisp, similar: (if testExpr trueExpr
> falseExpr) )
>
> is there a way to similate it?
>
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/
>
> [EMAIL PROTECTED] wrote:
> > what do you mean by one line ? Using map/filter, I believe it is
> > possible.
> >
> > Somthing like:
> >
> > map(lambda (s,f): os.path.exists(f) and f or s,
> > map(lambda x: (x, re.replace(x, "-s","")), imgPaths)
> >
> > My regex is a bit rusty but I hope you got the idea of what I am trying
> > to do. If there is a way to make the re return without destroying x,
> > the outer map is not needed I believe(that is run it twice, once for
> > getting the filename to do the testing, then again based on the testing
> > result).
> >

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

Re: write a loopin one line; process file paths

2005-10-19 Thread [EMAIL PROTECTED]

Xah Lee wrote:
> besides syntactical issues, another thing with doing functional
> programing in imperative languages is that they become very inefficent.
> Functional languages are optimized by various means of functional
> programings styles. Doing them in imperative languages usually comes
> with a order of execution penalty because imperative language compilers
> are usually dumb.

The itertools module and the new generator feature tries to make this
better as it is lazily evaluated, in a sense. But its side effect is
nasty. Usable though need to twist my mind a bit, not like when I do it
in haskell. But the occasion imperative dip makes some of my programs
easier to code.

>
> though, one can't totally blame for Python's lack of ability to do
> functional programing. Its language's syntax of using indentations for
> blocks by design, pretty much is in odds with functional programing's
> sequencing of functions and other ways. (such as generic mechanism for
> prefix/postfix syntax, or macros or other transformations and patterns,
> or heavy reliance on the free flow of expressions/values)

That I am not sure. haskell also use this indentation but I don't see a
problem about it. One thing I find it odd though is the @decorator
construct. I just don't understand why it is viewed as simple. It
becomes very ugly IMO when there is a number of it, I am doing some web
apps which requres varies decorators(one over the other).

@format
@login_block
@validate
@something
def my_func():

I find it easier to read and under stand in the form of

format(login_block(validate(something(my_func) though haskell's $
and . is even better.

format.login_block.validate.somethin.my_func

>
> I don't blame Python that it doesn't cater to functional programing BY
> DESIGN. But i do hate the mother fucking fuckheads Pythoners for one
> thing that they don't know what functional programing really is, and on
> the other hand fucking trumpet their righteousness and lies thru their
> teeth of their ignorance. (that Guido guy with his Python 3000 article
> on his blog is one example, possibly forgivable in that particular
> instance. (http://xahlee.org/perl-python/python_3000.html))

That seems to be the case, I mean the design. For fairness, list
comphrehension sometimes looks cleaner, though becomes ugly when you do
the pipe/chain like programming in FP(multiple for). This again is an
odd choice. It seems to be a flattening of multiple line for loop, yet
at the same time python seems to be moving towards being more
explicit(no map/filter/etc as they can be done in for loop).

But I believe Python is designed for easy to code and read and maintain
in mind. One has to admit that without some training, FP is not very
intuitive, my head spin when I see haskell code. A for loop is easier
to understand.

Well, if you want clean FP, you can always try haskell which is getting
better and better in terms of real world module support(file system,
network etc).
>
> (excuse me for lashing out)
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/

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

Re: write a loopin one line; process file paths

2005-10-19 Thread [EMAIL PROTECTED]

Xah Lee wrote:
> This i'm not sure. Of the past couple of years i increasingly developed
> a theory (probably well-known among proper experts), that the
> difficulty of human feats of various forms, are primarily a perception
> and familiarity thing. This may be getting off topic, but i wrote an
> essay expresising much of the idea using Juggling as a example:
> Difficulty Perceptions in Human Feats
>  http://xahlee.org/Periodic_dosage_dir/t2/juggling.html
>
> likewise, i think this applies to mental feats as well. In particular,
> i think that whether imperative code or functional code is easier for
> the mind is almost ENTIRELY dependent on which one the person is more
> familiar with, coulped with a innate attitude one may have picked up.

But most of us start learning programming with imperative language, I
started with COBOL and Pascal(are they still taught). Then we would hit
the problem of looping one way or another pretty soon. Without a doubt,
some experienced programmer would tell you to use for loop or search
for one. This is even true in two heavily used declarative tools, SQL
and Excel. If there is foldl/scanl/map in SQL, I think it would be much
easier to code. Likewise for Excel, it is very functional(like its
ancestors 1-2-3) then VBA was thrown in.

In fact, I think haskell should be taught in any CS course as it opens
up a completely different way of approaching problem and it is easier
to read than LISP.

> oh Haskell, my love! I am really going to learn it now. (maybe i'll
> start A-Java-Haskell-A-Day) This month i just learned and read about
> how Perl 6 is implemented in Haskell! (because one Taiwaness hacker
> single-handedly by happenstance tried to do it, as a by-product of
> learning Haskell) This Pugs (Perl6 in Haskell) really brought two
> rather incompatible communities together somewhat for mutual exchange.
> (the learning, on the surface, is politely said to be mutual, but i'm
> pretty sure it's mostly Perlers learning from the Haskell folks)
After seeing Haskell, I don't think I would go back to Perl(which I
like better than python but python has the momentum as a general
purpose language). That is why I am doing the think in haskell, code in
python, whenever possible.

>
> ... there is a sentiment among the elite tech-geeking morons, early on
> imbued by the concept of troll, so that they in general don't
> communicate and learn from any other language except their own.
> Anything cross-posted is considered as troll, and the inter-language
> communication has been essentially completely cut off. Basically, the
> only ones generating all the garbage posts are these troll-criers
> themselves. (will have to flesh out on this particular point of
> net-sociology in a essay some other day.)
>
May be you can tone down a bit if you want a constructive discussion. I
am too old to have feelings about opinionated posts(and insensitive to)
so I can go through the technical stuff. Confucius said "I can always
learn something whenever there is 3 people getting together", lousy
translation :-)

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


Re: Controlling exception handling of logging module

2005-10-19 Thread [EMAIL PROTECTED]
make the second statement 'logging.info("%d %d", 1, 2)' or
'logging.info("%d %d %d", 1, 2, 3)', and all works. for every argument
you want to log you need one format specifier

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


Re: Python variables are bound to types when used?

2005-10-19 Thread [EMAIL PROTECTED]
Fredrik Lundh wrote:
> reset your brain:
>
> http://effbot.org/zone/python-objects.htm

Neat link.

Can you expand on this:

> a type (returned by type(x))
...
> You cannot change the type.

Especially what's going on here:

>>> class a(object):
... pass
...
>>> class b(a):
... pass
...
>>> x=b()
>>> x.attr=1
>>> type(x)

>>> type(y)

>>> x.__class__=a
>>> type(x)

>>> x.attr
1

It looks to me like x is still referencing the same object (and still
has the "attr" attribute) but its type has changed.  Is that not right?

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


sqlstring -- a library to build a SELECT statement

2005-10-19 Thread [EMAIL PROTECTED]
After some thought on what I need in a Python ORM (multiple primary
keys, complex joins, case statements etc.), and after having built
these libraries for other un-named languages, I decided to start at the
bottom. What seems to plague many ORM systems is the syntactic
confusion and string-manipulation required to build the SQL Statements.
If you want to do a Left Outer Join, support nested functions, and a
nested conditional clause, you'd be building more of a string library
than an ORM. Let's not even mention syntactical differences between
databases, data types, and such.

My solution is sqlstring. A single-purpose library: to create SQL
statement objects. These objects (such as sqlstring.Select), represent
complex SQL Statements, but as Python objects. The benefit is that you
can, at run-time, "build" the statement pythonically, without
getting bogged down in String Manipulation. The theory is that once in
use, things that were complex (string magic) become simpler, and allow
the program to worry about higher-level issues.

An Example:

>>> import sqlstring
>>> model = sqlstring.TableFactory()
>>> print model.person
SELECT
person.*
FROM
[person] person
>>> person_smith = model.person \
** (model.person.first_name == "Smith")
>>> print person_smith
SELECT
person.*
FROM
[person] person
WHERE person.first_name = 'Smith'
>>> print person_smith("party_id", "first_name") \
< < model.address ** (\
model.address.party_id == model.person.party_id)
SELECT
party_id party_id,
first_name first_name,
address.*
FROM
[person] person
LEFT OUTER JOIN [address] address ON
address.party_id = person.party_id
WHERE person.first_name = 'Smith'

Things can get much more interesting than this, including nested
sub-selects (anywhere), conditional groups (and/or groups nested using
& and |) and even CASE statements.

Some of this stuff has been around for a while (using "magic" objects
to build where clauses, etc.).  But I'm trying to take it all the
way--to a legit Select statement.

While still in the early stages, it does work with a great many sql
statements, as seen in the test suite.  Currently supported are CASE
statements, Nested conditional clauses, nested queries and most join
types. At this point, I'm interested in getting feedback from the
community on several fronts:

   1. The Operator Overload model. I've chosen to overload Python's
operators to give a short-hand syntax to most of the things you'd
want to do with a select statement. The rest are accessable via
methods. Currently ** is the "where" operator, // is the "in"
operator, % the "like" operator and ^ aliases columns. Other
overloads are as you'd expect- + / - * == all result in Expression
Objects that dish out the right SQL string. The question is, is the
"leap" in syntax to confusing? Is there a cleaner way to do this?
(Functions for example)
   2. How to best add further sql function support? Adding magic
callable objects to columns came to mind, but this has it's own set
of issues. I'm leaning towards a magic object in the sqlstring
module. For example:

  sqlstring.F.substring(0, 4, person.first_name)

  would result in: substring(0, 4, person.first_name). the F object
could be put in the local scope for short-hand.
   3. I'm undecided on how best to handle database specific
overwrites. I want this to be as easy as possible. I'm thinking about
subclassing Expressions with a naming scheme on the Sub-Class (such as
CaseExpression_oracle). Then the __init__ factory could dish out the
right version of the object based on the the requestor. This brings up
lots of questions, such as how to support multiple types of databases
at the same time.

  Eventually the library should include all of the basic SQL
Statements, including UPDATE, INSERT and CREATE statements. This is
mostly for completeness, though. SELECT statements tend to be the most
complex.

  The library can be downloaded at http://betur.net/download.php

  Any other thoughts or comments are very much appreciated

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


How can I call a subclass method from parent class ?

2005-10-19 Thread [EMAIL PROTECTED]
Hi,

Suppose my class definition is like this :

class A:
name = "A"

@classmethod
def foo(cls):
cls.__super.foo()
cls.bar()

@classmethod
def bar(cls):
print cls.name

class B(A):
name = "B"

class C(B):
name = "C"

What I want is

C.foo() prints 'ABC'
B.foo() prints 'BC'
A.foo() prints 'A'

But when I call C.foo(), it said

AttributeError: class C has no attribute '_A__super'

How should this be coded ?

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


Re: sqlstring -- a library to build a SELECT statement

2005-10-19 Thread [EMAIL PROTECTED]

Jason Stitt wrote:
>
> I think some operator overloading, especially the obvious cases like
> ==, is cleaner than using only functions because it lets you order
> things normally. But some of the operator choices are non-intuitive.
> Personally, I would make something like 'alias' a function or class,
> rather than overloading XOR. Not sure about ** for where.
My strategy is to do both.  Have a "where" method that could be called
instead of ** (ie.  person.where(person.last_name=="smith"), but also
allow for the ** syntax.  After using it for a while, I'm finding the
** and ^ for alias very clear.  Alias function brings up the issue of
name-space (since table.alias could be a column if not a special
method.)  I'm assuming people don't use where, select, or other SQL key
words as column names, and if they do, they have a table["column"]
syntax to fall back on.  But I digress.  A method makes sense, though.

>
> Using // for 'in' looks really weird, too. It's too bad you can't
> overload Python's 'in' operator. (Can you? It seems to be hard-coded
> to iterate through an iterable and look for the value, rather than
> calling a private method like some other builtins do.)

// was a bit of a stretch.  I'd initially thought it for the "where"
clause, becuase it's lower precedence than ** (I think), and really
late at night // kind of looks like a W.  I decided against it because
it looks to close to a comment in some other languages.

Python "in" clause doesn't seem exploitable in any way--probably a good
thing.  I did add a "in_" method (name is arguable), which does the
same thing, also a not_in.

> Have you ever used Pyparsing? Its use of a combination of classes and
> operator overloading works pretty well.
I took a look at it.  Seems like a happy balance there--with the
overloading. http://www.aminus.org/blogs/index.php/fumanchu/2005/08/11/where_dejavu_fits_in_the_orm_cosmos";>Dejavu
is another cool solution--using Lambda expressions.  But it goes into
scary bytecode stuff (though it's well contained).

>
> For SQL function calls, don't you also want to support stored
> procedures? In that case, you don't want pre-set magic functions so
> much as a function that takes a string parameter for a function name
> and then a list of function parameters.
This is what I had in mind (echo.py in the distribution).  The only
issue becomes knowing when to quote the parameters (is a string always
a string?).  I 've ended up quoting everything, and forcing the user to
supply table.column notation if they don't want it quoted.

>
>  print person_smith("party_id", "first_name") \
> 
> > < < model.address ** (\
> > model.address.party_id == model.person.party_id)
> > SELECT
> > party_id party_id,
> > first_name first_name,
> > address.*
> > FROM
> > [person] person
> > LEFT OUTER JOIN [address] address ON
> > address.party_id = person.party_id
> > WHERE person.first_name = 'Smith'
>
> See, this is where I'm not sure about operator precedence. If <<
> binds tighter than **, it works, because the << operator would make a
> 'join' object and then the ** could be interpreted as an 'on' clause.
> But if ** binds tighter you get an extra 'where' clause on the
> address table, and then a join...
>
There's a little dark magic going on with the precedence here.  The **
is higher precedence, so it happens first, and is applied to the
address table object, which is then joined into person (with the <<
operator), and pulling in the existing where on address.  This sounds
bad, but it allows for where clauses to trickle up through the python
expression, which is how I get a + b >> c to behave as expected.


Thanks for the positive feedback!

Runar

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


Re: How can I call a subclass method from parent class ?

2005-10-20 Thread [EMAIL PROTECTED]
thanks, it works. Though I don't quite understand what super(cls,cls)
returns, and it doesn't work if I do a super(cls,cls).foo(). But
cls.__base__.foo() do the trick.

thankfully, I don't have multiple inheritance.

Jason  Lai wrote:
> If you use a newstyle class, e.g. class A(object), then you can get the
> superclass with cls.__base__. You could also use super(cls,cls),
> although note that it returns a  object that isn't exactly the
> same thing as a class -- but good enough for just accessing attributes.
>
> Make sure to check that your superclass isn't , otherwise it'll
> complain about  not having a foo attribute. __base__ is
> probably easier for this purpose. Also be careful with multiple
> inheritance.
> 
> No such thing as __super though.

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


Re: How can I call a subclass method from parent class ?

2005-10-20 Thread [EMAIL PROTECTED]
Thanks for the explanation but some how my code fail and since I don't
need multiple inheritance for the moment, I would settle for the not so
clean version.

The documentation of super is not very clear to me too. As seen in my
code, I am using classmethod which may cause some problem.

Steve Holden wrote:

> In point of fact super() is most useful when you *do* have multiple
> inheritance. The classic example is when classes B and C have a common
> supertype A, and then class D is a subclass of both B and C.
>
> Under these circumstances (the so-called "diamond-shaped inheritance
> graph") it can be problematic to ensure that each superclass's methods
> are called exactly once when methods are being extended rather than
> overridden: should a D call B's method, which then calls A's, and if so
> how does a D ensure that C's method gets called without it also calling
> A's method.
>
> Calls to super() are used to effectively place a linearised oredering on
> the superclasses to ansure that the diamond-shaped inheritance pattern
> is correctly handled to give the correct method resolution order.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC www.holdenweb.com
> PyCon TX 2006  www.python.org/pycon/

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


best way to replace first word in string?

2005-10-20 Thread [EMAIL PROTECTED]
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one

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


Re: __getattr__, __setattr__

2005-10-20 Thread [EMAIL PROTECTED]
for new style classes  __getattribute__ is defined, see eg.
http://www.python.org/2.2.3/descrintro.html

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


Re: sqlstring -- a library to build a SELECT statement

2005-10-20 Thread [EMAIL PROTECTED]
> The big operator question will be: how will "and" and "or" be
> implemented? This is always a sticking point because of Python's
> short-circuiting behaviors regarding them (the resultant bytecode will
> include a JUMP).

I'm using the Boolean | and & operators for logical groups, eg (a | b |
(b & c)).  This might seem ugly to pureists, but solves all of the
short-circuit issues.  It does require the user to use excessive
parentheses, becuase | evaluates before ==.  Another option is to use
functions-- AND(EQ(a, 1), OR(IN(B,(1,2,3 -- But I find this hard to
read.  But mixing the two is sometimes clean:  EQ(a,1) & LT(b,2).  But
having too many ways of doing things doesn't seem very pythonic.

>
> An alternative is to stuff the representation into a string, which can
> then be parsed however one likes.
>
> For Dejavu (http://projects.amor.org/dejavu), I didn't do either
> one--instead I used lambdas to express the where clause, so that:
>
> f = logic.Expression(lambda x: ('Rick' in x.Name) or
>  (x.Birthdate == datetime.date(1970, 1, 1)))
> units = sandbox.recall(Person, f)
>
> might produce, in the bowels of the ORM:
>
> "SELECT * FROM [Person] WHERE [Person].[Name] Like '%Rick%' or
> [Person].[Birthdate] = #1/1/1970#"
>
> Note that the tablename is provided in a separate step. The translation
> is based on the codewalk.py and logic.py modules, which are in the
> public domain if you want to use any part of them. See
> http://projects.amor.org/dejavu/svn/trunk/

This is a very elegant solution, so much so that I almost didn't go
down the path of sqlstring.  Having support for lambda expressions is
still an option, though I wanted to try object operator
overloading/methods first--too see if I could avoid the Bytecode issue.

>
> >2. How to best add further sql function support? Adding magic
> > callable objects to columns came to mind, but this has it's own set
> > of issues. I'm leaning towards a magic object in the sqlstring
> > module. For example:
> >
> >   sqlstring.F.substring(0, 4, person.first_name)
> >
> >   would result in: substring(0, 4, person.first_name). the F object
> > could be put in the local scope for short-hand.
>
> This is a hard problem, since your sqlstring module doesn't control the
> result sets, and so can't provide fallback mechanisms if a given
> database does not support a given function (or operator, or minute
> detail of how a function or operator works; for example, LIKE is
> case-insensitive in MS SQL Server but case-sensitive in PostgreSQL). If
> you're going to use subclasses to handle "database-specific overwrites"
> (below), then you'll probably want to stick such functions in that base
> class (and override them in subclasses), as well.
Good point.  These things should be able to be "intercepted" in the
database specific modules, so the library has a documented way
functions should be used (ANSI if applicable), but database specific
overwrites allow us to deal with issues or hacks (to emulate a
function) in databases.


> See the Adapter and SQLDecompiler classes in
> http://projects.amor.org/dejavu/svn/trunk/storage/db.py (and the
> store*.py modules) for some examples of using subclassing to produce
> database-specific syntax. There, it's one Adapter class per supported
> DB-type; you might consider keeping the Expression objects themselves
> free from SQL, and transform the Expressions to SQL in a separate
> class, which you could then subclass.
Thanks.  Your approach here had already inspired me, I'll take a look
at it again.  Pulling the SQL out of the Expression objects is double
sided, but might be a way to cleanly support db syntax nuances.  I'll
keep you posted.

Runar

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


Re: sqlstring -- a library to build a SELECT statement

2005-10-20 Thread [EMAIL PROTECTED]
> >> Using // for 'in' looks really weird, too. It's too bad you can't
> >> overload Python's 'in' operator. (Can you? It seems to be hard-coded
> >> to iterate through an iterable and look for the value, rather than
> >> calling a private method like some other builtins do.)
> >>
> >
> > // was a bit of a stretch.  I'd initially thought it for the "where"
> > clause, becuase it's lower precedence than ** (I think), and really
> > late at night // kind of looks like a W.  I decided against it because
> > it looks to close to a comment in some other languages.
> >
> > Python "in" clause doesn't seem exploitable in any way--probably a
> > good
> > thing.  I did add a "in_" method (name is arguable), which does the
> > same thing, also a not_in.
>
> What about modifying the overloaded == to produce 'in' if the right-
> hand side is a list? Then you can more easily generate statements
> dynamically:
>
> def makeCond(name):
>  return someOtherCond & (model.table.name == name)
>
> makeCond("foo")
> makeCond(["foo", "bar"])
>
> And it doesn't require two different functions.
>
> As long as there is no case where you might actually want to test if
> a column value equals a list, it should work. Is there? Some DBs
> support an Array type, but in general that might be better handled
> with an Array class, anyway.

This is a great idea, and should be the default behaviour for lists.
It does present a problem if the right hand expression is a SELECT
object, though.  Both of these are valid syntax:

id = (select max(id) from table)
id in (select id from table)

Also, SQLite allows for  column in table_name syntax.  I've never seen
that before, but I wanted to support that, there'd be no way of knowing
in vs. ==.

On this line of thought, what about the += operator?  That might be
more intuative than //.  I could even use -= for not in.

Runar

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


Ruby on Rails Agile role

2005-10-20 Thread [EMAIL PROTECTED]
I am looking for 2 Software Engineers with a Java / Python / Ruby
background to work for a rapidly growing start-up using Ruby on Rails
in an Agile environment.


The role is paying between £40 - £45k and is based in central London.



Please send your details to grant @ connectionsrecruit.co.uk or call
01189897601

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


newbie question about SocketServer

2005-10-20 Thread [EMAIL PROTECTED]
Is it just me or do the server_close() methods do squat?  I'm primarily
working with a ThreadingTCPServer object and trying to create a simple
server that can shut itself down.  But even simplest cases don't seem
to work.

Admittedly I am trying it from within my handler class, but for some
odd reason, the server is allways willing to handle one more request
before dying.  Then it dies.

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


Re: sqlstring -- a library to build a SELECT statement

2005-10-20 Thread [EMAIL PROTECTED]

Tom Anderson wrote:
> On Thu, 20 Oct 2005, [EMAIL PROTECTED] wrote:
>
> > On this line of thought, what about the += operator?  That might be more
> > intuative than //.  I could even use -= for not in.
>
> You're going to have to explain to me how using an assignment operator for
> something other than assignment is intuitive!
>
> -1 on this one from me, i'm afraid.
Point.  I do think it looks strange, because we're used to seeing += in
code.  But the concept is more along the lines of the  == and !=
comparison operators.
Python does expose other nice things, such as &= and %=, which (since
people aren't used to seeing them used much), might be better
candidates.  Does %= seem more agreeable?  (I'm already using % for a
like statement).

So, a statement could look like this:

person ** (
  (person.type_id == 'customer')
  & (person.id %= phone(phone.person_id)))
)

becomes:

select * from person
where person.type_id = 'customer'
and person.id in (select person_id from phone)


> Using 'in' would be good. It does require some truly puke-inducing
> contortions, though; since 'in' calls __contains__ on the right-hand
> operand, and that's likely to be a list, or some other type that's not
> under your control, you have to cross your fingers and hope that whatever
> it is implements __contains__ with equality tests with the probe object on
> the left-hand side and the candidates on the right (as lists do, at least
> in 2.4.1). then, you just have to make your table names do the right thing
> when compared to strings.
>
__contains__, while allowing side-effects on the object in question
(even if though it's on the right), only returns true/false (not a
custom object) afaik, so it breaks in a complex expression  --  (a ==
b) & (c in d), won't work.  You could modify D, but you can't pass that
value to the whole Condition Expression.

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


Re: sqlstring -- a library to build a SELECT statement

2005-10-20 Thread [EMAIL PROTECTED]

> person ** (
>   (person.type_id == 'customer')
>   & (person.id %= phone(phone.person_id)))
> )
>
Nevermind.  This doesn't work because all of the X= operators in
question are assignment operators, and therefore generate a Syntax
Error if in a nested expression. I think I've settled on just doing a
table.column.IN(blah) syntax.  This should be obvious to anyone reading
the code, and doesn't require mangling of the name (since it's
capitalized).  Then we'd have similar functions for other non intuitive
things, such as LIKE, EXISTS (on the table) and even a WHERE:

person.WHERE(
   (person.type_id == 'customer')
   & (person.id.IN(phone(phone.person_id)))
)

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


Re: Python vs Ruby

2005-10-20 Thread [EMAIL PROTECTED]
I don't think you really need to give to much time in weighting between
python or Ruby. Both are fine. But Python has the obvious advantage
that it has much more modules than Ruby so many things you don't need
to implement if you have real work to do.

I recommend you give haskell a shot if you are "in" to programming
because it makes you think differently, not necessary better(at least
not all the time) but helps.

I am not sure your intention but I think there isn't a one language
fits all situation here. I frequently use the following:

C/C++ - for linux kernel hacking etc., many library out there still use
it
python - generic stuff
SQL - nothing beats it for many business apps
haskell - a language to train my brain
javascript - Web front end

other than haskell and SQL, the others are more or less the same to me
so getting familiar with them is not too difficult.

Amol Vaidya wrote:
> I've done a lot of studying on my own, and taken the classes that my
> high-school offers. I feel that I have a fairly good understanding of Java,
> and basic OO concepts due to that. I've created some semi-complex programs
> in java, in my opinion, such as networked checkers, 8-player blackjack, a
> space-shooter type game, a copy of mario (one level, anyway), and some other
> stuff. I've also done a bit of studying on C. I've done a few projects in C,
> including another space-shooter type of game using SDL, an IRC client and
> some simple database-type programs. I also gave a shot at assembly using
> NASM for x86 before, but didn't get too far. I wrote some trivial code --
> wrote to the video buffer, played with some bios interrupts, stuff like
> that. The only thing I did in assembly was create a program that loads at
> boot-up, and loads another program that just reiterates whatever you type
> in. I only did that because I was curious. That's about as far as my
> programming knowledge/experience goes.
>
> Well, I'm not sure what you mean by programming concepts. I'm familiar with
> OO through Java, and procedural programming through C. I'd be more detailed,
> but I'm not exactly sure what you are asking. Sorry.
>
> I have no idea what Scheme is, but I'll cettainly look it up as soon as I'm
> done writing this.
>
> I've never given Perl a shot. It was another language I considered learning,
> but my father's friend told me to go with Python or Ruby.
> 
> Thanks for your help. Hopefully I wasn't too lengthy in this post.

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


Re: fun with lambdas

2005-10-20 Thread [EMAIL PROTECTED]


You are asking it to return a list of lambda, not its evaluated value.

map(lambda x: f(x,0), [0,1,2]) works.

[ f(o) for o in [0,1,2] ] works too.

Juan Pablo Romero wrote:
> Hello!
>
> given the definition
>
> def f(a,b): return a+b
>
> With this code:
>
> fs = [ lambda x: f(x,o) for o in [0,1,2]]
>
> or this
>
> fs = []
> for o in [0,1,2]:
> fs.append( lambda x: f(x,o) )
>
> I'd expect that fs contains partial evaluated functions, i.e.
>
> fs[0](0) == 0
> fs[1](0) == 1
> fs[2](0) == 2
>
> But this is not the case :(
>
> What is happening here?
>
>
> Nevertheless, this code does work
>
> fs = [ eval("lambda x: f(x,%d)" % o) for o in [0,1,2,3]]
> 
> Thanks.
> 
>Juan Pablo

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


pushing python to multiple windows machines

2005-10-21 Thread [EMAIL PROTECTED]
I am working on a project that requires python to be installed on a
large number of windows servers and was wondering if anyone has found a
method to do this.  I found the article from 2003, but nobody ever
stated that they have found an option for this.

http://groups.google.com/group/comp.lang.python/browse_frm/thread/f42f0813bc271995?tvc=1&q=%22Pushing+Python+to+Windows+workstations%22

-shawn

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


Re: pushing python to multiple windows machines

2005-10-21 Thread [EMAIL PROTECTED]
hey tim -

Thanks for you input.  I'm looking at it from the Windows perspective
of needing to push a python interpreter out to multiple machines.  I'll
check out Moveable Python as you suggested.

thanks
-shawn

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


Re: Psycopg2 date problems: "Can't adapt"

2005-10-21 Thread [EMAIL PROTECTED]
Is "None" a valid value for SQL ? Or should it be NULL ? May be it is
because your input is NULL which is being converted to None in python
but haven't been converted back to NULL on its way out.

Steve Holden wrote:
> I'm trying to copy data from an Access database to PostgreSQL, as the
> latter now appears to work well in the Windows environment. However I'm
> having trouble with date columns.
>
> The PostgreSQL table receiving the data has the following definition:
>
> CREATE TABLE Lines (
>LinID SERIAL PRIMARY KEY,
>LinDate   TIMESTAMP(0),
>LinQtyINTEGER,
>LinPrdID  INTEGER ,
>LinPrice  NUMERIC(8,2),
>LinInvoice INTEGER)
>
> Here's the problem in a nutshell:
>
>  >>> d
> 
>  >>> ocurs.execute("DELETE FROMI Lines")
>  >>> osql
> 'INSERT INTO Lines(LinID, LinDate, LinQty, LinPrdID, LinPrice,
> LinInvoice) VALUES(%s, %s, %s, %s, %s, %s)'
>  >>> ocurs.execute(osql, (1, d, 1, 1, 12500.0, 88))
> Traceback (most recent call last):
>File "", line 1, in 
> psycopg.ProgrammingError: can't adapt
>  >>> ocurs.execute(osql, (1, None, 1, 1, 12500.0, 88))
>  >>>
>
> Since the date value's the only difference between the two, I deduce
> it's causing the problem.
>
> I'd rather not have to manipulate the data (in other words, I'd rather
> just change the definition of the receiving table to avoid the error if
> possible), as the copying operation attempts to be table-independent. It
> currently reads:
>
> for tbl, cols in d.items():
>  print "Copying", tbl
>  dsql = "DELETE FROM %s" % tbl
>  ocurs.execute(dsql)
>  isql = "SELECT %s FROM %s" % (", ".join(cols), tbl)
>  osql = "INSERT INTO %s(%s) VALUES(%s)" % (
>  tbl, ", ".join(cols), ", ".join("%s" for c in cols))
>  print isql, '\n', osql
>  icurs.execute(isql)
>  for row in icurs.fetchall():
>  ocurs.execute(osql, row)
>
> Though until I started stepping through the data row by row the last two
> lines were replaced by
>
>  ocurs.executemany(osql, icurs.fetchall())
>
> Who can help me past this little sticking point?
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC www.holdenweb.com
> PyCon TX 2006  www.python.org/pycon/

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


Re: pushing python to multiple windows machines

2005-10-21 Thread [EMAIL PROTECTED]
Thanks Roger & Larry.  Both of your suggestions are very helpful!

-shawn

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


Re: Binding a variable?

2005-10-21 Thread [EMAIL PROTECTED]
I think not. temp is a name, not a variable. I believe temp=5 means it
points to an immutable object 5. temp=6 means now it points to another
immutable object 6. list=[temp] would resolve to whatever object temp
is pointed to at that moment.

You can try temp=[1].

Paul Dale wrote:
> Hi everyone,
>
> Is it possible to bind a list member or variable to a variable such that
>
> temp = 5
>
> list = [ temp ]
>
> temp == 6
>
> list
> 
> would show
> 
> list = [ 6 ]
> 
> Thanks in advance?
> 
> Paul

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


Re: Execute C code through Python

2005-10-21 Thread [EMAIL PROTECTED]
Grant Edwards wrote:
> On 2005-10-21, Ernesto <[EMAIL PROTECTED]> wrote:
>
> > Thanks.  Can anyone provide an example of using *subprocess* to run
> > helloWorld.C through the python interpreter.
>
> No.  You can't run a .C file

Unless you have a C interpreter installed. e.g.:

  import os
  os.system("eic helloWorld.C")

(Requires eic to be in your PATH.)

I doubt it's what the OP was looking for, though.

http://eic.sourceforge.net/

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


Re: Help with language, dev tool selection

2005-10-21 Thread [EMAIL PROTECTED]
Hi Vasilije,

Try the Python 411 Podcast for a good introduction.

http://www.awaretek.com/plf.html

Cheers,
Davy Mitchell

http://www.latedecember.com

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


Re: Python variables are bound to types when used?

2005-10-21 Thread [EMAIL PROTECTED]

Diez B. Roggisch wrote:
> [EMAIL PROTECTED] wrote:
> > Fredrik Lundh wrote:
> >
> >>reset your brain:
> >>
> >>http://effbot.org/zone/python-objects.htm
> >
> >
> > Neat link.
> >
> > Can you expand on this:
> >
> >
> >>a type (returned by type(x))
> >
> > ...
> >
> >>You cannot change the type.
...
> So what? That the flexibility of python allows for such a hack has
> nothing to do with x being totally unaware of the type of the object it
> points to.

I'm still not understanding, maybe my question was unclear (and was
related to the writeup that was linked, I wasn't saying anything about
the relationships of names and objects).

I'm wondering what is meant by "you cannot change the type", and
whether I'm misunderstanding what is going on in my example when I say
"x.__class__=a".  It looks to me like the type of the object that "x"
is referencing changes, but the URL implies that something else might
actually be happening.  I'm not understanding the distinction.

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


  1   2   3   4   5   6   7   8   9   10   >