Setting timeout for read api

2006-03-04 Thread Swaroop
PLS HELP..I am working on socket programming as part of my final year
project. I want to know how to set a timeout on read api that reads
from a socket. Is it possible using SIGALRM signal?Will setting
O_NONBLOCK flag of the socket help? Is there any other way to do it?

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


Re: add an asynchronous exception class

2006-03-04 Thread Paul Rubin
"Fredrik Lundh" <[EMAIL PROTECTED]> writes:
> PEP 348 addresses this by moving special exceptions out of the
> Exception hierarchy:
> 
> http://www.python.org/peps/pep-0348.html

I see that suggestion was rejected (it needed changing the semantics
of "except:").  Also, PEP 348 was rejected and is a huge, complex
reorganization of the whole exception system.  This is cited:

  http://mail.python.org/pipermail/python-dev/2005-August/055423.html

but it talks about distinguishing terminating from non-terminating
exceptions, whatever that means.  (Won't any uncaught exception like
ValueError terminate the program)?

I realize now that exceptions arising from signals are also asynchronous
(http://docs.python.org/lib/module-signal.html).  So that's another
place where we'd see user-defined asynchronous exceptions: signal
handlers should raise them instead of raising ordinary exceptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setting timeout for read api

2006-03-04 Thread Paul Rubin
"Swaroop" <[EMAIL PROTECTED]> writes:
> PLS HELP..I am working on socket programming as part of my final year
> project. I want to know how to set a timeout on read api that reads
> from a socket. Is it possible using SIGALRM signal?Will setting
> O_NONBLOCK flag of the socket help? Is there any other way to do it?

You could do it with sigalrm but more common is to set a timeout on
the socket (see the settimeout method in the doc).  You could also use
select with a timeout, and not read until the select tells you that
data is available.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-04 Thread Paul Rubin
"Paul Boddie" <[EMAIL PROTECTED]> writes:
> > Sandboxed code is a real obvious one.
> 
> I don't disagree that this is true in general, but is that actually
> covered in the design patterns book [1] or in other related literature?

It's been a while since I looked at the design patterns book and I
don't know whether it discusses sandboxing.  I'd guess probably not.
As for whether any of the GoF book patterns are easy in Java but
difficult in Python, it's a good question and I don't know the answer.
Maybe the book has some patterns involving interfaces.  I'm a rather
low-tech Java user and I'm not a fan of the language, so I'm not a
good person to ask.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket freezes

2006-03-04 Thread Steve Holden
Dennis Lee Bieber wrote:
> On Fri, 03 Mar 2006 20:12:22 +, "Luis P. Mendes"
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
> 
> 
>>I'm beggining to suspect that the problem has to do with a discontinual
>>of service of the ISP.  It provides me a dynamic IP address not a static
>>one.
>>
> 
>   And many ISPs force a "lease renewal" after some period of time
> (hours or days).
>  
The DHCP protocol is supposed to allow lease renewal throughout the 
lease period, and clients are normally expected to renew their lease 
halfway through the lease period. So a continuously-connected system 
should retain the same IP address.

If ISPs are *forcing* lease renewal they are perverting DHCP. Network 
service should be continuous as long as a system remains continuously 
connected.
 > [...]

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: add an asynchronous exception class

2006-03-04 Thread Steven D'Aprano
On Sat, 04 Mar 2006 08:41:48 +0100, Fredrik Lundh wrote:

> Paul Rubin wrote:
> 
>> I'd like to suggest adding a builtin abstract class to Python called
>> AsynchronousException, which would be a subclass of Exception.  The
>> only asynchronous exception I can think of right now is
>> KeyboardInterrupt, so KeyboardInterrupt would become a subclass of
>> AsynchronousException instead of being a direct subclass of Exception.
> 
> PEP 348 addresses this by moving special exceptions out of the
> Exception hierarchy:
> 
> http://www.python.org/peps/pep-0348.html

The PEP has been summarily rejected, perhaps because it was too broad in
the changes it suggested. 



-- 
Steven.

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


Re: stripping spaces in front of line

2006-03-04 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> hi
> wish to ask a qns on strip
> i wish to strip all spaces in front of a line (in text file)
> 
> f = open("textfile","rU")
> while (1):
> line = f.readline().strip()
> if line == '':
> break
> print line
> f.close()
> 
> in "textfile", i added some spaces in and then ran the code, it prints
> out the lines without the spaces in front. I double checked "textfile"
> and it does contains some lines with spaces in front.
> Is it true that "readline().strip()" perform the removing of spaces in
> front of a line as well? Is it documented anywhere?
> I am using Windows environment. thanks
> 
If you are using Windows then navigate to Start | All Programs | Python 
2.4 | Python Manuals. Click the "Index" tab and enter "strip".

You will see that there is a strip() function in module string, and that 
strings have a .strip() method.

This is called "Reading the Documentation". Do it more. Your time is no 
more valuable than that of those who help on this list. Please try to 
respect it by answering questions as best you can *before* resorting to 
the list.

That way you'll continue to be a welcome visitor.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: add an asynchronous exception class

2006-03-04 Thread Robert Kern
Paul Rubin wrote:
> "Fredrik Lundh" <[EMAIL PROTECTED]> writes:
> 
>>PEP 348 addresses this by moving special exceptions out of the
>>Exception hierarchy:
>>
>>http://www.python.org/peps/pep-0348.html
> 
> I see that suggestion was rejected (it needed changing the semantics
> of "except:").  Also, PEP 348 was rejected and is a huge, complex
> reorganization of the whole exception system. 

The relevant part of PEP 348 survived as PEP 352.

  http://www.python.org/peps/pep-0352.html

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


build windows module for python-2.4

2006-03-04 Thread william
Does any one having working python 2.4 compiler can give some details
on how to set it up ?

I've read lot of different website, but some are outdated, others
referencing dead links, ...

I would just use an existing python 2.3 module (VC6) to python-2.4.
I think the best is to recompile it with VC7.1, but how to setup the VC
environements?

Thanks.

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


Re: stripping spaces in front of line

2006-03-04 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> f = open("textfile","rU")
> while (1):
> line = f.readline().strip()
> if line == '':
> break
> print line
> f.close()

Be warned that your code doesn't read the whole file if that file contains
lines with only whitespace characters. If you want to print every line,
change the loop to

while 1:
line = f.readline()
if line == "":
break
print line.strip()

i. e. don't strip() the line until you have tested for an empty string. The
idiomatic way to loop over the lines in a file is

for line in f:
print line.strip()

Peter


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


Re: How to Mount/Unmount Drives on Windows?

2006-03-04 Thread Christos Georgiou
On 25 Feb 2006 18:06:15 -0800, rumours say that [EMAIL PROTECTED] might
have written:

>Hello,



>I do not know how to mount or unmount drives on Windows. I think that
>it could possibly be done with a DOS command (using os.system()).

mountvol is the command you want.  I know it's in winxp, I think it was in
win2k too.

Check the Windows Help for its usage.

PS another command that is most useful is netsh, especially for laptops.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making a tiny script language using python: I need a string processing lib

2006-03-04 Thread Christos Georgiou
On 2 Mar 2006 17:53:38 -0800, rumours say that "Sullivan WxPyQtKinter"
<[EMAIL PROTECTED]> might have written:

>I do not know if there is any lib specially designed to process the
>strings in scipt language.
>for example:
>I hope to process the string"print a,b,c,d,e "in the form"command
>argumentlist" and return:
>{'command'='print',
>'argumentlist'=['a','b','c','d','e']}

Have you checked the shlex module in the standard library?  It might be
useful.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing an OPC client with Python ?

2006-03-04 Thread Jarek Zgoda
pierlau napisał(a):

>> You can call methods/functions in a .dll using ctypes.
>>
>> http://starship.python.net/crew/theller/ctypes/
> 
> I have tried with ctypes.
> I acheived to load the library
> it works when I use following instructions :
> print windll.OPCDAAuto or print cdll.OPCDAAuto
> (i see an handle number)
> But I can't run the functions?
> I there a way to 'see' the inside of the dll
> (i.e. to list the methods)  ?

Look for C header file (*.h) for this library or find docs.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
Roy Smith:
>I like to create a top-level exception class to encompass all the 
>possible errors in a given module, then subclass that.  This way, if you 
>want to catch anything to goes wrong in a call, you can catch the top-level 
>exception class without having to enumerate them all.

What do you propose to do with exceptions from modules called by the given
module?

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
James Stroud:
>Which suggests that "try: except HTTPException:" will be specific enough 
>as a catchall for this module.
>
>The following, then, should catch everything you mentioned except the 
>socket timeout:

Your conclusion may be (almost) right in this case. I just don't like this
approach. Basically this is reverse engineering the interface from the
source at the time of writing the app. Even if you get it right, it may
fail next week when someone added an exception to a module.

>But it seems to me that working with the internet as you are doing is 
>fraught with peril anyway.

Why? It shouldn't be.

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
Peter Hansen:
>Good code should probably have a very small set of real exception 
>handling cases, and one or two catchalls at a higher level to avoid 
>barfing a traceback at the user.

Good point.

>> A catchall seems like a bad idea, since it also catches AttributeErrors
>> and other bugs in the program.
>
>Generally speaking this won't be a problem if you have your catchalls at 
>a fairly high level and have proper unit tests for the lower level code 
>which is getting called.  You are doing unit testing, aren't you? ;-)

With low coverage, yes. But unit testing isn't the answer for this
particular problem. For example, yesterday my app was surprised by an
httplib.InvalidURL since I hadn't noticed this could be raised by
robotparser (this is undocumented). If that fact goes unnoticed when
writing the exception handling, it will also go unnoticed when designing
test cases. I probably wouldn't have thought of writing a test case with a
first url with some external domain (that triggers robots.txt-fetching)
that's deemed invalid by httplib.

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
Paul Rubin :
>We have to get Knuth using Python.

Perhaps a MIX emulator and running TeXDoctest on his books will convince
him..

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: build windows module for python-2.4

2006-03-04 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Does any one having working python 2.4 compiler can give some details
> on how to set it up ?
> 
> I've read lot of different website, but some are outdated, others
> referencing dead links, ...
> 
> I would just use an existing python 2.3 module (VC6) to python-2.4.
> I think the best is to recompile it with VC7.1, but how to setup the VC
> environements?
> 
> Thanks.
> 
http://www.vrplumber.com/programming/mstoolkit/

did it for me!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
Steven D'Aprano:
>ExpectedErrors = (URLError, IOError)
>ErrorsThatCantHappen =
>
>try:
>process_things()
>except ExpectedErrors:
>recover_from_error_gracefully()
>except ErrorsThatCantHappen:
>print "Congratulations! You have found a program bug!"
>print "For a $327.68 reward, please send the following " \
>"traceback to Professor Donald Knuth."
>raise
>except:
>print "An unexpected error occurred."
>print "This probably means the Internet is broken."
>print "If the bug still occurs after fixing the Internet, " \
>"it may be a program bug."
>log_error()
>sys.exit()

Yes, I think I'll do something like this. Perhaps combined with Peter's
advice to not micromanage, like so:

Reraise = (LookupError, ArithmeticError, AssertionError) # And then some

try:
process_things()
except Reraise:
raise
except:
log_error()

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Jorge Godoy
Rene Pijlman <[EMAIL PROTECTED]> writes:

> With low coverage, yes. But unit testing isn't the answer for this
> particular problem. For example, yesterday my app was surprised by an
> httplib.InvalidURL since I hadn't noticed this could be raised by
> robotparser (this is undocumented). If that fact goes unnoticed when

It isn't undocumented in my module.  From 'pydoc httplib':


CLASSES
exceptions.Exception
HTTPException
BadStatusLine
ImproperConnectionState
CannotSendHeader
CannotSendRequest
ResponseNotReady
IncompleteRead
InvalidURL <---  HERE
NotConnected
UnimplementedFileMode
UnknownProtocol
UnknownTransferEncoding
HTTPException
BadStatusLine
ImproperConnectionState
CannotSendHeader
CannotSendRequest
ResponseNotReady
IncompleteRead
InvalidURL
NotConnected
UnimplementedFileMode
UnknownProtocol
UnknownTransferEncoding
HTTP
HTTPConnection
HTTPSConnection
HTTPResponse


(Yes, it appears twice, don't ask me why...)

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Roy Smith
Rene Pijlman <[EMAIL PROTECTED]> wrote:

> A catchall seems like a bad idea, since it also catches AttributeErrors
> and other bugs in the program.

All of the things like AttributeError are subclasses of StandardError.  You 
can catch those first, and then catch everything else.  In theory, all 
exceptions which represent problems with the external environment (rather 
than programming mistakes) should derive from Exception, but not from 
StandardError.  In practice, some very old code may raise things which do 
not derive from Exception, which complicates things somewhat.

--
#!/usr/bin/env python   


import socket

try:
x = []
y = x[42]
except StandardError, foo:
print "Caught a StandardError: ", foo
except Exception, foo:
print "Caught something else: ", foo

try:
socket.socket ()
except StandardError, foo:
print "Caught a StandardError: ", foo
except Exception, foo:
print "Caught something else: ", foo

try:
raise "I'm a string pretending to be an exception"
except StandardError, foo:
print "Caught a StandardError: ", foo
except Exception, foo:
print "Caught something else: ", foo
--

Roy-Smiths-Computer:play$ ./ex.py
Caught a StandardError:  list index out of range
Caught something else:  (43, 'Protocol not supported')
Traceback (most recent call last):
  File "./ex.py", line 21, in ?
raise "I'm a string pretending to be an exception"
I'm a string pretending to be an exception
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Package organization: where to put 'common' modules?

2006-03-04 Thread Kent Johnson
fortepianissimo wrote:
> Say I have the following package organization in a system I'm
> developing:
> 
> A
>  |B
>  |C
> |D
> 
> I have a module, say 'foo', that both package D and B require. What is
> the best practice in terms of creating a 'common' package that hosts
> 'foo'? I want to be able to
> 
> - Testing modules in D right in D's directory and testing modules in B
> in B's directory;
> - If possible, minimize the modification to PYTHONPATH or sys.path
> while doing the above.

What I do is run always from the base directory (violates your first 
requirement). I make a util package to hold commonly used code. Then B 
and D both use
   from util import foo

In Python 2.5 you will be able to say (in D, for example)
   from ..util import foo

http://www.python.org/peps/pep-0328.html

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


Re: Write a GUI for a python script?

2006-03-04 Thread [EMAIL PROTECTED]
Another option would be FarPy GUIE: http://farpy.holev.com

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


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
Jorge Godoy:
>Rene Pijlman:
>> my app was surprised by an
>> httplib.InvalidURL since I hadn't noticed this could be raised by
>> robotparser (this is undocumented).
>
>It isn't undocumented in my module.  From 'pydoc httplib':

That's cheating: pydoc is reading the source :-)

What I meant was, I'm calling robotparser, and there's no mention of
exceptions on http://docs.python.org/lib/module-robotparser.html

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Rene Pijlman
Roy Smith:
>In theory, all exceptions which represent problems with the external 
>environment (rather than programming mistakes) should derive from 
>Exception, but not from StandardError.

Are you sure?

"""
The class hierarchy for built-in exceptions is:

Exception
 +-- StandardError
 |+-- KeyboardInterrupt
 |+-- ImportError
 |+-- EnvironmentError
 ||+-- IOError
"""
http://www.python.org/doc/current/lib/module-exceptions.html

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with os.spawnv

2006-03-04 Thread Damon Pettitt
I'm not sure if this is how I'm supposed to post, but I saw a thread entitled, 
"Help with os.spawnv", that I wanted to respond to.
 
I believe if you change the variable pyScript from:
"E:\\Documents and 
Settings\\Administrator\\Desktop\\Ian\\GIS\\Python\\subProcess2.py"
to
'"E:\Documents and 
Settings\Administrator\Desktop\Ian\GIS\Python\subProcess2.py"'
 
(this basically uses a single backslash and a single quote preceding the first 
double quote and a single quote just after the last double quote).
 
your script would work.
 
 
Damon Pettitt
 

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


Re: Package organization: where to put 'common' modules?

2006-03-04 Thread Jorge Godoy
Kent Johnson <[EMAIL PROTECTED]> writes:

> What I do is run always from the base directory (violates your first
> requirement). I make a util package to hold commonly used code. Then B and D
> both use
>   from util import foo
>
> In Python 2.5 you will be able to say (in D, for example)
>   from ..util import foo
>
> http://www.python.org/peps/pep-0328.html

I do work a bit different here.  When two programs start sharing code, then I
convert this code into a "library", i.e., I make it a module, put it in
PYTHONPATH and then import it.  Probably more than two projects will use it if
two of them already are :-)


-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing an OPC client with Python ?

2006-03-04 Thread F. GEIGER
About a year ago I dev'ed a host app in Python (2.3 at that time) to control 
a KUKA KR16 robot. Comm was over OPC. The OPC 2.0 server was inst'ed on the 
KRC2. What I was needed to do, was to install the appropriate (i.e. delivere 
together w/ the server) client software and to take Mark Hammonds COM Makepy 
utility to to create the wrapper. The rest of the story was fun, pure fun, 
as Python programming always is.

So, register the client software, fire up PythonWin, start the COM Makepy 
utility and wrap that DLL. If you are completely new to this stuff, it might 
help to look at all that from w/i MSVB 6.0 or something like that.

HTH
Franz GEIGER



"pierlau" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> Hello,
>
> I use an OPC server for connection to DC Drive.
> I would like to write a small OPC client.
> I have the dll OPCDAAuto.dll which contains all class and method but I 
> wonder if its possible to instance in python the class that are in the dll 
> ?
>
> Thanks for your help .
>
> Pierre
>
>
> 


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


Re: Win32api, pyHook, possibly win32com, not sure XD, thats why I'm posting

2006-03-04 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Is there a way to hide a python instance from the Task Manager process
> list?

Try sony's rootkit. Or any other.

Diez

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


Re: do design patterns still apply with Python?

2006-03-04 Thread Paul Novak
A lot of the complexity of design patterns in Java falls away
in Python, mainly because of the flexibility you get with dynamic
typing.  

For a Pythonic Perspective on Patterns, "Python Programming Patterns"
by Thomas W. Christopher is definitely worth tracking down.  It
looks like it is out of print, but you can find used copies on Amazon.

Regards,

Paul.

 


This sounds like an article crying out to be written,"(Learning) Design Patterns with Python".Has it been written already?
Cheers,TerryBruce Eckel began writing "Thinking In Python" it was last updated in 2001.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to except the unexpected?

2006-03-04 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Rene Pijlman <[EMAIL PROTECTED]> wrote:

> Roy Smith:
> >In theory, all exceptions which represent problems with the external 
> >environment (rather than programming mistakes) should derive from 
> >Exception, but not from StandardError.
> 
> Are you sure?
> 
> """
> The class hierarchy for built-in exceptions is:
> 
> Exception
>  +-- StandardError
>  |+-- KeyboardInterrupt
>  |+-- ImportError
>  |+-- EnvironmentError
>  ||+-- IOError
> """
> http://www.python.org/doc/current/lib/module-exceptions.html

Hmmm, OK, I missed EnvironmentError.  So, what you need to do is:

try:
   whatever()
except EnvironmentError:
   ...
except StandardError:
   ...
except Exception:
   ...

or something like that.

I do agree with you that there is some value in Java's "must catch or 
re-export all exceptions" semantics, and this would be one of those places 
where it would be useful.  In general, however, I've always found it to be 
a major pain in the butt, to the point where I sometimes just punt and 
declare all my methods to "throw Exception" (or whatever the correct syntax 
is).  Not to mention that with a dynamic language like Python, it's 
probably impossible to implement.

I think the real problem here is that the on-line docs are incomplete 
because they don't list all the exceptions that this module can raise.  The 
solution to that is to open a bug on sourceforge against the docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-04 Thread Bo Yang
Paul Novak 写道:
> A lot of the complexity of design patterns in Java falls away in 
> Python, mainly because of the flexibility you get with dynamic typing.
>
I agree with this very much !
In java or C++ or all such static typing and compiled languages , the 
type is fixed on
in the compile phrase , so for the flexible at the runtime , we often 
need to program to
interface . For example ,
we do in java :

implement I{...}
class A implement I{...}
class B implement I{...}

oprate(I var) // we can pass A's instance or B's instance here

and in C++ :

class Abstract{...}
class A : Abstract{...}
class B : Abstract{...}

oprate(Abstract var) // pass the A's instance or B's instance here

But in python , type is dynamic , and name is bind at runtime , so we 
can pass any variable as we want ! This feather make python not need for 
redundant class inherits
and interfaces which are the core of the GoF's design patterns I think !

> For a Pythonic Perspective on Patterns, "Python Programming Patterns" 
> by Thomas W. Christopher is definitely worth tracking down. It looks 
> like it is out of print, but you can find used copies on Amazon.
>
> Regards,
>
> Paul.
>
>
> This sounds like an article crying out to be written,
> "(Learning) Design Patterns with Python".
>
> Has it been written already?
>
> Cheers,
> Terry
>
>
> Bruce Eckel began writing "Thinking In Python" it was last updated
> in 2001.
>

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

Re: do design patterns still apply with Python?

2006-03-04 Thread Bo Yang
Paul Novak :
> A lot of the complexity of design patterns in Java falls away in 
> Python, mainly because of the flexibility you get with dynamic typing. 
>
I agree with this very much !
In java or C++ or all such static typing and compiled languages , the 
type is fixed on
in the compile phrase , so for the flexible at the runtime , we often 
need to program to
interface . For example ,
we do in java :

implement I{...}
class A implement I{...}
class B implement I{...}

oprate(I var) // we can pass A's instance or B's instance here

and in C++ :

class Abstract{...}
class A : Abstract{...}
class B : Abstract{...}

oprate(Abstract var) // pass the A's instance or B's instance here

But in python , type is dynamic , and name is bind at runtime , so we 
can pass any variable as we want ! This feather make python not need for 
redundant class inherits
and interfaces which are the core of the GoF's design patterns I think !
> For a Pythonic Perspective on Patterns, "Python Programming Patterns" 
> by Thomas W. Christopher is definitely worth tracking down.  It looks 
> like it is out of print, but you can find used copies on Amazon.
>
> Regards,
>
> Paul.
>
>  
>
> This sounds like an article crying out to be written,
> "(Learning) Design Patterns with Python".
>
> Has it been written already?
>
> Cheers,
> Terry
>
>
> Bruce Eckel began writing "Thinking In Python" it was last updated
> in 2001.
>

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


Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
I have made and recently posted a libary I made to do Modular
Arithmetic and Prime numbers on my website  at
http://www.geocities.com/brp13/Python/index.html . I am currently in a
crypotology class, and am working on building a RSA public key
cryptology system for a class project. I am building the librarys just
to get the experience to do so. However, I would ask if any of you know
of any gaping security holes that can easily be seen from my selection
of random prime numbers, ei, are they somehow predictable? Just wanting
to make sure. For simpler than going to the website, I used the ranint
function to pick a random prime number, then ran it through the miller
rabin primality test. It's a probabalistic test, which means it isn't
full proof, but there's still less than 1 in a million of giving a
false reading. Thanks! And if you should so want for some reason, feel
free to use it!

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


Re: socket freezes

2006-03-04 Thread Luis P. Mendes
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Thank you all for your suggestions.



Luis P. Mendes
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFECb5AHn4UHCY8rB8RAmeLAKCmSVfTvgQ94NPnJlD2QqdbMwVFXACdGFAh
8GL/9zxwXCYcmWxpyDweggE=
=9U0o
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-04 Thread Terry Hancock
On 3 Mar 2006 17:33:31 -0800
"sturlamolden" <[EMAIL PROTECTED]> wrote:
> 1. Time is money. Time is the only thing that a scientist
> cannot afford to lose. Licensing fees for Matlab is not an
> issue. If we can spend $1,000,000 on specialised equipment
> we can pay whatever Mathworks or Lahey charges as well.
> However, time spent programming are an issue. (As are time
> time spend learning a new language.)

"that man speaks for himself!" ;-)

Seriously, this depends on the lab. If you're working for
a monster pharmaceutical corp or on a military contract on
"applied" science (meaning there is a definitely payback
expected), then you likely have money to burn. People
working in a academic or non-profit lab on "unsexy"/"pure"
science, likely don't.

Remember that site-licensing usually works on some kind of
"per seat" basis (even if you are lucky enough *not* to have
a "license server" that constantly tracks usage in order to
deny service if and when N+1 users try to use the system,
the fee the site fee is still based on the number
of expected users).  The last science facility I worked at
was in considerable debt to a proprietary scientific
software producer and struggling to pay the bills.  The
result was that they had fewer licenses than they wanted
and many people simply couldn't use the software when they
wanted.

I'm not sure what happened in the end, because I left for
unrelated reasons before all of that got sorted out, but
Python (with a suitable array of add-ons) was definitely on
the short-list of replacement software (and partly because I
was trying to sell people on it, of course).

In fact, if I had one complaint about Python, it was the
"with a suitable array of add-ons" caveat. The proprietary
alternative had all of that rolled into one package (abeit
it glopped into one massive and arcane namespace), whereas
there was no "Python Data Language" or whatever that
would include all that in one named package that everyone
could recognize (I suppose SciPy is trying to achieve that).

For similar reasons, Space Telescope Science Institute
decided to go full tilt into python development -- they
created "numarray" and "pyraf", and they are the ones paying
for the "chaco" development contract.

Which brings up another point -- whereas with proprietary
software (and stuff written using it, like the IDL astronomy
library) can leave you with an enormous investment in stuff
you can't use, free software development can often be just
as cheap, and you get to keep what you make.

At one point, I was seriously thinking about trying to write
some kind of translator to convert those IDL libs into
python libs (quixotic of me?).

So why rent when you can own?

Scientists certainly do understand all that bit about
"seeing further" because you're "standing on the shoulders
of giants".  With proprietary software, the giants keep
getting shot out from under you, which tends to make things
a bit harder to keep up with.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


spliting on ":"

2006-03-04 Thread s99999999s2003
hi

i have a file with

xxx.xxx.xxx.xxx:yyy
xxx.xxx.xxx.xxx:yyy
xxx.xxx.xxx.xxx:yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx:yyy

i wanna split on ":" and get all the "yyy" and print the whole line out
so i did

print line.split(":")[-1]

but line 4 and 5 are not printed as there is no ":" to split. It should
print a "blank" at least.
how to print out lines 4 and 5 ?
eg output is

yyy
yyy
yyy


yyy

thanks

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


Re: spliting on ":"

2006-03-04 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> print line.split(":")[-1]
> 
> but line 4 and 5 are not printed as there is no ":" to split. It should
> print a "blank" at least.
> how to print out lines 4 and 5 ?
> eg output is
> 
> yyy
> yyy
> yyy
> 
> 
> yyy

if ":" in line:
   print line.split(":")[-1]
else:
   print

what's the problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Write a GUI for a python script?

2006-03-04 Thread Bill Maxwell
On Fri, 3 Mar 2006 07:19:34 -0500, "Peter Decker" <[EMAIL PROTECTED]>
wrote:

>I started with wxPython and struggled with it for a long time. I was
>able to get the job done, but using it never seemed natural. Then I
>found the Dabo project, whose ui module wraps wxPython into a much
>more Pythonic, consistent interface. Since then I've been able to
>create GUIs without much effort at all. I highly recommend Dabo if you
>are thinking about wxPython.

Dabo does look really nice, but seems like it has a ways to go yet.

I downloaded it a couple of weeks ago, and the very first thing I wanted
to do doesn't seem to be supported.  I tried to create a simple
application with a Notebook control inside a frame.  The Notebook
control doesn't appear to be supported yet.

Is that right, or am I just not looking in the right places?


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


Re: add an asynchronous exception class

2006-03-04 Thread Christian Stapfer
"Paul Rubin"  wrote in message 
news:[EMAIL PROTECTED]
> "Fredrik Lundh" <[EMAIL PROTECTED]> writes:
>> PEP 348 addresses this by moving special exceptions out of the
>> Exception hierarchy:
>>
>> http://www.python.org/peps/pep-0348.html
>
> I see that suggestion was rejected (it needed changing the semantics
> of "except:").  Also, PEP 348 was rejected and is a huge, complex
> reorganization of the whole exception system.  This is cited:
>
>  http://mail.python.org/pipermail/python-dev/2005-August/055423.html
>
> but it talks about distinguishing terminating from non-terminating
> exceptions, whatever that means.  (Won't any uncaught exception like
> ValueError terminate the program)?

I guess it means the following:

"Terminating exceptions" are exceptions that
terminate the *thrower* of the exception.
"Non-terminating exceptions" are exceptions
that might allow the thrower to resume
(provided the catcher does *not* decide
to unwind the thrower's stack frame - and
possibly some other frames as well...).
So non-terminating exceptions allow the
thrower to offer the catcher a choice
between terminating the thrower or having
him try harder (until he possibly throws
yet another, but maybe this time terminating
exception that does not allow the catcher to
ask for resumption of the throwing code).

  So what's terminated (or not terminated)
here is not the program but merely the
code that throws an exception.
  VAX/VMS had such a non-terminating exception
handling mechanism, for example.

Regards,
Christian


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


Re: Python advocacy in scientific computation

2006-03-04 Thread Alex Martelli
Terry Hancock <[EMAIL PROTECTED]> wrote:

> In fact, if I had one complaint about Python, it was the
> "with a suitable array of add-ons" caveat. The proprietary
> alternative had all of that rolled into one package (abeit
> it glopped into one massive and arcane namespace), whereas
> there was no "Python Data Language" or whatever that
> would include all that in one named package that everyone
> could recognize (I suppose SciPy is trying to achieve that).

I believe the Enthought distribution of Python (for Windows, with a Mac
version planned) is trying to move exactly in that direction, by
packaging up everything and a half (while of course leaving a reasonable
assignment of namespaces from the pieces it's packaging!-). However,
maintaining such a distro, and making it available for a wider variety
of platforms, are heavy, continuing tasks -- unless either firms, such
as Enthought, or volunteers, commit to such tasks, they won't "just
happen".


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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
I have discoved that the mod function isn't quite right in dealing with
powers, but, I'll have it fixed shortly.

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Alex Martelli
Tuvas <[EMAIL PROTECTED]> wrote:
   ...
> to make sure. For simpler than going to the website, I used the ranint

I assume you mean random.randint here.

> function to pick a random prime number, then ran it through the miller
> rabin primality test. It's a probabalistic test, which means it isn't
> full proof, but there's still less than 1 in a million of giving a

Miller-Rabin is not the problem -- rather, random.randint might be... it
makes no claims to be cryptographically strong, in either the current
Mersenne implementation or the previous Wichman-Hill one. Could you
maybe use /dev/random or the like?  Cfr
 for an introduction to the
subject.  (For speed, you may want to look into gmpy.sf.net, but that's
quite a separate issue from the strength of your random numbers).


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


Easy immutability in python?

2006-03-04 Thread Terry Hancock
Is there an *easy* way to make an object immutable in
python?  Or perhaps I should say "one obvious way to do it"?
Oughtn't there to be one?

I've found a thread on how to do this[1], which essentially
says something like "redefine __setattr__, __delattr__,
__hash__, __eq__, __setitem__, delitem__ ... and probably
some other stuff too".

[1]

Yet, what you have to do is pretty mechanical (e.g. all the
mutators have to raise NotImplementedError and the hashes
and comparisons seem like they have obvious defaults).

Given that I have some kind of container, like an overloaded
list, and I just say "oh, I need that to be immutable, like
a tuple" -- it would be nice to just be able to declare it
so.  I just want this for QA purposes -- I have a pretty
complex system, and I want the programmer to be warned when
he accidentally tries to change an immutable enumeration or
redefine a symbol.

I know a (hard and error-prone) way to do it, but I'm
thinking there must be a "smart" way to do it.

Is there some way to do that with, e.g. decorators?

(I haven't really figured out why I should want decorators,
is this a use case?).

Or maybe I should make an "Immutable" class, and just
inherit from it last so it overloads everything else with
the null interfaces?

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Michael Tobis
There is a range of folks doing scientific programming. Not all of them
are described correctly by your summary, but many are. The article is
aimed not at them, but rather at institutions that develop engineered
Fortran models using multipuurpose teams and formal methods. I
appreciate your comments, because I see that there should be another
article aimed at desktop programmers.

One of the things python addresses best is the division of labor, where
the subtle concepts are available to those who need them and hidden
from those who don't need them. From what I understand of your work
(and what I have seen of the work of two other neuroscientists,
actually) Python would be a good choice for you.

That said, the level of computational skill in many scientists is
alarming. Why do we expect to spend six semesters learning mathematics
and expect to pick up computing "on the side"? It baffles me.  Frankly,
saying "I don't need version control" sounds to me no less foolish than
 saying "I don't need logarithms". (Perhaps you don't but someday soon
you will.)

"Speed of excecution is an issue, regardless of what computer science
folks try to tell you." strikes me as nothing short of hallucinatory.
No informed person says that speed is never an issue, and a great deal
of effort is spent on  speed. Where do you suppose your Fortran
compiler came from in the first place?

For someone without legacy code to worry about, fussing with Fortran
for single-user one-off codes strikes me as a weak choice. If you are
hitting Matlab's performance or memory limits, you should take the time
to learn something about computation, not because you are idle, but
because you are busy. Or if you prefer, because your competitors will
be learning how to be more productive while you put all your efforts
into coping with crude tools.

The peculiar lack of communication between computer scientists and
application scientists is real; but I believe the fault is not all on
one side. The fact that you have a PhD does not prove that you know
everything you need to know, and I strongly recommend you reconsider
this attitude. For one thing, you misjudged which side of the divide I
started on.

Michael Tobis
(While I dislike credentialism on usenet, I will reply in kind. I hold
a Ph.D. in geophysical fluid dynamics.)

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
Well, the RSA element's never going to encrypt more than a small, 1
block system except under rare occasions, the primary encryption will
be AES128. Thanks for the help though!

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


Re: spliting on ":"

2006-03-04 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> hi
> 
> i have a file with
> 
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx:yyy
> xxx.xxx.xxx.xxx
> xxx.xxx.xxx.xxx
> xxx.xxx.xxx.xxx:yyy
> 
> i wanna split on ":" and get all the "yyy" and print the whole line out
> so i did
> 
> print line.split(":")[-1]
> 
> but line 4 and 5 are not printed as there is no ":" to split. It should
> print a "blank" at least.
> how to print out lines 4 and 5 ?
> eg output is
> 
> yyy
> yyy
> yyy
> 
> 
> yyy

That's not what I get:

In [2]: data='''xxx.xxx.xxx.xxx:yyy
...: xxx.xxx.xxx.xxx:yyy
...: xxx.xxx.xxx.xxx:yyy
...: xxx.xxx.xxx.xxx
...: xxx.xxx.xxx.xxx
...: xxx.xxx.xxx.xxx:yyy'''.splitlines()

In [3]: for line in data:
...: print line.split(':')[-1]
...:
...:
yyy
yyy
yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
yyy

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Brian Blais
sturlamolden wrote:
> 
> Typically a scientist need to:
> 
> 1. do a lot of experiments
> 
> 2. analyse the data from experiments
> 
> 3. run a simulation now and then
> 

unless you are a theorist!  in that case, I would order this list backwards.


> 
> 1. Time is money. Time is the only thing that a scientist cannot afford
> to lose. Licensing fees for Matlab is not an issue. If we can spend
> $1,000,000 on specialised equipment we can pay whatever Mathworks or
> Lahey charges as well. However, time spent programming are an issue.
> (As are time time spend learning a new language.)
> 

Another person stated that they don't have infinite funds, as implied here.  I 
would
add that, in addition to one's own research, professors must also teach and 
advise.
I find it very helpful to be able to say to a student, "go download this, and 
here is
the code I wrote for the work I do".  The price is often an impediment for 
getting 
students into research.  Often there are site licenses, but they don't work off 
campus.


> 2. We don't need fancy GUIs. GUI coding is a waste of time we don't
> have. We don't care if Python have fancy GUI frameworks or not.
> 

again, for sharing ideas, GUIs are *necessary*.  If you work with people who do 
less 
programming than you, then you need to make an interface to your code that they 
can 
understand.  it doesn't have to be fancy, just functional.

> 3. We do need fancy data plotting and graphing. We do need fancy
> plotting and graphing that are easy to use - as in Matlab or S-PLUS.
> 

here, I've found python to be good, but not great.  matplotlib (pylab) is a 
really 
great thing, but is not as straightforward as plotting in Matlab.  Either, you 
have a 
window which locks the process until you close it, or you do interactive mode, 
but 
the window results disappear if any other window is put on top (like your 
shell), and 
has to be manually redrawn.  This makes it far less convenient to deal with in 
interactive mode.

> 4. Anything that has to do with website development or enterprise class
> production quality control are crap that we don't care about.
> 

I think it can be pitched as an alternative to shell-scripts, which is a nice 
economy 
of concepts: the language you use for your scientific work, you can also use 
for your 
OS work, and your tinkering.


> 7. "My simulation is running to slowly" is the number ONE complaint.
> Speed of excecution is an issue, regardless of what computer science
> folks try to tell you. That is why we spend disproportionate amount of
> time learning to vectorize Matlab code.
> 

here, I would plug Pyrex like crazy.  to me the Python/Pyrex combination is the 
biggest selling point for me to convert my scientific matlab code to Python. 
Learning a new API is a drag, and I've found that SWIG is not particularly 
intuitive 
(although convenient, if you have a lot of libraries already written).  Pyrex 
seems 
to get the best of all possible worlds: seamless use of python objects, and the 
ability to do C-loops for speed, with no API.  Making extensions this way is a 
real joy.


> Now please go ahead and tell me how Python can help me become a better
> scientist. And try to steer clear of the computer science buzzwords
> that don't mean anyting to me.
> 


I have been using Matlab for nearly 10 years.  My claim to no-fame is the 
neural 
network simulator Plasticity (http://web.bryant.edu/~bblais/plasticity) which 
has 
taken me years to write.  I have some complaints about Matlab, but it has been 
a 
useful tool.  Some of my complaints are as follows:

1) Cost.  I find that the marketing model for Matlab is annoying.  They 
nickle-and-dime you, with the base package (educational pricing) at $500 per 
machine/operating system/user and then between $200-$500 *per* "toolbox", which 
adds 
up really quick.   I can't even buy 1 license for a dual boot, to have Matlab 
run on 
a Linux partition and a Windows partition.

The cost impacts my use of Matlab in the classroom, and with research students.

2) License Manager.  The license manager for Matlab is the most inconvenient 
program 
I have ever dealt with.  It is incredibly sensitive to the license file, and it 
nearly impossible to debug.  This has made Matlab one of the hardest programs 
to 
install, for me.  The issue that impacts my productivity is the following: the 
license key is tied to the network card, on eth0.  Thus, if I upgrade my 
laptop, I 
need to contact Mathworks for an updated license key.  Also, occasionally, my 
operating system decides to name my wireless card eth0, and my wired card eth1. 
Nothing else is affected by this, but then I can't run Matlab!

3) Upgrade Version Hell.  *Every* time Matlab has upgraded, my program has 
broken. 
Usually something small, but still it is a real pain in the butt.  Also, I have 
to 
pay full price for the upgrade, or pay some fee continuously whether there is 
an 
upgrade or not.

I have only been using Python for about 2 months, 

Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
Okay, the bug in my code has been fixed, it should work alot better
now... I thought I had tested the power function, but I appearently
wasn't even close... But now it works just fine.

I guess you are right, I will have to work on a better system to be
cryptologically secure. But, at least I have a start. Thanks for the
help!

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


Re: re-posting: web.py, incomplete

2006-03-04 Thread _wolf
ok, that does it! [EMAIL PROTECTED] a lot!

sorry first of all for my adding to the confusion when i jumped to
comment on that ``-u`` option thing---of course, **no -u option** means
**buffered**, positively, so there is buffering and buffering problems,
**with -u option** there is **no buffer**, so also no buffering
problems at that point. these add-option-to-switch-off things do get
confusing sometimes.

ok, so the ``#!/usr/local/bin/python -u`` does work. as noted on
http://www.imladris.com/Scripts/PythonForWindows.html: "Trying to run
python cgi scripts in the (default) buffered mode will either result in
a complete lack of return value from your cgi script (manifesting as a
blank html page) or a "premature end of script headers" error." funny
you don't get to see a lot of ``-u`` shebang lines these days tho. as
the document goes on to explain, there is a way to put ::

SetEnv PYTHONUNBUFFERED 1

into your apache ``httpd.conf``. this works for me! great!

now, thinking about this problem it strikes me it has never bitten me
before, where it should have. is there something special about the way
web.py cgi apps work that make this thing pop up? also, in theory,
since apache itself (as of v1.3) does no buffering of cgi output, then
when apache calls a cgi process, and that process happily buffers at
its own descretion, and then finalizes and terminates, then should the
remaining buffer not be output and sent to apache---as happens with a
script run from the command line? you do get to see all the output in
that case, at long last upon process termination, right? i'm wondering.

_wolf

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


Re: Write a GUI for a python script?

2006-03-04 Thread Peter Decker
On 3/4/06, Bill Maxwell <[EMAIL PROTECTED]> wrote:

> Dabo does look really nice, but seems like it has a ways to go yet.
>
> I downloaded it a couple of weeks ago, and the very first thing I wanted
> to do doesn't seem to be supported.  I tried to create a simple
> application with a Notebook control inside a frame.  The Notebook
> control doesn't appear to be supported yet.
>
> Is that right, or am I just not looking in the right places?

It's fully supported. Their generic term for these paged controls is a
'pageframe', so a wx.Notebook is their dPageFrame class; wx.Listbook
is their dPageList class; wx.Choicebook is their dPageSelect, and they
also have a page control with no tabs called (gasp!) dPageFrameNoTabs.
One thing that they've done is pick names for classes and properties
that are the most common for all toolkits instead of blindly following
the wx names.

All of these classes have the same interface, and respond to the same
events. IOW, they've unified these different classes so that they have
a single API, making working with them much easier.

--

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy immutability in python?

2006-03-04 Thread jess . austin
Since this is a container that needs to be "immutable, like a tuple",
why not just inherit from tuple?  You'll need to override the __new__
method, rather than the __init__, since tuples are immutable:

class a(tuple):
def __new__(cls, t):
return tuple.__new__(cls, t)

cheers,
Jess

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


Re: How to except the unexpected?

2006-03-04 Thread Roman Susi
Rene Pijlman wrote:
> Paul Rubin :
> 
>>We have to get Knuth using Python.
> 
> 
> Perhaps a MIX emulator and running TeXDoctest on his books will convince
> him..

Or maybe Python written for MIX...


-Roman

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


license preamble template

2006-03-04 Thread Xah Lee
I noticed, that in just about all emacs programs on the web (elisp
code), it comes with this template text as its preamble:

;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2, or (at
;; your option) any later version.

;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

Concerned parties and the FSF foundation, please remove the middle
section of this template. That section is mainly for lawyers, for
programers to protect themselves in the context of modern society's law
system. Legally speaking, that section is redundant because it is in
the GNU General Public License itself. The effect of that section in a
license summary is fueling the habit and sanction of irresponsible
programing we see all around us.

In place of that section, i'd propose replacing it with the following
gist:

«This program is distributed in the hope that it will be useful. The
author(s) has responsibly produced it, and will take reasonable
responsibilities with regards to the program's intended purpose and
workability. For legal aspects of WARRANTY, please see the GNU General
Public License for more details.»

Regarding these issues, please read:

Responsible Software Licensing
http://xahlee.org/UnixResource_dir/writ/responsible_license.html

Responsible Software Licensing & the Free Software Foundation
http://xahlee.org/UnixResource_dir/writ/responsible_license_FSF.html

   Xah
   [EMAIL PROTECTED]
 ∑ http://xahlee.org/

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

Re: Easy immutability in python?

2006-03-04 Thread jess . austin
To be clear, in this simple example I gave you don't have to override
anything.  However, if you want to process the values you place in the
container in some way before turning on immutability (which I assume
you must want to do because otherwise why not just use a tuple to begin
with?), then that processing should take place in a.__new__.

cheers,
Jess

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


generators shared among threads

2006-03-04 Thread jess . austin
hi,

This seems like a difficult question to answer through testing, so I'm
hoping that someone will just know...  Suppose I have the following
generator, g:

def f()
i = 0
while True:
yield i
i += 1
g=f()

If I pass g around to various threads and I want them to always be
yielded a unique value, will I have a race condition?  That is, is it
possible that the cpython interpreter would interrupt one thread after
the increment and before the yield, and then resume another thread to
yield the first thread's value, or increment the stored i, or both,
before resuming the first thread?  If so, would I get different
behavior if I just set g like:

g=itertools.count()

If both of these idioms will give me a race condition, how might I go
about preventing such?  I thought about using threading.Lock, but I'm
sure that I don't want to put a lock around the yield statement.

thanks,
Jess

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


Re: do design patterns still apply with Python?

2006-03-04 Thread jess . austin
msoulier wrote:

> I find that DP junkies don't tend to keep things simple.

+1 QOTW.  There's something about these "political" threads that seems
to bring out the best quotes.  b^)

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


Re: How to except the unexpected?

2006-03-04 Thread Bruno Desthuilliers
Rene Pijlman a écrit :
> Jorge Godoy:
> 
>>Rene Pijlman:
>>
>>>my app was surprised by an
>>>httplib.InvalidURL since I hadn't noticed this could be raised by
>>>robotparser (this is undocumented).
>>
>>It isn't undocumented in my module.  From 'pydoc httplib':
> 
> 
> That's cheating: pydoc is reading the source :-)

Yes, and that's the Right Thing(tm) to do. Source code don't lie. Source 
  code don't get out of sync. So source code *is* the best documentation 
(or at least the most accurate).

> What I meant was, I'm calling robotparser, and there's no mention of
> exceptions on http://docs.python.org/lib/module-robotparser.html
> 
That's why reading the source is better. CQFD !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


The old round off problem?

2006-03-04 Thread sam
Hello all, I am taking a class in scientific programming at the local
college. My problem is that the following difference produces round off
errors as the value of x increases. For x >= 19 the diference goes to
zero.I understand the problem, but am curious as to whether their
exists a solution. I have tried various graphing programs,and they all
exihibit this problem.

thanks in advance Sam Schulenburg
f(x)  = cosh^2(x) - sinh^2(x)  = 1

>>> from math import *
>>> for x in range(20):
print "x= %2d  Sinh^2(x) = %20.3f f(x) = %2.10f
"%(x,pow(cosh(x),2),pow(cosh(x),2)- pow(sinh(x),2))


x=  0  Sinh^2(x) =1.000 f(x) = 1.00
x=  1  Sinh^2(x) =2.381 f(x) = 1.00
x=  2  Sinh^2(x) =   14.154 f(x) = 1.00
x=  3  Sinh^2(x) =  101.358 f(x) = 1.00
x=  4  Sinh^2(x) =  745.740 f(x) = 1.00
x=  5  Sinh^2(x) = 5507.116 f(x) = 1.00
x=  6  Sinh^2(x) =40689.198 f(x) = 1.00
x=  7  Sinh^2(x) =   300651.571 f(x) = 0.99
x=  8  Sinh^2(x) =  2221528.130 f(x) = 1.00
x=  9  Sinh^2(x) = 16414992.784 f(x) = 1.37
x= 10  Sinh^2(x) =121291299.352 f(x) = 1.000298
x= 11  Sinh^2(x) =896228212.033 f(x) = 0.998808
x= 12  Sinh^2(x) =   6622280532.961 f(x) = 1.019073
x= 13  Sinh^2(x) =  48932402357.710 f(x) = 0.923706
x= 14  Sinh^2(x) = 361564266073.369 f(x) = 0.389648
x= 15  Sinh^2(x) =2671618645381.616 f(x) = 1.00
x= 16  Sinh^2(x) =   19740740045670.668 f(x) = 0.9921875000
x= 17  Sinh^2(x) =  145865435631864.219 f(x) = 1.00
x= 18  Sinh^2(x) = 1077807886778799.250 f(x) = 1.00
x= 19  Sinh^2(x) = 7963982939278438.000 f(x) = 0.00 
>>>

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


Is there a WSGI sollutions repository somewhere

2006-03-04 Thread Damjan
It seems that WSGI support starts to flourish is there some document or
a web site that tracks what's out there, some place to pick and choose
WSGI components?

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


Re: PyQt issue

2006-03-04 Thread Damjan
> Because you wrote curentText - note the missing t.

:)

You mean the missing 'r'

:)

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


Re: generators shared among threads

2006-03-04 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> hi,
> 
> This seems like a difficult question to answer through testing, so I'm
> hoping that someone will just know...  Suppose I have the following
> generator, g:
> 
> def f()
> i = 0
> while True:
> yield i
> i += 1
> g=f()
> 
> If I pass g around to various threads and I want them to always be
> yielded a unique value, will I have a race condition?  That is, is it

Yes, you will.

> before resuming the first thread?  If so, would I get different
> behavior if I just set g like:
> 
> g=itertools.count()

I believe that in the current implementation you'd get "lucky", but
there is no guarantee that such luck would persist across even a minor
bugfix in the implementation.  Don't do it.
 
> If both of these idioms will give me a race condition, how might I go
> about preventing such?  I thought about using threading.Lock, but I'm
> sure that I don't want to put a lock around the yield statement.

Queue.Queue is often the best way to organize cooperation among threads.
Make a Queue.Queue with a reasonably small maximum size, a single
dedicated thread that puts successive items of itertools.count onto it
(implicitly blocking and waiting when the queue gets full), and any
other thread can call get on the queue and obtain a unique item
(implicitly waiting a little bit if the queue ever gets empty, until the
dedicated thread waits and fills the queue again).  [[Alternatively you
could subclass Queue and override the hook-method _get, which always
gets called in a properly locked and thus serialized condition; but that
may be considered a reasonably advanced task, since such subclassing
isn't documented in the reference library, only in Queue's sources]].


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


Re: Easy immutability in python?

2006-03-04 Thread Terry Hancock
Whoops I forgot to list the reference.
Also, I just finished reading the old thread, so I see some
damage-control may be needed.

On Sat, 4 Mar 2006 11:52:59 -0600
Terry Hancock <[EMAIL PROTECTED]> wrote:
> [1]
> http://news.hping.org/comp.lang.python.archive/28916.html

And more specifically, I'm referring to Alex Martelli's
reply:

http://news.hping.org/comp.lang.python.archive/28966.html

[Vain attempt to co-opt a flame-war follows]

And having seen that that discussion largely devolved into a
rant about why "you shouldn't do that", can we PLEASE
restrict this thread to the *how*?

My use case is quite similar to Ben's enumeration type. In
both cases, assigning attributes to the objects is
NONSENSICAL and possibly UNWISE.  Any attempt to do so is
almost certainly a bug in your code if you are using my
module -- and it happens to be one I want to make sure I
catch.  It is also true that the average person using my
code is not a blackbelt pythoneer, but rather a scripter who
needs/wants training wheels whenever it is practical to
provide them.

If you are REALLY sure you want mutability, you can always
subclass it.

If you think that code that handles prime numbers by marking
integer objects like so:

101.prime = True

is "just fine", and are not bothered that 101 is
mysteriously unclassified sometime after you've marked it
(because 100+1 is 101 == False), then we are not going to
see eye-to-eye, so let's not argue about it.

I also am not trying to alter the Python language. I am
trying to figure out how to most easily fix __setattr__ etc
to act immutably, *using* the existing features.

I can already do what I want with some 25-30 lines of code
repeated each time I need it, but I think it's dumb that
it's that complicated.

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Python advocacy in scientific computation

2006-03-04 Thread David Treadwell
On Mar 4, 2006, at 5:55 AM, Dennis Lee Bieber wrote:


> On Fri, 3 Mar 2006 22:05:19 -0500, David Treadwell
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
>
>
>> My ability to think  of data structures was stunted BECAUSE of
>> Fortran and BASIC. It's very difficult for me to give up my bottom-up
>> programming style, even though I write better, clearer and more
>> useful code when I write top-down.
>>
>>

IIRC, during 1984, my senior year, BYTE magazine had a cover story on  
OOP. (OH, how I loved the cover art back in the day!) My impression  
after reading the article: WTF is that for? Every class I had which  
needed programming, be it CS or chemical engineering, taught it in a  
very linear, bottom-up fashion. First you read inputs, then do Foo,  
then do Bar, then do (fill in your favorite third-level word).

It was even worse in the chemistry department. No chem major (other  
than myself, as I also was a chem eng major) had _any_ computer  
courses beyond the required Fortran 101. It was a struggle to get any  
chemistry student to do anything that required using LINPAC,  
Mathematical Recipes code or a plotting program.

This level of absurdity reached its apex during grad skewl when I  
wrote a monolithic 30-page program in MS QuickBasic for Mac to  
simulate NMR spectra. No one else was ever able to understand how to  
use the program.

Even worse, that 30-page program disappeared the day Mac System 7.0  
was installed. The byte-compiled basic code became unreadable because  
System 7 permanently broke QuickBasic.

The last program I wrote for anyone else's use was written in VBA/ 
Excel. I hated every minute of it, but the request was made because  
everyone has Excel, and nobody wanted to install Python. VBA has at  
least 3 API's running simultaneously (Excel, VBA-classic and VBA- 
pseudoOOP). Now that I know Py2App, that dragon has been slain.

Which brings me to my last point: Why be beholden to the graces of a  
single-source supplier of a language or OS? Proprietary systems will  
always become either (a) extinct or (b) so crammed with legacy code  
they become unreliable.

I still don't get OOP completely, but Python has helped a great deal.


>   FORTRAN was quite amenable to "top-down" design (which was barely
> taught during my senior year: 1980; and I'm a CS major -- you don't  
> want
> to see the text used for the "systems analysis" class; I don't recall
> ever seeing a "requirement document" created in the entire text...)
>
>   I've done lots of FORTRAN stuff where the main program was
> interchangeable...
>
>   program main
>   ...
>   call Initialize()
>   call Process()
>   call CleanUp()
>   stop
>   end
>

Sure. It seems logical now. But remember, I learned WatFiv Fortran,  
which came before even Fortran 77. I saw my first Fortran 95 code  
about two years ago. It took me a while to realize that what I was  
looking at _was_ Fortran!


>> 3. I demand a general-purpose toolkit, not a gold-plated screwdriver.
>>
>
>   Would a gold-plated sonic screwdriver work?  {Let's see how many
> catch that reference}
>

Google makes this game too easy, but it's to Who you refer. How about  
_this_ reference: "What we all need is a left-handed monkey wrench."  


:--David

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


how to record how long i use the intenet

2006-03-04 Thread b53444
use python
use ADSL
use windows XP
i want to record the time when i get on the internet and off the
internet
into a txt file
HOW?

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


Papers on Dynamic Languages

2006-03-04 Thread Jay Parlar
For one of my grad school classes, I'm writing a paper on "Dynamic 
Languages". What a wonderfully vague topic (but at least it'll let me 
write about Python).

Anyway, I want to talk about things like typing disciplines (weak, 
strong, etc.),"class vs. prototype, JIT technologies in dynamic 
languages, interactive interpreters, etc.

I've got Brett Cannon's thesis already, but I'm looking for references 
to some more papers on these topics. A Python basis for any of the 
papers would be preferred, but anything will do.

Any suggestions? This is my first real research paper in grad school, 
so I'm starting out from scratch here.

Jay P.

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


XP rich text cut-n-paste

2006-03-04 Thread Paddy
Hi,
Is their a colourized editor/shell that allows you to cut and paste the
colourized text?

Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both
command line input as well as editor windows but when I cut and paste
(in this case, into OpenOffice Writer), even the paste-special menu
just allows the pasting of un-adorned text.

i have a work-around: gvim coourizes and allows export as html, but it
is long-winded.

Thanks in advance, Paddy.

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


Re: Easy immutability in python?

2006-03-04 Thread Terry Hancock
On 4 Mar 2006 10:14:56 -0800
[EMAIL PROTECTED] wrote:
> Since this is a container that needs to be "immutable,
> like a tuple", why not just inherit from tuple?  You'll
> need to override the __new__ method, rather than the
> __init__, since tuples are immutable:
> 
> class a(tuple):
> def __new__(cls, t):
> return tuple.__new__(cls, t)

The reason this is undesireable, is because in the typical
use-case, I want to have TWO kinds of objects, one mutable,
and one immutable. Just like tuple / list. I would prefer
not to have to implement them completely separately.  So
far, it's usually simpler to implement the mutable type
first -- the need for immutability semantics usually arises
after you have a mutable version. 

But undoing mutability apparently is like making a sieve
watertight -- it would've been easier to design a ladle and
then put holes in it, than to design a sieve and then stop
up the holes.

In fact, my particular case wants to subclass Set and
ImmutableSet -- their contents, though, are also immutables
in principle.  In fact the elements are similar to "int" or
"str", but I don't want to subclass those, because I don't
want them to have math methods or string methods.

I've considered several different approaches to this. One is
to create a "BaseVocabulary" as an abstract class, from
which the mutable and immutable types are drawn, and then
mix it in with Set and ImmutableSet:

class BaseVocabulary(object):
def __init__(self, values):
self._data = values
# (or something like that)
# other functionality

class Vocabulary(Set, BaseVocabulary):
# stuff appropriate for the "open" vocabulary
pass

class Enumeration(ImmutableSet, BaseVocabulary):
# stuff appropriate for the "closed" enumeration
pass

This is bad, both aesthetically and practically.
Aesthetically, because "abstract classes stink of Java" and
pragmatically because the __init__ from BaseVocabulary
will generally not work for the immutable case.

So I either have to rewrite it special, or go back in
time and fix the original, knowing that I'm going to want
an immutable variant.

Again with the aesthetics, it's just ugly that I can't
mutate an object in its __init__ and then make it immutable
after I'm done setting it up. The approach with __new__ and
using the superclass's __setattr__ to set values is nasty
boilerplate-rich cruft which forces me to go back and
completely re-implement the same functionality in a
completely different way, just because of something that
seems like a simple conceptual change (i.e. "don't overwrite
or extend this thing -- make a new one if you need a
change").

I even tried defining __setattr__ at the end of the
__init__, but that doesn't seem to work (or I'm doing it
wrongly).

Right now I'm leaning towards making a class "Immutable"
with all the mutator methods raising NotImplementedError,
and then subclass from this so that it overrides the
necessary methods. It's still going to mess with me, though,
because it will not allow the __init__ to work as planned,
and I'll have to go back and redesign the base class to work
with or without immutability.

Alternatively, I could just decide to change my practice and
implement ALL objects on the assumption that they will be
immutable, and add *mutability* after-the-fact. But that
seems like extraordinarily bad practice, since mutability is
usually the better default.

I'm going to dig through the sets module code to see how it
does this, but what little I've seen gives me a bad feeling
that this simple idea is hard to implement simply in Python
-- and that strikes me as a "wart", yes.

So, I'm wondering if there is a simple way after all.

1) Is there an idiom for this that I just don't know?

2) Have recent changes to the language made it easier?
   (__new__ for example, is apparently new, or at least
   newly documented -- but as I say, I'm not sure it's
   the most practical solution for this problem).

3) Is there a "remarkably clever" way that I can tack
   on, even if it isn't exactly simple?

and only in the unlikely event that answers 1-3 are all
"no", would I ask:

4) And as a last resort, if it really is hard, why?
   Shouldn't a simple idea to express in English be easy to
   express in Python? If it's really impossibly difficult,
   maybe Python should provide a means to implement it.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: spliting on ":"

2006-03-04 Thread Cyril Bazin
Your file looks like a list of IP adresses. You can use the urllib and urllib2 modules to parse IP adresses.import urllib2for line in open("fileName.txt"):    addr, port  = urllib2.splitport(line)
    print (port != None) and '' or portCyril
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Easy immutability in python?

2006-03-04 Thread jess . austin
I guess we think a bit differently, and we think about different
problems.  When I hear, "immutable container", I think "tuple".  When I
hear, "my own class that is an immutable container", I think, "subclass
tuple, and probably override __new__ because otherwise tuple would be
good enough as is".

I'm not sure how this relates to the clp thread that you cite.  I
didn't read the whole thing, but I didn't find it to be a flamewar so
much as a typical clp contest of tedium, which failed to devolve into a
flamewar simply due to the maturity of the interlocutors.  To
summarize: first post is a use case, second post is an implementation
of that use case, and subsequent posts alternate between "that's not
how I want to do it" and "please provide a more specific use case for
which the provided implementation is not acceptable".

good luck,
Jess

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


Re: Easy immutability in python?

2006-03-04 Thread Alex Martelli
Terry Hancock <[EMAIL PROTECTED]> wrote:
   ...
> I also am not trying to alter the Python language. I am
> trying to figure out how to most easily fix __setattr__ etc
> to act immutably, *using* the existing features.
> 
> I can already do what I want with some 25-30 lines of code
> repeated each time I need it, but I think it's dumb that
> it's that complicated.

If you need many immutable classes, inject __setattr__ etc into them
(via metaclass or otherwise).


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


Re: how to record how long i use the intenet

2006-03-04 Thread Gerard Flanagan

[EMAIL PROTECTED] wrote:
> use python
> use ADSL
> use windows XP
> i want to record the time when i get on the internet and off the
> internet
> into a txt file
> HOW?


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


HTH

Gerard

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


Re: Python advocacy in scientific computation

2006-03-04 Thread Terry Hancock
On Sat, 4 Mar 2006 14:23:10 -0500
David Treadwell <[EMAIL PROTECTED]> wrote:
> On Mar 4, 2006, at 5:55 AM, Dennis Lee Bieber wrote:
> > On Fri, 3 Mar 2006 22:05:19 -0500, David Treadwell
> > <[EMAIL PROTECTED]> declaimed the following
> > in comp.lang.python:
> >> 3. I demand a general-purpose toolkit, not a
> >gold-plated screwdriver. >
> >
> > Would a gold-plated sonic screwdriver work? 
> > {Let's see how many
> > catch that reference}
> >
> 
> Google makes this game too easy, but it's to Who you
> refer. How about   _this_ reference: "What we all need is
> a left-handed monkey wrench."   

You know, it just occured to me that you sent me on a quest
to get a "left-handed monkey wrench", and like a fool, I
went.  Of course, I found not one, but many...

In fact, this expression has so many echoes on the
web, it would be difficult to ascertain where it actually
came from (the derivation is obvious, of course, but who
first coined the expression?).

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: How to except the unexpected?

2006-03-04 Thread James Stroud
Rene Pijlman wrote:
> Steven D'Aprano:
> 
>>ExpectedErrors = (URLError, IOError)
>>ErrorsThatCantHappen =
>>
>>try:
>>   process_things()
>>except ExpectedErrors:
>>   recover_from_error_gracefully()
>>except ErrorsThatCantHappen:
>>   print "Congratulations! You have found a program bug!"
>>   print "For a $327.68 reward, please send the following " \
>>   "traceback to Professor Donald Knuth."
>>   raise
>>except:
>>   print "An unexpected error occurred."
>>   print "This probably means the Internet is broken."
>>   print "If the bug still occurs after fixing the Internet, " \
>>   "it may be a program bug."
>>   log_error()
>>   sys.exit()
> 
> 
> Yes, I think I'll do something like this. Perhaps combined with Peter's
> advice to not micromanage, like so:
> 
> Reraise = (LookupError, ArithmeticError, AssertionError) # And then some
> 
> try:
> process_things()
> except Reraise:
> raise
> except:
> log_error()
> 

Why catch an error only to re-raise it?

This falls under http://c2.com/cgi/wiki?YouReallyArentGonnaNeedThis
-- 
http://mail.python.org/mailman/listinfo/python-list


Open source reliability study

2006-03-04 Thread bearophileHUGS
They have used a lot of time and money to find bugs in Python too:
http://www.theregister.co.uk/2006/03/03/open_source_safety_report/print.html

0.32 defects per 1,000 lines of code in LAMP, it says.
I hope they will show such Python bugs, so Python developers can try to
remove them. From the bottom of the article:

>Coverity said it would now engage with open source developers to improve code, 
>and identify potential reasons for why some projects have more bugs than 
>others.<

Bye,
bearophile

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


Re: How to except the unexpected?

2006-03-04 Thread Alex Martelli
James Stroud <[EMAIL PROTECTED]> wrote:

> > Reraise = (LookupError, ArithmeticError, AssertionError) # And then some
> > 
> > try:
> > process_things()
> > except Reraise:
> > raise
> > except:
> > log_error()
> > 
> 
> Why catch an error only to re-raise it?

To avoid the following handler[s] -- a pretty common idiom.


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


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Paul Rubin
"Tuvas" <[EMAIL PROTECTED]> writes:
> I have made and recently posted a libary I made to do Modular
> Arithmetic and Prime numbers on my website  at
> http://www.geocities.com/brp13/Python/index.html . I am currently in a
> crypotology class, and am working on building a RSA public key
> cryptology system for a class project. I am building the librarys just
> to get the experience to do so.

I'm looking at 
  http://www.geocities.com/brp13/Python/prime3.html

You do something for x in range(10) but you don't use x in the loop.

I'll guess you actually intended to pick some random number n and find
the closest prime p >= n.  That's not a good strategy: imagine you pick
a random number n in the range 1..50.  Let's say n is 14.  14 isn't
prime, so you check 15, 16, and 17.  17 is prime so you return p = 17.
You also return 17 if n is 15, 16, or 17.  So the chance of your
returning p = 17 is 4/50.

What is your chance of returning p = 19?  It means n has to be 18 or
19, so the chance is only 2/50.  That's not good--you want all primes
to be equally likely.

Anyway, the simplest approach is:

1) get random numbers by reading characters from os.urandom() and
converting them to integers.  Don't use randint which makes no attempt
at cryptographic security.

2) For each random integer (you can set the low bit to make sure it is
odd), test against some small prime divisors p (say the primes up to
1000) as a fast way to throw away some composites.  If n%p == 0 for
any p, throw away n and go back to step 1.

3) If you get an n with no small divisors, do the (slow) Miller-Rabin
test.  If it passes, you're done; if it fails, go back to step 1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: add an asynchronous exception class

2006-03-04 Thread Paul Rubin
"Christian Stapfer" <[EMAIL PROTECTED]> writes:
> I guess it means the following:
> 
> "Terminating exceptions" are exceptions that
> terminate the *thrower* of the exception.

Are you sure?  I didn't read it that way.  I'm not aware of there ever
having been a detailed proposal for resumable exceptions in Python,
though the gurus would know better than I do whether there's been one.

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


Re: The old round off problem?

2006-03-04 Thread Paul Rubin
"sam" <[EMAIL PROTECTED]> writes:
> Hello all, I am taking a class in scientific programming at the local
> college. My problem is that the following difference produces round off
> errors as the value of x increases. For x >= 19 the diference goes to
> zero.I understand the problem, but am curious as to whether their
> exists a solution.   [f(x)  = cosh^2(x) - sinh^2(x)  = 1]

The usual way is to notice that the difference goes to zero because
the lowest order terms of the Taylor series for cosh^2 and sinh^2 are
equal and cancel each other out.  The solution is to write down the
series for (cosh^2(x) - sinh^2(x)) and add up a few non-cancelled terms.
All these series should converge very fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> > try:
> > process_things()
> > except Reraise:
> > raise
> > except:
> > log_error()
> >
> 
> Why catch an error only to re-raise it?
> 
> This falls under http://c2.com/cgi/wiki?YouReallyArentGonnaNeedThis

No, without the reraise, the bare "except:" clause would capture the
exception incorrectly and log it as an error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread James Stroud
Rene Pijlman wrote:
> James Stroud:
> 
>>Which suggests that "try: except HTTPException:" will be specific enough 
>>as a catchall for this module.
>>
>>The following, then, should catch everything you mentioned except the 
>>socket timeout:
> 
> 
> Your conclusion may be (almost) right in this case. I just don't like this
> approach. Basically this is reverse engineering the interface from the
> source at the time of writing the app.

This is using the source as documentation, there is no law against that. 
It's better than waiting for a closed source software mogul to 
benevolently give you the API documentation, which may not be 100% 
accurate itself.

> Even if you get it right, it may
> fail next week when someone added an exception to a module.

Given how all of the exceptions raised by both modules are either (1) 
builtin or (2) defined in the module itself and given that all 
exceptions defined in these modules inheret from a single class, my 
money is on the fact that this approach should be forward compatible.

> 
>>But it seems to me that working with the internet as you are doing is 
>>fraught with peril anyway.
> 
> Why? It shouldn't be.
> 

How things are and how things should be have always been 2 entirely 
different things. See early books by Robert J. Ringer for a more 
complete discussion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spliting on ":"

2006-03-04 Thread Peter Hansen
Cyril Bazin wrote:
> Your file looks like a list of IP adresses.
> You can use the urllib and urllib2 modules to parse IP adresses.
> 
> import urllib2
> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport(line)
> print (port != None) and '' or port

Is this what you want to happen when port is None?

 >>> port = None
 >>> print (port != None) and '' or port
None


I think you're getting caught by the classic and/or trap in Python, 
trying to avoid using a simple if statement.

By the way, equality comparison with None is generally a bad idea as 
well, so even if the above worked it should be (port is not None) rather 
than (port != None).

-Peter

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


Re: The old round off problem?

2006-03-04 Thread David Treadwell
On Mar 4, 2006, at 4:33 PM, Paul Rubin wrote:

> "sam" <[EMAIL PROTECTED]> writes:
>> Hello all, I am taking a class in scientific programming at the local
>> college. My problem is that the following difference produces  
>> round off
>> errors as the value of x increases. For x >= 19 the diference goes to
>> zero.I understand the problem, but am curious as to whether their
>> exists a solution.   [f(x)  = cosh^2(x) - sinh^2(x)  = 1]
>
> The usual way is to notice that the difference goes to zero because
> the lowest order terms of the Taylor series for cosh^2 and sinh^2 are
> equal and cancel each other out.  The solution is to write down the
> series for (cosh^2(x) - sinh^2(x)) and add up a few non-cancelled  
> terms.
> All these series should converge very fast.

Here's my analysis:

First, keep in mind that the range of values for a Taylor expansion  
of sinh() and cosh() is limited. Then...

Write down the series for (cosh^2(x) - sinh^2(x)), as Paul suggested.

c2 = taylor(cosh(x)^2,x,8)

s2 = taylor(sinh(x)^2,x,8)

The first method gives the expected answer:

eval(c2-s2) ==> 1

Write down the series for cosh(x), square that; write the series for  
sinh(x), square that and subtract.

Compare the two (I just did this in Eigenmath). Higher-order terms  
remain for the second method.. I don't know how many terms my cosh()  
and sinh() functions use, but if I evaluate (again, in Eigenmath)

The second method, which is more akin to what Python is doing (unless  
there is an explicit 'sinh**2(x)' function) is different.

c2 = (taylor(cosh(x),x,8))^2, which gives terms up to and including  
(x**8)**2 = x**16

s2 = (taylor(sinh(x),x,9))^2, which gives terms up to and including  
x**18, then subtract the two, the result is

eval(c2 - s2) ==> 1 - 1/1814400 * x**10 - ... higher terms.

This begs the question, "What is the algorithm used by my Python?"

And, the ever-important question, "Does it matter in my final  
result?" This is important, because I do not, in general, trust the  
result when subtracting two large numbers.

:--David T.


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


Advice from distutils experts?

2006-03-04 Thread olsongt
I'm doing something a little wierd in one of my projects.  I'm
generating a C source file based on information extracted from python's
header files.  Although I can just generate the file and check the
result into source control, I'd rather have the file generated during
the install process instead of doing it manually.

So I'd like to:
+ have the file generated when a unix user runs setup.py install.
+ have the file generated when I create a windows binary
distribution.
+ not have the file generated when I create source distribution
.tgz's and .zip's.

I'd appreciate any pointers on the best way to hook into disutils to do
this.  And if the answer is "Your crazy, generate the file outside of
distutils." just let me know.

-Grant

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


Re: Papers on Dynamic Languages

2006-03-04 Thread Paul Boddie
Jay Parlar wrote:
>
> Anyway, I want to talk about things like typing disciplines (weak,
> strong, etc.),"class vs. prototype, JIT technologies in dynamic
> languages, interactive interpreters, etc.

There are a few classic papers on a number of these topics, but I'll
leave it to the papers mentioned below to provide references.

> I've got Brett Cannon's thesis already, but I'm looking for references
> to some more papers on these topics. A Python basis for any of the
> papers would be preferred, but anything will do.
>
> Any suggestions? This is my first real research paper in grad school,
> so I'm starting out from scratch here.

I'd have a look at the following Python-related papers:

Michael Salib's Starkiller paper (and presentation):
http://www.python.org/pycon/dc2004/papers/1/

Mark Dufour's ShedSkin paper:
http://kascade.org/optimizing_python.pdf

John Aycock's "Aggressive Type Inference" paper:
http://www.python.org/workshops/2000-01/proceedings/papers/aycock/aycock.html

I also provided a fair number of references in the following thread:

http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/cc98317bdf96efda

I hope this is of use!

Paul

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


Re: How to except the unexpected?

2006-03-04 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> > approach. Basically this is reverse engineering the interface from the
> > source at the time of writing the app.
> 
> This is using the source as documentation, there is no law against
> that.

That's completely bogus.  Undocumented interfaces in the library
source are allowed to change between Python versions and across Python
implementations.  If you write your application according to the
documented interfaces in the Python manual, it should not break when
someone upgrades to the next Python release.  You should not have to
depend on undocumented aspects of the Python implementation which
change out of sync with the application.

> How things are and how things should be have always been 2 entirely
> different things. See early books by Robert J. Ringer for a more
> complete discussion.

That's like saying programs shouldn't have bugs, but they often do
anyway.  It doesn't mean the bugs are a good thing or that they
shouldn't be fixed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spliting on ":"

2006-03-04 Thread Cyril Bazin
Ok, ok, there was a mistake in the code. (Of course, it was done on prupose in order to verify if everybody is aware ;-)I don't know why it is preferable to compare an object to the object "None" using "is not".
"==" is, IMHO, more simple. Simple is better than complex. So I use "==". The correct program is:import urllib2for line in open("fileName.txt"):    addr, port  = urllib2.splitport
(line)
    print (port == None) and '' or portor import urllib2
for line in open("fileName.txt"):
    addr, port  = urllib2.splitport(line)

    if port == None:    print ''     else:    print port
On 3/4/06, Peter Hansen <[EMAIL PROTECTED]> wrote:
Cyril Bazin wrote:> Your file looks like a list of IP adresses.> You can use the urllib and urllib2 modules to parse IP adresses.>> import urllib2> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport(line)> print (port != None) and '' or portIs this what you want to happen when port is None? >>> port = None >>> print (port != None) and '' or port
NoneI think you're getting caught by the classic and/or trap in Python,trying to avoid using a simple if statement.By the way, equality comparison with None is generally a bad idea aswell, so even if the above worked it should be (port is not None) rather
than (port != None).-Peter--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: spliting on ":"

2006-03-04 Thread Petr Jakes
> I think you're getting caught by the classic and/or trap in Python,
> trying to avoid using a simple if statement.

What do you mean by "the classic and/or trap"? Can you give an example
please?

Petr Jakes

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


CallBack

2006-03-04 Thread Ramkumar Nagabhushanam
Hello All,
I am trying to integrate the ftpclient (in ftplib) with an application that
has been written I C/C++.
I am able to delete,send change working directories etc. When I receive data
back from the server i.e. Retrieve files, get a directory listing) I want to
pass a callback function to the ftpclient so that the output does not get
displayed on stdout. The code I have written is as shown below. Can anyone
out there give me advise on how to write "c_function" that is called in
ftpTest::DoesFileExist ?Any help will be most appreciated. The code runs
under windows and is compiled with VC++ 6.0. THe code is as shown below.
Regards,
Ram
 
>>> CODE START >>>
// test.cpp : Defines the entry point for the console application.
//
#include 
#include 
#include 
#include 
#include 
#include "C:\Python24\include\Python.h"
 
Class ftpTest
{
Private:
 PyObject *_FTP;
 PyObject *_callBack;
 
Public:
 FtpTest (const char * ipAddress, const char * username, const char *
password); // Open the FTP connection, Initialize python interpreter
 ~ftpTest (); // Close connection and finalize python interpreter
 Int Close ();
 Int GetFile (const char * fileName);
 Int PutFile (const char * fileName);
 Int ChangeDir (const char * dirName);
 Int DoesFileExist (const char * fileName);
 Int DeleteFile (const char * fileName);
 Int ChangePermissions (const char * fileName, const char * permissions);
};
 
FtpTest::ftpTest (const char * ipAddress, const char * username, const char
* password)
{
 PyObject *modname, *mod, *func, *mdict, *pArgs, *pValue;
 
 // Initialize the python interpreter
 Py_Initialize();
 
 Modname = PyString_FromString("ftplib");
 
 If (modname == NULL)
 {
  // Log an error
 }
 Else
 {
  Mod = PyImport_Import (modname);
 }
 
 If (mod)
 {
  Mdict = PyModule_GetDict (mod);
  Func = PyDict_GetItemString (mdict, "FTP");
  If (func)
  {
   Printf ("I am here -- 1\n");
  }
 
  Const char *arguments[] = {ipAddress, username, password};
 
  PArgs = PyTuple_New (3);
For (int I = 0; I < 3; ++I) 
  {
PValue = PyString_FromString(arguments[I]);
If (!pValue) 
   {
Py_DECREF(pArgs);
Py_DECREF(mod);
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, I, pValue);
}
 
  _FTP = PyObject_CallObject (func, pArgs);
 
  If (_FTP != NULL)
  {
   Printf ("I am here -- 2\n");
  }
 }
}
 
FtpTest::~ftpTest ()
{
 //Py_Finalize();
}
 
Int ftpTest::Close ()
{
 Return (1);
}
 
Int ftpTest::ChangeDir (const char * dirName)
{
 PyObject *t = PyObject_CallMethod (_FTP, "cwd", "(S)", dirName);
 Return (1);
}
 
Int ftpTest::DeleteFile (const char * fileName)
{
 PyObject *t = PyObject_CallMethod (_FTP, "delete", "(S)", fileName);
 Return (1);
}
 
Int ftpTest::PutFile (const char * fileName)
{
 PyObject * py_file = PyFile_FromString ((char *)fileName, "rb"); 
 Std::string S("STOR ");
 s += fileName;
 PyObject * t = PyObject_CallMethod (_FTP, "storlines", "(sO)", S.c_str(),
py_file);
 Return (1);
}
 
Int ftpTest::ChangePermissions (const char * fileName, const char *
permissions)
{
 Std::string S("SITE");
 s += " chmod ";
 s += permissions;
 s += " ";
 s += fileName;
 PyObject * t = PyObject_CallMethod (_FTP, "sendcmd", "(S)", S.c_str());
 Return (1);
}
 
Int ftpTest::GetFile (const char * fileName)
{
// TODO: Implement callback
#if 0
 PyObject *t = PyObject_CallMethod (_FTP, "retrlines", "(S)", "RETR ram.txt
);
#endif
 Return (1);
}
 
PyObject * c_function(char * data)
{
 // Process the data received in "data"
 Return (NULL);
}
 
Int ftpTest::DoesFileExist (const char * fileName)
{
 // Just get the list
 PyObject *t = PyObject_CallMethod (_FTP, "retrlines", "(sO)", "LIST",
c_function);
 If (t == NULL)
 {
  Printf ("I am here -- 4\n");
 }
 Return (1);
}
 
Int main ()
{
 FtpTest ftpClient("127.0.0.1", "xxx", "");
 FtpClient.DoesFileExist(NULL);
 Return (1);
}

>>> CODE END >
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random Prime Generator/Modular Arithmetic

2006-03-04 Thread Tuvas
Okay, I don't know if your farmiliar with the miller-rabin primality
test, but it's what's called a probabalistic test. Meaning that trying
it out once can give fake results. For instance, if you use the number
31 to test if 561 is prime, you will see the results say that it isn't.
Mathematically, the most possible wrong answers is 1/4th of the
numbers. Thus, one should try at least 10 times (A very standard value)
in order to ensure that the number is not a psuedoprime, but indeed a
real prime number. That was the intent of the loop of 10 without using
the number.

If this test fails, it will chose another random number to test.

I could easily test with several small numbers, at least primes up to
20 would greatly reduce the number of miller-rabin tests to perform,
and would speed up the process considerably. Might as well toss it in.

Thanks for the tip on the urandom. I knew there had to be a better
random number generator somewhere. I saw lots of stuff for os specific,
but I'm trying to develop this as os independent.

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


Re: How to except the unexpected?

2006-03-04 Thread James Stroud
Paul Rubin wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
> 
>>>approach. Basically this is reverse engineering the interface from the
>>>source at the time of writing the app.
>>
>>This is using the source as documentation, there is no law against
>>that.
> 
> That's completely bogus.  Undocumented interfaces in the library
> source are allowed to change between Python versions and across Python
> implementations.  If you write your application according to the
> documented interfaces in the Python manual, it should not break when
> someone upgrades to the next Python release.  You should not have to
> depend on undocumented aspects of the Python implementation which
> change out of sync with the application.
> 

My suggestion was to use some common sense about the source code and 
apply it. I've wasted many hours programming to faulty documentation 
when a quick peek at the source code would have saved some serious time. 
   How do you think I happened accross the technique?

I would wager that, in 10 years time, the urllib2 module will not raise 
any exceptions that don't inheret from urllib2.URLError or a built-in 
(i.e. documented) exception; unless, of course, someone made a change in 
a deliberate attempt to win said wager ;o)

>>How things are and how things should be have always been 2 entirely
>>different things. See early books by Robert J. Ringer for a more
>>complete discussion.
> 
> That's like saying programs shouldn't have bugs, but they often do
> anyway.  It doesn't mean the bugs are a good thing or that they
> shouldn't be fixed.

The original reference was to the internet, which seems vast in its 
sources of unforseen peril. If some gracious soul aspires to fix every 
bug in the internet, I invite him to be my guest.

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


Re: Advice from distutils experts?

2006-03-04 Thread Robert Kern
[EMAIL PROTECTED] wrote:
> I'm doing something a little wierd in one of my projects.  I'm
> generating a C source file based on information extracted from python's
> header files.  Although I can just generate the file and check the
> result into source control, I'd rather have the file generated during
> the install process instead of doing it manually.
> 
> So I'd like to:
> + have the file generated when a unix user runs setup.py install.
> + have the file generated when I create a windows binary
> distribution.
> + not have the file generated when I create source distribution
> .tgz's and .zip's.
> 
> I'd appreciate any pointers on the best way to hook into disutils to do
> this.  And if the answer is "Your crazy, generate the file outside of
> distutils." just let me know.

We do things like this in numpy. We've extended distutils to allow functions in
the sources list for Extension.

from numpy.distutils.core import Extension
from distutils.dep_util import newer

def generate_source_c(ext, build_dir):
target = os.path.join(build_dir, 'source.c')
if newer(__file__, target):
# ... parse Python headers
contents = """
#include "Python.h"
/* ... */
""" % (stuff, more_stuff)
f = open(target, 'w')
f.write(contents)
f.close()
return target

ext = Extension('my_extension',
sources=[generate_source_c],
)

setup(#...
ext_modules=[ext]
)

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: How to except the unexpected?

2006-03-04 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> My suggestion was to use some common sense about the source code and
> apply it.

The common sense to apply is that if the source code says one thing
and the documentation says another, then one of them is wrong and
should be updated.  Usually it's the source code that's wrong, but in
either case, saying to ignore the documentation and follow the code,
rather than repairing the discrepancy somehow, is poor advice.

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


Re: Suggestions for documentation generation?

2006-03-04 Thread Bo Peng
kpd wrote:
> Hello,
> 
> I have written a C++ library that I've then wrapped with Pyrex.
> Any suggestions to the best-in-class tool to create documentation for
> the libraries?
> 
> I would love to document things in one spot (could be the code) and
> generate html and PDF from there.
> 
> Doxygen (www.doxygen.org) looks to be about the best so far. 
> 
>

I was facing the same problem and took the following approach:

1. write c++ code with doxygen-complaint comments
2. generate XML comments using doxygen
3. parse XML and generate Python docstring
4. insert the docstring into SWIG interface file

I can send you the parser but I do not know if pyrex support python 
docstring.

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


Cryptographically random numbers

2006-03-04 Thread Tuvas
Okay, I'm working on devoloping a simple, cryptographically secure
number, from a range of numbers (As one might do for finding large
numbers, to test if they are prime). My function looks like this:

def cran_rand(min,max):
if(min>max):
x=max
max=min
min=x
range=round(log(max-min)/log(256))
if range==0:
range=1
num=max+1
while(num>max):
num=min+s2num(urandom(range))
return num

Any comments on this? I think it should hold up to a test, it seems to
work alright. Thanks!

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


Passing a method indirectly

2006-03-04 Thread swisscheese
I'm trying to write a function that takes an arbitrary object and
method.
The function applies the method to the object (and some other stuff).
I get error "Test instance has no attribute 'method' "
How can I make this work?

def ObjApply (object,method):
object.method ()

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply (self,self.test1)

ta = Test ()
ta.test2 ()

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


Re: Passing a method indirectly

2006-03-04 Thread André

swisscheese wrote:
> I'm trying to write a function that takes an arbitrary object and
> method.
> The function applies the method to the object (and some other stuff).
> I get error "Test instance has no attribute 'method' "
> How can I make this work?
>
> def ObjApply (object,method):
>   object.method ()
>
> class Test:
>   def test1 (self): print "Hello"
>   def test2 (self):
>   ObjApply (self,self.test1)
>
> ta = Test ()
> ta.test2 ()

You need to add one line (2nd one below).

def ObjApply (object, method):
object.method = method
object.method()

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply (self, self.test1)

ta = Test ()
ta.test2 ()

André

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


Re: Passing a method indirectly

2006-03-04 Thread Farshid Lashkari
You don't need to pass the object along with the method. The method is 
bound to the object. Simply call the method by itself:

def ObjApply(method):
method()

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply(self.test1)

ta = Test ()
ta.test2 ()

If you wanted to pass an unbound method, then it would look like the 
following:

def ObjApply(object,method):
method(object)

class Test:
def test1 (self): print "Hello"
def test2 (self):
ObjApply(self,Test.test1)

ta = Test ()
ta.test2 ()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spliting on ":"

2006-03-04 Thread Peter Hansen
Cyril Bazin wrote:
> Ok, ok, there was a mistake in the code.
> (Of course, it was done on prupose in order to verify if everybody is 
> aware ;-)
> I don't know why it is preferable to compare an object to the object 
> "None" using "is not".
> "==" is, IMHO, more simple. Simple is better than complex.. So I use "==".

The archives could tell you more, but basically on is usually interested 
in *identity* with a singleton object (None), not in whether the object 
on is examining happens to compare equal.  A custom object could be 
designed to compare equal to None in certain cases, even though it *is 
not* None, leading to the "== None" approach being defective code.

In the specific code in question, it won't make any differences, but I 
pointed it out to help folks who don't know this to start developing the 
safer habit, which is always to use "is" and "is not" with None (or, 
generally, with other singletons).

> The correct program is:
> 
> import urllib2
> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport (line)
> print (port == None) and '' or port

Nope, sorry... the point is that the "and/or" pseudo-ternary operator is 
inherently flawed if the operand after "and" evaluates False.  Check 
this out:

 >>> port = None
 >>> print (port == None) and '' or port
None
 >>> print (port != None) and '' or port
None

and even:

 >>> print (port is None) and '' or port
None

So the bug isn't in using "!=" instead of "==", or using equality 
instead of identity comparison, it is in trying to use the and/or 
expression for a purpose it wasn't intended for.

> or
> 
> import urllib2
> for line in open("fileName.txt"):
> addr, port  = urllib2.splitport(line)
> if port == None:
> print ''
> else:
> print port

That should work nicely... and it's more readable too!

Note that in Python 2.5 you should be able to write this as

 print '' if port is None else port
or  print '' if (port is None) else port

but it's quite arguable whether that is better than the simple if/else 
statement in this case.

-Peter

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


Re: spliting on ":"

2006-03-04 Thread Peter Hansen
Petr Jakes wrote:
>>I think you're getting caught by the classic and/or trap in Python,
>>trying to avoid using a simple if statement.
> 
> What do you mean by "the classic and/or trap"? Can you give an example
> please?

Sure, see my subsequent reply to Cyril, elsewhere in this thread.

(In summary, and/or is defective when used as a ternary operator if the 
expression after "and" evaluates False.  The list archives can tell you 
more.)

-Peter

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


  1   2   >