Re: numpy or _numpy or Numeric?

2007-01-24 Thread George Sakkis
On Jan 24, 2:24 am, auditory <[EMAIL PROTECTED]> wrote:

> I am a newbie here
>
> I am trying to read "space separated floating point data" from file
>
> I read about csv module by searching this group,
> but I couldn't read space separated values with csv.
> (which may be matter of course..)
>
> I also read about numpy.fromfile(file, sep=' ') which i can use.
> but on my machine(ubuntu linux) numpy is unknown module,
> which I didn't install by myself.
>
> While trying to install numpy accroding to its homepage.
> (http://numpy.scipy.org/numpydoc/numdoc.htm).
> i am quite confused.
>
> it's talking about the Numerical Python,
> and it says to test whether it is installed or not,
> try import Numeric instead of numpy.
>
> I got Nurmeric modules and
> as a matter of fact i got a file named '_numpy.so' in lib directory.
>
> I can import _numpy but _numpy does not have 'fromfile' method
>
> My question is:
> 1. Do i need to install numpy module?
> 2. Then Is it different from Numeric module?
> 3. Then where can i get it?
>
> 4. Or what is general way to read 'space separated values' from file?
>
> Thanks in advance.

If *all* you need is to read a space-separated file with floating point
values, installing numpy (or Numeric or numarray..) is an overkill; you
can do it in one line in pure Python:

matrix = [map(float, line.split()) for line in
open('my_space_separated_file.txt')]

This stores the values as a list of lists, each list corresponding to a
row in the file. Depending on what you plan to do next with these
numbers, this may or may not be the best way to go about it, but since
you only mentioned the file reading part, we can't assume much.

George

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


Re: How to use dynamic properties? <-- Noob

2007-01-24 Thread Sean Schertell
Yep, that was it. Thanks Gary :-)

Sean



On Jan 23, 2007, at 5:05 PM, Gary Herron wrote:

> Sean Schertell wrote:
>> person.name = 'Joe'
>> person.age = 20
>> person.sex = 'm'
>>
>> info_I_need = name
>>
>> print person.info_I_need
>>
>> # How can I make it print 'Joe' ?
>>
>>
>> Sean
>>
>>
>>   DataFly.Net  
>> Complete Web Services
>> http://www.datafly.net
>>
>>
> Like this:
>
>info_I_need = 'name'
>
>print getattr(person, info_I_need)
>
> Related to getattr are setattr and hasattr.
> Gary Herron
>
>
>
>

  DataFly.Net  
Complete Web Services
http://www.datafly.net

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


Re: numpy or _numpy or Numeric?

2007-01-24 Thread auditory
George Sakkis ? ?:
> On Jan 24, 2:24 am, auditory <[EMAIL PROTECTED]> wrote:
> 
>> I am a newbie here
>>
>> I am trying to read "space separated floating point data" from file
>>
>> I read about csv module by searching this group,
>> but I couldn't read space separated values with csv.
>> (which may be matter of course..)
>>
>> I also read about numpy.fromfile(file, sep=' ') which i can use.
>> but on my machine(ubuntu linux) numpy is unknown module,
>> which I didn't install by myself.
>>
>> While trying to install numpy accroding to its homepage.
>> (http://numpy.scipy.org/numpydoc/numdoc.htm).
>> i am quite confused.
>>
>> it's talking about the Numerical Python,
>> and it says to test whether it is installed or not,
>> try import Numeric instead of numpy.
>>
>> I got Nurmeric modules and
>> as a matter of fact i got a file named '_numpy.so' in lib directory.
>>
>> I can import _numpy but _numpy does not have 'fromfile' method
>>
>> My question is:
>> 1. Do i need to install numpy module?
>> 2. Then Is it different from Numeric module?
>> 3. Then where can i get it?
>>
>> 4. Or what is general way to read 'space separated values' from file?
>>
>> Thanks in advance.
> 
> If *all* you need is to read a space-separated file with floating point
> values, installing numpy (or Numeric or numarray..) is an overkill; you
> can do it in one line in pure Python:
> 
> matrix = [map(float, line.split()) for line in
> open('my_space_separated_file.txt')]
> 
> This stores the values as a list of lists, each list corresponding to a
> row in the file. Depending on what you plan to do next with these
> numbers, this may or may not be the best way to go about it, but since
> you only mentioned the file reading part, we can't assume much.
> 
> George
> 
Thanks a lot for your 'elegant' suggestion.
As a next step i wish to do some math with matrix and produce a vector
and write it on a file. (in fact math is just averaging now)

I hope i can do this with a little more efforts.

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


sys.path issue in cygwin

2007-01-24 Thread Wang Shuhao


I successfully built and installed Python 2.2.3 in cygwin. But there is 
something wrong in the sys.path. I use following statments for a test.

>>> import sys
>>> print sys.path
['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', 'C/lib/python2.2/lib-tk'
, '\\Python24/lib/python2.2/lib-dynload']
>>>

To keep the question simple, I've set PATH= in cygwin.bat to avoid python 
initialze sys.path from Windows' PATH environment.

Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is installed 
in /usr/local/lib/python2.2.3. The result of the issue is that when you run a 
program python can't find the module. So what I really want to know is where 
these path came from and how to fix it.

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

Re: numpy or _numpy or Numeric?

2007-01-24 Thread auditory
Travis E. Oliphant ? ?:
> auditory wrote:
>> I am a newbie here
>>
>> I am trying to read "space separated floating point data" from file
>>
>> I read about csv module by searching this group,
>> but I couldn't read space separated values with csv.
>> (which may be matter of course..)
>>
>> I also read about numpy.fromfile(file, sep=' ') which i can use.
>> but on my machine(ubuntu linux) numpy is unknown module,
>> which I didn't install by myself.
> 
> You will need to install NumPy.
> 
>>
>> While trying to install numpy accroding to its homepage.
>> (http://numpy.scipy.org/numpydoc/numdoc.htm).
>> i am quite confused.
> 
> You are reading old documentation for Numeric and so any installation 
> description is how to install the Numeric module (not its newer 
> replacement which is called NumPy).
> 
> 
> So:
> 
> 1) Yes, you need NumPy
> 2) This *is different* from Numeric
> 3) You get it by either installing a pre-built package for your system 
> or by
> 
>a) downloading the source tar-file from 
> http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 
> 
>  (get the numpy-.tar.gz file
>b) tar zxvf numpy-.tar.gz
>c) cd numpy-
>d) sudo python setup.py install
> 
>e) If you want to link against high-performance libraries on your 
> system, then either put them in standard locations or edit the site.cfg 
> file appropriately (Optional).
> 
>>
>> 4. Or what is general way to read 'space separated values' from file?
> 
> You can easily read space-separated values from a file by reading in a 
> line at a time and using the split method of strings:
> 
> fid = open('filename')
> linedata = fid.readlines()
> new = [[float(x) for x in line.split()] for line in linedata]
> 
> new will be a nested sequence of floats.  You can convert it to an array 
> (if you want to do math on it) using
> 
> anew = numpy.array(new)
> 
> -Travis
> 
Thank you for quick answer..

I found the above website from googling with "numpy" keyword,
and supprised at that the top matching page is old one.

In addition to your method and below one,
I found csv moudule can do this with "delimiter" paramter.
I made mistake not to read manual first.
My apology on that.
-- 
http://mail.python.org/mailman/listinfo/python-list


sys.path issue in cygwin

2007-01-24 Thread Wang Shuhao
I successfully built and installed Python 2.2.3 in cygwin. But there is 
something wrong in the sys.path. I use following statments for a test.

>>> import sys
>>> print sys.path
['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', 'C/lib/python2.2/lib-tk'
, '\\Python24/lib/python2.2/lib-dynload']
>>>

To keep the question simple, I've set PATH= in cygwin.bat to avoid python 
initialze sys.path from Windows' PATH environment.

Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is installed 
in /usr/local/lib/python2.2.3. The result of the issue is that when you run a 
program python can't find the module. So what I really want to know is where 
these path came from and how to fix it.

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

Re: Getting to an SSH account over a HTTP proxy

2007-01-24 Thread amadain
use pexpect to set the prompt after the login.

class Login(General):
"""Class spawning an ssh expect instance"""
def __init__(self, user, host, pwd, cfg_name=None, log=None):
if cfg_name:
self.testcell = test_config(cfg_name)
self.spawn = pexpect.spawn("ssh [EMAIL PROTECTED]" % (user, 
host), [], 100)
if log:
self.spawn.logfile = log
sshreply = self.spawn.expect(["Last login", "assword", 
"connecting"])

if sshreply == 1:
self.spawn.sendline(pwd)
self.spawn.expect("Last login")
elif sshreply == 2:
time.sleep(0.1)
self.spawn.sendline("yes")
print self.spawn.after
Login(user, host, cfg_name, log)
time.sleep(1)
self.prompt=prompt_chg(self.spawn, "PROMPT:")
self.spawn.sendline("uname -a")
self.spawn.expect(self.prompt)


On Jan 23, 10:28 am, Willi Richert <[EMAIL PROTECTED]> wrote:
> Am Dienstag, 23. Januar 2007 02:16 schrieb Nanjundi:
>
>
>
> > BJörn Lindqvist wrote:
> > > I want to use Python to connect to a SSH account over a HTTP proxy to
> > > automate some operations. I thought paramiko would be able to do that,
> > > but it can not (it seems).
>
> > > Is there some other Python module that can do what I want?
>
> > > --
> > > mvh Björn
>
> > Did you take a look at twisted library?
> > twistedmatrix.com
> >http://twistedmatrix.com/projects/core/documentation/howto/clients.html
>
> > I haven't tried to connect over port 80, but its worth a try.
>
> > -NIf you need it for automation you might want to 
> > usepexpect:http://pexpect.sourceforge.net/
>
> It listens to the tty-stream and simulates a user typing in commands. It is
> very useful, e.g. if you want to start processes on many machines over ssh.
> If there are gateways/firewalls between - no problem just use a
> second "sendline('ssh [EMAIL PROTECTED]')"
>
> The only problem is the regular expression: If e.g. you use a custom $PS1
> variable for your prompt you have to account for that.
> 
> Regards,
> wr

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


[OT]Could anyone send me a copy of "timeout sockets for jython"

2007-01-24 Thread Slowness Chen
The information about this module:
http://www.xhaus.com/alan/python/timeout.html

I can't access the download url due to the severe network issue these
days, and I need to use this module for work.
Could anyone do me a favor to send a copy? the download url :

http://cvs.sourceforge.net/viewcvs.py/jython/jython/Lib/socket.py?rev=1.16&view=log

Thanks.

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

Re: Overloading assignment operator

2007-01-24 Thread John Pye
Hi thre,

On Jan 24, 5:24 am, Achim Domma <[EMAIL PROTECTED]> wrote:
> I want to use Python to script some formulas in my application.

Depending on what you're trying to do, you might possibly find it
useful to lake a look at the approach used by PyGINAC, which is a
symbolic algebra system (in C++) wrapped with some clever python
bindings:

http://pyginac.sourceforge.net/

Hope that helps,
JP

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Laurent Rahuel
Hi,

I known this can be impossible but what about an "HTML" GUI ?

Daniel Jonsson wrote:

> So, I've reached the point where my building pipeline tools actually
> needs to be used by other people in my company. By this reason I
> actually need to think about the usability, and I've come to the
> conclusion that I need a GUI. So, which of the two packages should I
> learn, and which one is easier to pick up?
> Thanks in advance!
> 
> Daniel

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


Q: Why Python is bad for web from the point of URLs?

2007-01-24 Thread techtonik
A: Because you need three modules to parse, edit and reassemble query
string. urlparse, cgi and urllib

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


Re: smtplib starttls gmail example - comments?

2007-01-24 Thread Tim Williams
On 24/01/07, py <[EMAIL PROTECTED]> wrote:
> I would love for anybody to comment on this code with regard to 
> redundancy/efficiency/wordiness or whatever else.
> for instance, do i understand correctly that i cant have a try: else: without 
> an intervening except:?
> -dave
>
> stdout.write("calling smtp server...")
> try:
> server = SMTP(msgsmtp)
> except:
> stdout.write("FAIL.")   #using .write to avoid the implied \n 
> with print
> else:
> server.set_debuglevel(msgdebug)
> stdout.write("starting tls...")
> server.ehlo(msgfrom)
> try:server.starttls()
> except: stdout.write("FAIL.")
> else:
> server.ehlo(msgfrom)   #neessary duplication (?)
> stdout.write("logging in...")
> try:server.login(msgfrom, msgpass)
> except: stdout.write("FAIL.")
> else:
> stdout.write("sending...")
> try:server.sendmail(msgfrom, msgto, msgtxt + "\n.\n")
> except: stdout.write("FAIL.")
> else:
> try:
> server.quit()
> except sslerror:  # a known and largely ignored 
> issue with early EOF in ssl protocol
> stdout.write("success.")
> else:
> stdout.write("success.")
> --


*** Not tested  but should have the same functionality and error
handling as your script ***

this_host = 'myhostname.mydom1.com'
print "calling smtp server...", #  the trailing comma removes '\n'
try:
server = smtplib.SMTP(msgsmtp,local_hostname=this_host)
server.set_debuglevel(msgdebug)
print "starting tls...",
server.starttls()
server.ehlo(this_host)  # RFC requirement for 2nd EHLO after requesting TLS
print "logging in...",
server.login(msgfrom, msgpass)
print "sending...",
failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n")
try:
server.quit()
except: pass
print "success."
except:
print "FAIL.",

if failed:
print "failed:", failed  # some recipients, but not all of them, failed
-- 
http://mail.python.org/mailman/listinfo/python-list


use of a GChildWatch source

2007-01-24 Thread awalter1
Hello

I am using python, pyGTK and GTK+ on HPUX (unix)
In this context, the pygtk documentation about gobject.spawn_async says
: ... you must use a GChildWatch source to be notified about the death
of the child process ...
Does someone know where to find details about GChildWatch ? I didn't
retrieve any thing on the net.
In addition, does someone be aware about some limitations concerning
subprocesses creation in a python/GTK application
Thanks a lot

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


Pydev 1.2.6 Released

2007-01-24 Thread Fabio Zadrozny

Hi All,

Pydev and Pydev Extensions 1.2.6 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

*  Added refactoring support for rename (still BETA, so, don't forget to
review your changes before applying them)
 - Keybinding: Alt+Shift+R
 - Supports preview
 - Integrated in the editor (but not in the package explorer, so, it
can rename a module, but only through an import to that module)
 - Supports undo/redo in the workspace
 - Rename class
 - Rename method
 - Rename attribute
 - Rename imports
 - Rename local variable
* Menu changes:
 - Now the debug/navigate actions are all under a 'Pydev' menu
 - The pydev navigate action is now only initially shown in the
pydev/debug perspective
 - The pydev remote debugging actions are now only initially shown in
the debug perspective
* Fix: code analysis problem when working with nested list-comprehensions
* Fix: go to definition sometimes failed to find module definitions


Release Highlights in Pydev:
--

* Pydev package explorer (Still BETA, so, use it with care -- the navigator
is still the preferred way of browsing your project)
 - Filters for .pyc and .pyo files created
 - Working set integration added (just available for Eclipse 3.2.1)
 - Some minor bugs fixed
* Patch by Olof Wolgast: The 'create docstrings' assistant has more options
(windows > preferences > pydev > code formatter > docstrings)
 - Option to choose between single and double quotes
 - Option to create '@type' too and not only '@param'
 - Option to skip creation of the @type tag for parameters starting
with some prefix (if 'Custom' is chosen)
* Block comments now have more options (windows > preferences > pydev > code
formatter > block comments)
 - Option to align single-line block comment to the left or right
 - Option to put class name above class if applied on a class
definition
* Fix: Multi-line Templates indent correctly
* Fix: When a file from a project that was deleted was still opened inside
pydev, Eclipse would not start-up correctly
* Fix: When a different interpreter is chosen in the run dialog, the
pythonpath is correctly gotten
* Fix: when Pydev was started, it would re-save the .pydevproject file even
if no change was done
* Fix: When tab width was set to 0 it could halt the editor (now if 0 is
set, 4 is assumed)
* Grammar Patch by Ueli Kistler, Dennis Hunziker




What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and Jython
development -- making Eclipse a first class Python IDE -- It comes with many
goodies such as code completion, syntax highlighting, syntax analysis,
refactor, debug and many others.


Cheers,

--
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rendering text question (context is MSWin UI Automation)

2007-01-24 Thread Boris Borcic
imageguy wrote:
> 
> I was looking for ( and still am searching for) similiar functionality.
>  Specifically I would like to be able to capture a small area of the
> screen (a number or a code) and convert this to text that can be used
> in my application.

There is a windows executable version of gnu ocr at 
http://jocr.sourceforge.net/download.html that (in combination with screen 
capture capability that pywinauto distributes) sort of can do that. An issue is 
that it's not exceedingly accurate, for instance it recognizes "2" as "1" (in 
the font that er, counts for me). I could probably manage such imprecisions but 
I would rather have an exact solution.
...
> 
> I work with wxPython and Win32 applications exclusively.
> 
> So if I can be of any help or assistance, please let me know.
> 
> Geoff.
> 

Thanks for the offer, I will keep it in mind,

Boris Borcic

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


Re: Rendering text question (context is MSWin UI Automation)

2007-01-24 Thread Boris Borcic
Chris Mellon wrote:
 > On 1/23/07, Boris Borcic <[EMAIL PROTECTED]> wrote:
 >> ...A simple -
 >> with Tkinter or otherwise - way to wrap access to the MS Windows UI text
 >> rendering engine, as a function that would return a picture of rendered 
 >> text,
 >> given a string, a font, a size and colors ?
...
 >
 > There are actually several different text rendering methods (and 2 or
 > more totally different engines) and they will give different results,
 > so if you want a fully generic solution that could be quite difficult.
 > However, it sounds like this is for a specific purpose.

Indeed.

 >
 > ...You could also use
 > wxPython, which uses what will probably be the right API and will take
 > less code than win32 will. I'd suggest this if you aren't familiar
 > with the win32 API.

Thanks for your guidance and quick code, I am going to try that.

Boris Borcic

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


Re: Q: Why Python is bad for web from the point of URLs?

2007-01-24 Thread Jia Lu

But you can do capsulation to them.


On 1月24日, 午後7:50, "techtonik" <[EMAIL PROTECTED]> wrote:
> A: Because you need three modules to parse, edit and reassemble query
> string. urlparse, cgi and urllib

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


Re: easy_install pylons failure - www.myghty.org unavailable

2007-01-24 Thread skip
Robert,

Thanks, I passed the contents of this thread along to distutils-sig.
Hopefully the list moderator is awake, as I'm not subscribed there... ;-)

Skip

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


Re: smtplib starttls gmail example - comments?

2007-01-24 Thread BJ Swope

On 1/24/07, Tim Williams <[EMAIL PROTECTED]> wrote:


On 24/01/07, py <[EMAIL PROTECTED]> wrote:
> I would love for anybody to comment on this code with regard to
redundancy/efficiency/wordiness or whatever else.
> for instance, do i understand correctly that i cant have a try: else:
without an intervening except:?
> -dave
>
> stdout.write("calling smtp server...")
> try:
> server = SMTP(msgsmtp)
> except:
> stdout.write("FAIL.")   #using .write to avoid the implied
\n with print
> else:
> server.set_debuglevel(msgdebug)
> stdout.write("starting tls...")
> server.ehlo(msgfrom)
> try:server.starttls()
> except: stdout.write("FAIL.")
> else:
> server.ehlo(msgfrom)   #neessary duplication (?)
> stdout.write("logging in...")
> try:server.login(msgfrom, msgpass)
> except: stdout.write("FAIL.")
> else:
> stdout.write("sending...")
> try:server.sendmail(msgfrom, msgto, msgtxt +
"\n.\n")
> except: stdout.write("FAIL.")
> else:
> try:
> server.quit()
> except sslerror:  # a known and largely
ignored issue with early EOF in ssl protocol
> stdout.write("success.")
> else:
> stdout.write("success.")
> --


*** Not tested  but should have the same functionality and error
handling as your script ***

this_host = 'myhostname.mydom1.com'
print "calling smtp server...", #  the trailing comma removes '\n'
try:
server = smtplib.SMTP(msgsmtp,local_hostname=this_host)
server.set_debuglevel(msgdebug)
print "starting tls...",
server.starttls()
server.ehlo(this_host)  # RFC requirement for 2nd EHLO after
requesting TLS
print "logging in...",
server.login(msgfrom, msgpass)
print "sending...",
failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n")
try:
server.quit()
except: pass
print "success."
except:
print "FAIL.",

if failed:
print "failed:", failed  # some recipients, but not all of them,
failed
--
http://mail.python.org/mailman/listinfo/python-list





Both examples have included the cardinal sin in smtp...

They both send the message text followed by new line dot new line.

The smtp protocol specifically mentions CRLF dot CRLF.   Please please
please use \r\n.\r\n in your code...

--
We are all slave to our own paradigm. -- Joshua Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to get self reference from within a module?

2007-01-24 Thread Lavoie Érick

I finally found what I was searching for here:

http://www.thescripts.com/forum/thread25264.html


I wanted the reference to the current module and we can obtain it this way:

sys.modules[__name__]

so its property can be used.

Thanks,

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

Py_DECREF after an exception

2007-01-24 Thread Hrvoje Nikšić
I'm wondering what happens with the exception info during object cleanup
immediately after an exception is thrown.  Consider this code:

  PyObject *args = PyBuild_Value("(O(O){})", name, parent);
  if (!args)
return NULL;
  PyObject *val = some_python_func(x, args, NULL);
  Py_DECREF(args);
  if (!val)
return NULL;

The idea is to propagate the exception possibly raised by
some_python_func and at the same time avoid leaking memory.  But
Py_DECREF can cause arbitrary Python code to get executed, including the
code that eventually ends up calling PyErr_Clear when it wants to ignore
some unrelated exception.  This could cause exception information to be
forgotten.

Is there a way around this, or is there a reason why this is not a
problem in practice?



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


Thoughts on using isinstance

2007-01-24 Thread abcd
In my code I am debating whether or not to validate the types of data
being passed to my functions.  For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name, str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things?  is it a "heavy"
operation?  for example, if I use this in each function validate input
will it slow things down a lot?

just curious how you might handle this type of situation (other than
not validating at all).

thanks

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


Re: sys.path issue in cygwin

2007-01-24 Thread Jason Tishler
Wang,

On Wed, Jan 24, 2007 at 04:14:48PM +0800, Wang Shuhao wrote:
> I successfully built and installed Python 2.2.3 in cygwin.
> [snip]
> Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is
> installed in /usr/local/lib/python2.2.3. The result of the issue is
> that when you run a program python can't find the module. So what I
> really want to know is where these path came from and how to fix it.

Why not use the Python that is part of the standard Cygwin distribution?

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question: ftp.storbinary()

2007-01-24 Thread Facundo Batista
Scott Ballard wrote:

> Sorry for the lame question, I'm still trying to pick up Python and new to 
> the list here.

Welcome!


> I'm assuming that  I should use storbinary( command, file[, blocksize]) to 
> transfer the files. the documentation says "command should be an appropriate 
> "STOR" command: "STOR filename"."

For example:

>>> fp = open("/tmp/file_to_transfer.txt")   # open the file
>>> self.ftp.storbinary("STOR file_to_transfer.txt", fp)   # note that the name 
>>> has not the path
>>> fp.close()  # close the file, :)

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Re: Thoughts on using isinstance

2007-01-24 Thread Maxim Sloyko


On Jan 24, 3:38 pm, "abcd" <[EMAIL PROTECTED]> wrote:
> In my code I am debating whether or not to validate the types of data
> being passed to my functions.  For example
>
> def sayHello(self, name):
> if not name:
> rasie "name can't be null"
> if not isinstance(name, str):
> raise "name must be a string"
> print "Hello " + name
>
> Is the use of isinstance a "bad" way of doing things?  is it a "heavy"
> operation?  for example, if I use this in each function validate input
> will it slow things down a lot?
>
> just curious how you might handle this type of situation (other than
> not validating at all).
>
> thanks

My opinion is that validation is generally good.  However, you have to
make it not too strict.
For example, instead of

print "Hello " + name

you could have written

print "Hello " + str(name)

In this case requirement isinstance() will be too strict. The only
thing you have to check is that hasattr(name, "__str__")  and
callable(name.__str__)

In this case you can have validation, while at the same time enjoy full
flexibility of dynamic typing.

--
Maxim

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread David Boddie
On Jan 24, 12:09 am, "Daniel" <[EMAIL PROTECTED]> wrote:
> I've downloaded both the wxPython and the PyQt4 package, and by the
> first impression I must say that the PyQt4 system had a very
> compelling presentation. From what I can understand from the feedback
> I've gotten so far is that the wxPython is a better choice when it
> comes to compability (with linux), and it's free even if I want to
> create applications and sell them.

Can you explain why you think wxPython is a better choice with respect
to "compatibility (with linux)"?

> So, from what I understand I will have to go with PyQt4 since (from
> my understanding):
> 1. I will not sell the applications I'm working with since they will
> only be used by the internal QA at a computer game company.
> 2. There seems to be a lot of documentation available for PyQt4.
> 3. PyQt4 seems to be easier to learn.
> 4. My programs does not need to support Linux or Unix.

Qt is a cross-platform framework, so you would get support for
X11-based
platforms, anyway.

David

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


Re: Thoughts on using isinstance

2007-01-24 Thread Steve Holden
abcd wrote:
> In my code I am debating whether or not to validate the types of data
> being passed to my functions.  For example
> 
> def sayHello(self, name):
> if not name:
> rasie "name can't be null"
> if not isinstance(name, str):
> raise "name must be a string"
> print "Hello " + name
> 
> Is the use of isinstance a "bad" way of doing things?  is it a "heavy"
> operation?  for example, if I use this in each function validate input
> will it slow things down a lot?
> 
> just curious how you might handle this type of situation (other than
> not validating at all).
> 
> thanks
> 
The "Python way" is to validate by performing the operations you need to 
perform and catching any exceptions that result. In the case of your 
example, you seem to be saying that you'd rather raise your own 
exception (which, by the way, should really be a subclass of Exception, 
but we will overlook that) that relying on the interpreter to raise a 
ValueError or a TypeError. Is there really any advantage to this? You 
increase your code size and add *something* to execution time with 
little real purpose.

People coming to Python after C++ or some similar language that allows 
or requires parameter type declarations often don't feel comfortable 
taking this direction to start with, but  it works well for most of us.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread hg
Laurent Rahuel wrote:

> Hi,
> 
> I known this can be impossible but what about an "HTML" GUI ?
> 
> Daniel Jonsson wrote:
> 
>> So, I've reached the point where my building pipeline tools actually
>> needs to be used by other people in my company. By this reason I
>> actually need to think about the usability, and I've come to the
>> conclusion that I need a GUI. So, which of the two packages should I
>> learn, and which one is easier to pick up?
>> Thanks in advance!
>> 
>> Daniel

I think it has been proposed.

I have customers that require that but usually find two major issues with
the concept:

1) Unless very knowledgeable in Ajax, it is quite difficult to reach the
same level of functionnality from a browser
2) accessing local devices generally requires browser plugins (XPCOM for
mozilla and ActiveX for IE)  which are a pain to code and are
considered a security breach.

hg

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


Re: Thoughts on using isinstance

2007-01-24 Thread Duncan Booth
"abcd" <[EMAIL PROTECTED]> wrote:

> In my code I am debating whether or not to validate the types of data
> being passed to my functions.  For example
> 
> def sayHello(self, name):
> if not name:
> rasie "name can't be null"
> if not isinstance(name, str):
> raise "name must be a string"
> print "Hello " + name
> 
> Is the use of isinstance a "bad" way of doing things?  is it a "heavy"
> operation?  for example, if I use this in each function validate input
> will it slow things down a lot?
> 
> just curious how you might handle this type of situation (other than
> not validating at all).
> 
For a start, don't raise strings as exceptions: only use instances of 
Exception.

Now consider what your first test does: it throws an error if you pass in 
an empty string. Perhaps you do want to check for that, in which case you 
will need to test for it and throw an appropriate exception.

The first test also catches values such as None, 0 or []. Do you really 
want to throw a different exception for sayHello(0) and sayHello(1)? It 
seems a bit pointless, so the first test should just check against an empty 
string and not against other false objects which would get caught by the 
second test.

Now for the second test. It would probably be useful to say in the 
exception which type was involved, not just that it wasn't a string.
An appropriate exception for these would be something like:

  TypeError: cannot concatenate 'str' and 'int' objects

since that tells you both the types and the operation that failed. Delete 
that second test altogether and you'll get an appropriate exception instead 
of a string which hides all the information.

A good rule is if you want to hide exception information from the user do 
it when displaying the exception not when raising it. That way you can get 
at all the exception information available by changing one place in the 
code instead of having to do it everywhere.

So your modified function should look like:

def sayHello(name):
if name=="":
raise ValueError("name can't be blank")
print "Hello "+name

(this is slightly different than your original in a few other ways: it will 
accept unicode strings so long as they can be encoded in ascii, and its a 
function as there isn't much point having a method which doesn't use self.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing .dlls when installing PyQt!? :(

2007-01-24 Thread Phil Thompson
On Wednesday 24 January 2007 1:36 pm, [EMAIL PROTECTED] wrote:
> Hello!
>
> I must be doing something wrong here because I'm getting all these
> missing .dll messages after installing PyQT. This is what I've done (no
> step excluded):
>
> 1. Fresh installation of Python25
> 2. I run the PyQt-gpl-4.1.1-Py2.5-Qt4.2.2.exe file which should include
> SIP
> 3. I run the qt-win-opensource-4.2.2-mingw.exe file
> 4. I try to launch the C:\Program
> Files\PyQt4\examples\tools\qtdemo\qtdemo.pyw file
>
> Result:
> Error message says: Can't find mingwm10.dll
>
> After searching for the file I found it in the C:\Qt\4.2.2\bin
> directory. I copied the dll to the windows dir just to run in to the
> next missing dll error (QtCore4.dll) which is also located in the same
> directory. What have I missed? I've been trying to install QT for 6
> hours now...
>
> Gah, please help! :)

Make sure your PATH includes the directory containing the MinGW DLL.

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


Re: sys.path issue in cygwin

2007-01-24 Thread Steve Holden
Wang Shuhao wrote:
>  
>  
> I successfully built and installed Python 2.2.3 in cygwin. But there is 
> something wrong in the sys.path. I use following statments for a test.
>  
>  >>> import sys
>  >>> print sys.path
> ['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', 
> 'C/lib/python2.2/lib-tk'
> , '\\Python24/lib/python2.2/lib-dynload']
>  >>>
>  
> To keep the question simple, I've set PATH= in cygwin.bat to avoid 
> python initialze sys.path from Windows' PATH environment.
>  
> Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is 
> installed in /usr/local/lib/python2.2.3. The result of the issue is that 
> when you run a program python can't find the module. So what I really 
> want to know is where these path came from and how to fix it.
>  
>  
> 
Why "obviously"? 2.2.3 and 2.2.2 aren't meant to coexist, so one will
install over the other. So the directories you are seeing are what would
be used with standard prefix settings.

If you mean "obviously because I used a setting to configure the
prefixes for loading from a specific directory" then perhaps you are
suffering from having set your Windows PATH. If you *don't* set your
Windows PATH do you see it using the "2.2.3" variants?

Did you run "make install"?

Just a couple of random thoughts ... are you even sure that running the
"python" command does run your new 2.2.3 binary?

regards
 Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com

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

Missing .dlls when installing PyQt!? :(

2007-01-24 Thread wd . jonsson
Hello!

I must be doing something wrong here because I'm getting all these
missing .dll messages after installing PyQT. This is what I've done (no
step excluded):

1. Fresh installation of Python25
2. I run the PyQt-gpl-4.1.1-Py2.5-Qt4.2.2.exe file which should include
SIP
3. I run the qt-win-opensource-4.2.2-mingw.exe file
4. I try to launch the C:\Program
Files\PyQt4\examples\tools\qtdemo\qtdemo.pyw file

Result:
Error message says: Can't find mingwm10.dll

After searching for the file I found it in the C:\Qt\4.2.2\bin
directory. I copied the dll to the windows dir just to run in to the
next missing dll error (QtCore4.dll) which is also located in the same
directory. What have I missed? I've been trying to install QT for 6
hours now...

Gah, please help! :)

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Giovanni Bajo
On 24/01/2007 1.45, Joshua J. Kugler wrote:

>> I've downloaded both the wxPython and the PyQt4 package, and by the
>> first impression I must say that the PyQt4 system had a very
>> compelling presentation. From what I can understand from the feedback
>> I've gotten so far is that the wxPython is a better choice when it
>> comes to compability (with linux), and it's free even if I want to
>> create applications and sell them.
>> So, from what I understand I will have to go with PyQt4 since (from
>> my understanding):
>> 1. I will not sell the applications I'm working with since they will
>> only be used by the internal QA at a computer game company.
> 
> Even that is getting on shaky ground, at least according to Troll Tech. 
> See: http://www.trolltech.com/developer/knowledgebase/190/  So, write it
> for internal use, and put up for distribution on your personal web site
> (pending company approval, of course).

That page is legal babble, trying to trick you into buying (or making your 
boss buy) a commercial license. The Qt Open Source edition *IS* GPL and thus 
it falls under all the normal GPL clauses and uses, irrespective of what 
Trolltech may or may not think.

For instance, see this FAQ:
http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic

which makes pretty clear that a "company"/"organization" is basically the same 
of an "individual". "Releasing a software within a company for internal usage" 
is by no means the same of "releasing it to the public". Basically, for what 
the GPL is concerned, it is *not* a "release" or a "distribution" at all.

Thus, it is well possible to write internal GPL software, using the Qt Open 
Source library, and to release/distribute/use it *ONLY* internally. Also, it 
should be made clear that a company can of course relicense its own 
proprietary libraries as GPL for internal usage only, so that they can be 
linked to other GPL libraries "legally". For instance, in the case of Daniel 
and his game company, they can link their proprietary game code to PyQt4 (Open 
source edition) to produce an internal tool, like a level editor, which would 
then fall under the GPL. If and only if they were to release that tool to the 
public (either for free or for sale), they would have to either go GPL and 
release full source code (include the parts of their game code linked to it), 
or buy a Qt commercial license.

[[ Another page of similar babble is the one where they try to convince you 
that you cannot use the Qt Open Source edition to develop a software, and then 
buy the commercial edition only the day before you want to release it as non 
open-source. I can't even understand how they can even try to support such a 
nonsense position. You're free to develop your software for years as GPL 
without distributing it, and then relicense your own code whenever you want. 
They're obviously just trying to scare people. ]]
-- 
Giovanni Bajo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing .dlls when installing PyQt!? :(

2007-01-24 Thread Giovanni Bajo
On 24/01/2007 14.36, [EMAIL PROTECTED] wrote:

> I must be doing something wrong here because I'm getting all these
> missing .dll messages after installing PyQT. This is what I've done (no
> step excluded):
> 
> 1. Fresh installation of Python25
> 2. I run the PyQt-gpl-4.1.1-Py2.5-Qt4.2.2.exe file which should include
> SIP
> 3. I run the qt-win-opensource-4.2.2-mingw.exe file
> 4. I try to launch the C:\Program
> Files\PyQt4\examples\tools\qtdemo\qtdemo.pyw file
> 
> Result:
> Error message says: Can't find mingwm10.dll
> 
> After searching for the file I found it in the C:\Qt\4.2.2\bin
> directory. I copied the dll to the windows dir just to run in to the
> next missing dll error (QtCore4.dll) which is also located in the same
> directory. What have I missed? I've been trying to install QT for 6
> hours now...

Add C:\Qt\4.2.2\bin to your PATH.
-- 
Giovanni Bajo
-- 
http://mail.python.org/mailman/listinfo/python-list


AFP library for Python

2007-01-24 Thread Luca Masini
Hi,

googled for a Python library that support AFP but
found only a PERL module:
   http://search.cpan.org/src/AUTRIJUS/Parse-AFP-0.24/

Maybe someone know of a similar library for Python ?

PS: in alternative if there are some interested people
 we can implement it...
 :-))

Thanks


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


Re: Thoughts on using isinstance

2007-01-24 Thread abcd
> The "Python way" is to validate by performing the operations you need to
> perform and catching any exceptions that result. In the case of your
> example, you seem to be saying that you'd rather raise your own
> exception (which, by the way, should really be a subclass of Exception,
> but we will overlook that) that relying on the interpreter to raise a
> ValueError or a TypeError. Is there really any advantage to this? You
> increase your code size and add *something* to execution time with
> little real purpose.
>
> People coming to Python after C++ or some similar language that allows
> or requires parameter type declarations often don't feel comfortable
> taking this direction to start with, but  it works well for most of us.
>
> regards
>   Steve


So instead of validating input I should just try and use the input as
if it was correct, and let python throw the errors?

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


Re: OT Annoying Habits (Was: when format strings attack)

2007-01-24 Thread Steve Holden
Carroll, Barry wrote:
> Greetings:
> 
> Personally, I don't think top-posting is the most annoying newsgroup
> habit.  I think it's making a big fuss about minor inconveniences.  
> 
> One of the nicest things about being human is the amazing flexibility of
> our brains.  For example, if a block of text isn't arranged in the order
> we're used to, we can easily rearrange it mentally and read it anyway.
> Oriental and Arabic peoples, for example, do this each time they read
> something written in English.  It's EASY, once you get used to it!
> 
That's as may be. but just last week I was presented with a printed 
five-page message where all contributors to the thread had top-posted. 
There were four and five levels of quoting in some places, line wrapping 
was all over the place as a result, and it was difficult to even make 
out which bits were quoted at the same level.

If everyone had refrained from top-posting then it would have been much 
easier to read the ensuing (linear) conversation. In short: top-posting 
doesn't hurt in simple cases, but it's a real hurdle to understanding in 
the long-running threads typically generated on mailing lists and 
newsgroups.

There are many people who find it natural to consider their own 
convenience over that of hundreds or thousands of others, so by all 
means continue with your top-posting habit if it's too much trouble to 
avoid it. It's unlikely to get you killed, but it *does* say something 
about you, and people will draw conclusions, possibly incorrect ones, 
about you as a result.

As a final riposte, our personal opinions aren't really much of a guide 
to the wishes of the masses, whereas the reaction of the masses (as in: 
"Why do you top-post?") often is. How often do you see someone ask 
"please start top-posting"? I've had precisely one such request in many 
many years of email and Internet usage.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com

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


Re: Thoughts on using isinstance

2007-01-24 Thread Neil Cerutti
On 2007-01-24, abcd <[EMAIL PROTECTED]> wrote:
> In my code I am debating whether or not to validate the types of data
> being passed to my functions.  For example
>
> def sayHello(self, name):
> if not name:
> rasie "name can't be null"
> if not isinstance(name, str):
> raise "name must be a string"
> print "Hello " + name
>
> Is the use of isinstance a "bad" way of doing things?  is it a
> "heavy" operation?  for example, if I use this in each function
> validate input will it slow things down a lot?
>
> just curious how you might handle this type of situation (other
> than not validating at all).

Validation of parameters is an excellent idea, but *not*
validation of datatypes. The problem is that sayHello can
function properly with many more objects than just strings, if
you write it differently. The following version accepts any
iterable over strings.

def sayHello(self, name):
  it = iter(name)
  print "Hello", ''.join(it)

It still lacks validation. But to validate a name you will need
to conceive a set of regular strings that contains every name
you'd like to accept. Names probably aren't worth validating,
although you might reasonably reject a few things, like the empty
string.

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread David Boddie
On Jan 24, 3:00 pm, Giovanni Bajo <[EMAIL PROTECTED]> wrote:

> Thus, it is well possible to write internal GPL software, using the Qt Open
> Source library, and to release/distribute/use it *ONLY* internally.

http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic

> Also, it
> should be made clear that a company can of course relicense its own
> proprietary libraries as GPL for internal usage only, so that they can be
> linked to other GPL libraries "legally".

That seems to be a reasonable approach, though it seems to me that the
GPL grants even "internal" users certain rights.

> [[ Another page of similar babble is the one where they try to convince you
> that you cannot use the Qt Open Source edition to develop a software, and then
> buy the commercial edition only the day before you want to release it as non
> open-source. I can't even understand how they can even try to support such a
> nonsense position. You're free to develop your software for years as GPL
> without distributing it, and then relicense your own code whenever you want.
> They're obviously just trying to scare people. ]]

That's nothing to do with any restrictions in the GPL; it's more to do
with
purchasing a commercial license. Obviously, if you're operating a dual
licensing scheme, it's not in your interest to encourage people to
pretend
to write open source software up until the day it is released as a
closed
source product. That sort of behaviour is not exactly inviting mutual
trust
between vendor and customer, is it?

David

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


Re: Rendering text question (context is MSWin UI Automation)

2007-01-24 Thread Boris Borcic
Chris Mellon wrote:
> 
> Using either win32 or wxPython you will be able to produce bitmaps
> directly, without needing to create a visible window.
> 
> 
> Some quick & dirty wxPython code
> 
> def getTextBitmap(text, font, fgcolor, bgcolor):
> dc = wx.MemoryDC()
> dc.SetFont(font)
> width, height= dc.GetTextExtent(text)
> bmp = wx.EmptyBitmap(width, height)
> dc.SelectObject(bmp)
> dc.SetBackground(wx.Brush(bgcolor))
> dc.Clear()
> dc.SetTextBackground(bgcolor)
> dc.SetTextForeground(fgcolor)
> dc.DrawText(text, 0, 0)
> dc.SelectObject(wx.NullBitmap)
> return bmp
> 
> 
> Raw win32 code will look similar but will be much more verbose.

Thx again for this base.

Quickly testing this, it appears that the result is rendered half a pixel off 
in 
the x-direction. Does this make sense ? Is it possible to position text with 
subpixel accuracy ?

Regards, Boris Borcic

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


Re: Thoughts on using isinstance

2007-01-24 Thread Bruno Desthuilliers
abcd a écrit :
> In my code I am debating whether or not to validate the types of data
> being passed to my functions.  For example
> 
> def sayHello(self, name):
> if not name:
> rasie "name can't be null"
> if not isinstance(name, str):
> raise "name must be a string"
> print "Hello " + name
> 
> Is the use of isinstance a "bad" way of doing things? 

Mostly, yes. Python is dynamically typed (well, it's dynamic all the 
way...), and fighting against the language is a bad idea.

Also, since the use of an object of non-compatible type would usually 
raise an exception (and while we're at it, avoid using strings as 
exceptions - better to use some Exception class), you don't actually 
gain anything.

> just curious how you might handle this type of situation (other than
> not validating at all).

There are mostly 2 cases :
1/ you're getting data from the outside world. Here, you have to be 
*very* careful, and you usually need more than simple validation. Good 
news is that we have modules like FormEncode designed to handle this case.

2/ you're getting 'data' from within your Python program. If you 
correctly applied 1/, whatever comes in should be ok - that is, unless 
you have a programmer error !-). But then, you'll usually have a nice 
exception and traceback (or better unit tests failures), so you can fix 
the problem immediatly.

Now there are *a few* corner cases where it makes sens to check what has 
been passed to a function - either because there are very strict and 
stable requirements here, or because the function can accept different 
kinds of objects, but needs to handle them in distinct ways.

MVHO is that the less code the better. As a matter of fact, trying to 
'protect' your function, you introduced a syntax error, that would not 
have been here if you had just wrote the simplest thing:

def say_hello(who):
   print "Hello", who

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.path issue in cygwin

2007-01-24 Thread Wang Shuhao
There is only python2.2.3 on my machine, and the location is 
/usr/local/lib/python2.2 . I say the 'C/lib/python2.2/' is a wrong path is 
because the leading C/lib is not point to the location of my python 
installation. I'v found the solution anyway. The environment variable 
PYTHONHOME controls the content of the initial sys.path. put 
export PYTHONHOME=/usr/local in .bash_profile will fix it.

- Original Message - 
From: "Steve Holden" <[EMAIL PROTECTED]>
To: 
Sent: Wednesday, January 24, 2007 9:42 PM
Subject: Re: sys.path issue in cygwin


> Wang Shuhao wrote:
>>  
>>  
>> I successfully built and installed Python 2.2.3 in cygwin. But there is 
>> something wrong in the sys.path. I use following statments for a test.
>>  
>>  >>> import sys
>>  >>> print sys.path
>> ['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', 
>> 'C/lib/python2.2/lib-tk'
>> , '\\Python24/lib/python2.2/lib-dynload']
>>  >>>
>>  
>> To keep the question simple, I've set PATH= in cygwin.bat to avoid 
>> python initialze sys.path from Windows' PATH environment.
>>  
>> Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is 
>> installed in /usr/local/lib/python2.2.3. The result of the issue is that 
>> when you run a program python can't find the module. So what I really 
>> want to know is where these path came from and how to fix it.
>>  
>>  
>> 
> Why "obviously"? 2.2.3 and 2.2.2 aren't meant to coexist, so one will
> install over the other. So the directories you are seeing are what would
> be used with standard prefix settings.
> 
> If you mean "obviously because I used a setting to configure the
> prefixes for loading from a specific directory" then perhaps you are
> suffering from having set your Windows PATH. If you *don't* set your
> Windows PATH do you see it using the "2.2.3" variants?
> 
> Did you run "make install"?
> 
> Just a couple of random thoughts ... are you even sure that running the
> "python" command does run your new 2.2.3 binary?
> 
> regards
> Steve
> -- 
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb http://del.icio.us/steve.holden
> Blog of Note:  http://holdenweb.blogspot.com
> 
>





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

Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Harry George
"Joshua J. Kugler" <[EMAIL PROTECTED]> writes:

> Daniel wrote:
> 
> > I've downloaded both the wxPython and the PyQt4 package, and by the
> > first impression I must say that the PyQt4 system had a very
> > compelling presentation. From what I can understand from the feedback
> > I've gotten so far is that the wxPython is a better choice when it
> > comes to compability (with linux), and it's free even if I want to
> > create applications and sell them.
> > So, from what I understand I will have to go with PyQt4 since (from
> > my understanding):
> > 1. I will not sell the applications I'm working with since they will
> > only be used by the internal QA at a computer game company.
> 
> Even that is getting on shaky ground, at least according to Troll Tech. 
> See: http://www.trolltech.com/developer/knowledgebase/190/  So, write it
> for internal use, and put up for distribution on your personal web site
> (pending company approval, of course).
> 
> j
> 
> -- 
> Joshua Kugler
> Lead System Admin -- Senior Programmer
> http://www.eeinternet.com
> PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE
> 
> -- 
> Posted via a free Usenet account from http://www.teranews.com
> 

There are several OSS suppliers that use GPL, and then try to define
its meaning.  They are welcome to comment on their understanding of
the GPL, but they do not have the authority to actually define its
legal ramifications.  Check with your company legal staff.

Having said that, I have been troubled by trolltech's approach from
the beginning, and therefore stay away from it.  PyGTK and wdxPython
are solid GUIs, without the legal uncertainty.


-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Kevin Walzer
Daniel Jonsson wrote:
> So, I've reached the point where my building pipeline tools actually 
> needs to be used by other people in my company. By this reason I 
> actually need to think about the usability, and I've come to the 
> conclusion that I need a GUI. So, which of the two packages should I 
> learn, and which one is easier to pick up? 
> Thanks in advance!
> 
> Daniel

I recommend Tkinter. By itself, Tkinter is too basic (it only supports
buttons, labels, frames, and so on), but if you add extension packages
such as Tablelist (for data display), Tile (for platform-native
theming), and TkTreeCtrl (for tree views), it can produce GUI's that are
just as rich as those available from wx or Qt.

Here are some links for more info:

Tile: http://tktable.sourceforge.net/tile
Tile for Tkinter: http://tkinter.unpythonic.net/wiki/TileWrapper

Tablelist: http://www.nemethi.de/
Tabelist for Tkinter (with Tile support):
http://tkinter.unpythonic.net/wiki/TableListTileWrapper

Tktreectrl: http://tktreectrl.sourceforge.net/
Treectrl for Tkinter: http://klappnase.zexxo.net/TkinterTreectrl/index.html

All these libraries are open-source and available under
commercial-friendly terms (BSD-style licenses).

I make heavy use of Tile and Tablelist in my applications. Tktreectrl is
incredibly powerful, but is also quite complex, and I have not used it
myself in an application.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Kevin Walzer
Kevin Walzer wrote:

> 
> Tablelist: http://www.nemethi.de/
> Tabelist for Tkinter (with Tile support):
> http://tkinter.unpythonic.net/wiki/TableListTileWrapper
> 

Additionally, here is a link to some screenshots for Tablelist:

http://www.nemethi.privat.t-online.de/tablelist/screenshots.html


-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not play well with others

2007-01-24 Thread Harry George
John Nagle <[EMAIL PROTECTED]> writes:

>The major complaint I have about Python is that the packages
> which connect it to other software components all seem to have
> serious problems.  As long as you don't need to talk to anything
> outside the Python world, you're fine.  But once you do, things
> go downhill.  MySQLdb has version and platform compatibility
> problems.  So does M2Crypto.  The built-in SSL support is weak.
> Even basic sockets don't quite work right; the socket module
> encapsulates the timeout mechanism but doesn't get it right.
> 
>In the Perl, Java, PHP, and C/C++ worlds, the equivalent
> functions just work.   That's because, in those worlds, either the
> development team for the language or the development team
> for the subsystem takes responsibility for making them work.
> Only Python doesn't do that.
> 
>Python has been around long enough that this should have
> been fixed by now.
> 
>   John Nagle

You experience isn't shared by everyone.  Some of us find Python the
most functional and portable of the candidates you mention.

Perl - excellent modules and bindings for just about everything you
can think of, but the whole thing is painful to watch.  Once you've
done a few code reviews on 10,000 line perl packages where even the
authors have no idea what the code is doing, you tend to look
elesewhere.

Java - a world of its own.  They reinvent the wheel instead of linking
to existing libraries.  In the process you get libraries upon
libraries upon libraries.  Even if there isn't a performance hit, you
(as a human) can get lost.  And the language is just too verbose to
live with.

PHP - are we talking web scripts or serious programs?  Are you doing
numerical analysis, NLP, computational chemistry, or bit twiddling in
PHP?

C - the portable assembler.  Solid, trusted, tunable performance,
bindings for everything.  Of course memory bugs can stop your project
in its tracks for indeterminant periods.

C++ - objects tacked onto C; but that didn't work so invent a whole
world of templates and rewrite everything again, but now trickier than
C to bind to other languages.  Good work can be done in C++, but that
is a testimony to the programmers and not to the language.

Python - it just works.  Same scripts run on every platform.  Bindings
available to every C/C++/FORTRAN library I've needed so far.  Often
the bindings are not complete, but oddly enough the binding developers
have chosen to do just the functions I need, so who cares.  A clean
architecture for adding more function bindings if I'm so inclined.

-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread hg
Kevin Walzer wrote:

> Kevin Walzer wrote:
> 
>> 
>> Tablelist: http://www.nemethi.de/
>> Tabelist for Tkinter (with Tile support):
>> http://tkinter.unpythonic.net/wiki/TableListTileWrapper
>> 
> 
> Additionally, here is a link to some screenshots for Tablelist:
> 
> http://www.nemethi.privat.t-online.de/tablelist/screenshots.html
> 
> 
> --
> Kevin Walzer
> Code by Kevin
> http://www.codebykevin.com

Just for info - one of the reasons I stopped using Tkinter a few years ago
was for the lack of print support (preview ...) - is there such an
extension today ?

hg

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


Email attachments

2007-01-24 Thread Steve Holden
I'm having some trouble getting attachments right for all recipients, 
and it seems like Apple's mail.app is the pickiest client at the moment. 
It doesn't handle attachments that both Thunderbird and Outlook find 
perfectly acceptable.

Since the code I'm using is currently ugly and embedded, before I trim 
it down for posting could anyone who's successfully generated emails 
with attachments received by mail.app let me know if they had any 
problems along the way? Google hasn't given me much on this, but I'm not 
feeling very creative today.

Note that this is an important application: it sends out the invoices 
for PyCon sponsorship!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com

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


Re: smtplib starttls gmail example - comments?

2007-01-24 Thread Tim Williams
On 24/01/07, BJ Swope <[EMAIL PROTECTED]> wrote:
>
>
>
> On 1/24/07, Tim Williams <[EMAIL PROTECTED]> wrote:
> >
> > On 24/01/07, py <[EMAIL PROTECTED]> wrote:
> > > I would love for anybody to comment on this code with regard to
> redundancy/efficiency/wordiness or whatever else.
> > > for instance, do i understand correctly that i cant have a try: else:
> without an intervening except:?
> > > -dave
> > >
> > > stdout.write("calling smtp server...")
> > > try:
> > > server = SMTP(msgsmtp)
> > > except:
> > > stdout.write("FAIL.")   #using .write to avoid the implied
> \n with print
> > > else:
> > > server.set_debuglevel(msgdebug)
> > > stdout.write("starting tls...")
> > > server.ehlo(msgfrom)
> > > try:server.starttls ()
> > > except: stdout.write("FAIL.")
> > > else:
> > > server.ehlo(msgfrom)   #neessary duplication (?)
> > > stdout.write("logging in...")
> > > try:server.login(msgfrom, msgpass)
> > > except: stdout.write("FAIL.")
> > > else:
> > > stdout.write("sending...")
> > > try:server.sendmail(msgfrom, msgto, msgtxt +
> "\n.\n")
> > > except: stdout.write("FAIL.")
> > > else:
> > > try:
> > > server.quit()
> > > except sslerror:  # a known and largely
> ignored issue with early EOF in ssl protocol
> > > stdout.write("success.")
> > > else:
> > > stdout.write("success.")
> > > --
> >
> >
> > *** Not tested  but should have the same functionality and error
> > handling as your script ***
> >
> > this_host = 'myhostname.mydom1.com'
> > print "calling smtp server...", #  the trailing comma removes '\n'
> > try:
> > server =
> smtplib.SMTP(msgsmtp,local_hostname=this_host)
> > server.set_debuglevel(msgdebug)
> > print "starting tls...",
> > server.starttls()
> > server.ehlo(this_host)  # RFC requirement for 2nd EHLO after
> requesting TLS
> > print "logging in...",
> > server.login(msgfrom, msgpass)
> > print "sending...",
> > failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n")
> > try:
> > server.quit()
> > except: pass
> > print "success."
> > except:
> > print "FAIL.",
> >
> > if failed:
> > print "failed:", failed  # some recipients, but not all of them,
> failed
> > --
> > http://mail.python.org/mailman/listinfo/python-list
>
>
> Both examples have included the cardinal sin in smtp...
>
>  They both send the message text followed by new line dot new line.
>
>  The smtp protocol specifically mentions CRLF dot CRLF.   Please please
> please use \r\n.\r\n in your code...
>

Ha, yeah I didn't spot that,  but then I wasn't looking for it either :)

However, Its not an issue with smtplib because its takes these kind of
things into account by:

* modifying line endings that aren't RFC compliant to CRLFs.
* normalising/changing a single leading dot (.) to dot dot (..)
* adding the CRLF dot CRLF to the end of the supplied message text.

So adding adding "\n.\n" to the end of the msg text will just add a
line containing  ".."  to the end of the message text, it won't
terminate the DATA part.

that line should therefore be just

failed = server.sendmail(msgfrom, msgto, msgtxt)

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


Re: Thoughts on using isinstance

2007-01-24 Thread Steve Holden
abcd wrote:
>> The "Python way" is to validate by performing the operations you need to
>> perform and catching any exceptions that result. In the case of your
>> example, you seem to be saying that you'd rather raise your own
>> exception (which, by the way, should really be a subclass of Exception,
>> but we will overlook that) that relying on the interpreter to raise a
>> ValueError or a TypeError. Is there really any advantage to this? You
>> increase your code size and add *something* to execution time with
>> little real purpose.
>>
>> People coming to Python after C++ or some similar language that allows
>> or requires parameter type declarations often don't feel comfortable
>> taking this direction to start with, but  it works well for most of us.
>>
>> regards
>>   Steve
> 
> 
> So instead of validating input I should just try and use the input as
> if it was correct, and let python throw the errors?
> 
Yes. This approach is often referred to as BTAFTP (better to ask 
forgiveness than permission), as opposed to the LBYL (look before you 
leap) approach that your original email inquired about.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com

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


Re: sys.path issue in cygwin

2007-01-24 Thread Jason Tishler
Wang,

Please keep your replies on-list.

On Wed, Jan 24, 2007 at 10:28:51PM +0800, Wang Shuhao wrote:
> > Why not use the Python that is part of the standard Cygwin
> > distribution?
> > 
> Cause the Cygwin version python has the same problem, that why I try
> to build python from source.

The above implies that you may have a Cygwin installation problem that
may impact other Cygwin applications too.  I recommend taking this
problem to the Cygwin list:

http://cygwin.com/problems.html

FWIW, I get the following with the official Cygwin Python version:

$ python -c 'import sys; print sys.path'
['', '/usr/lib/python24.zip', '/usr/lib/python2.4', 
'/usr/lib/python2.4/plat-cygwin', '/usr/lib/python2.4/lib-tk', 
'/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages']

> But finally I found the solution, the PYTHONHOME environment variable
> controls the content of initial sys.path. Thanks anyway.
> export PYTHONHOME=/usr/localWang Shuhao

IMO, the above is just a workaround, not a solution.

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


for thibaut: genuinely excellent pictures - umcu - (1/1)

2007-01-24 Thread rocky
Hello,

Images, video, mp3 music, the real news from around the world... it's all 
inside waiting for you.
You can find almost anything you are looking for.
They offer some of the best premium newsgroup access anywhere.
One thing I love about them, they don't keep log files of the news I read or 
files I download.
Take a look, I know you'll love it as much as I do.
They give you access to some of the best groups others may not carry.
Great prices and support await you as you travel into the beautiful world of 
premium nntp access.
Take a look at all the great features below and imagine! You'll LOVE it.

Blazing fast downloads
Posting allowed!
Convenient thumbnail indexes
Very long retention
Keyword searchable
Streaming audio and video
2,000,000 new posts each day

Just go to http://www.newsdude.net and see why I love them so much. Have a 
great night!


Jik hel ki vatnuzehgow newdebotrig totva fesmo, riwwi berte doy berwa guypo!
At absa i ecci. Evwu rop marke huppu ok i anyo ovtu! Rog pi sahmilunyiw 
bashorasnah
ak hud! Uh irfu up op awtu. I iskutagyuf ruz vi gevsigushes hitmi mafri dapji, 
futwe
it diz nog ot ur atmi. Osja ahhe i emsekuzpid, bey fuhfa ni sokgeferjub 
gamtosogjos
bah! Of uyho egsi i ecnu oscelapsob akso as i anyocazgol offu! I peh nohtiwedjip
didpu gi huczu mevpapudpom jud fojru nohyu! Oj uzhi i ug embi if i apta! 
Uvbicerdez
ecru i oywo. Okcemokfal iybo uz i ejyerowlur lis gi vum mudhi ev ar! Ahpes ewfu 
kir
mi vizkihudduk rakbewuwgif pi wofco sewyuzucdiw zusso sin. Mapja hi dac 
nirgasaktik
og i irbemommij iskapojbes uywa fiw, ri ut ivde i zot pepwomekyak tavru ki huz 
dal.
Ref jecfo gi az umminizpez avga i eh abpa i ejne onwavepgeb, okca azzi i ler 
tuhtu
dezpu! Ib i ofmijihvej on, i evda anyohiknah i ton, zajsocehmel tonci vuplutiv
dezva sen ib olre azyu wum! Sahci nellu gento, pi ed et ewze i onricodjaf! Ufme 
ujmi
ilni i evli if i wut zigyusagjez wi zosgofuptum, il ozne ujhu, ecwi awvu i 
ihcovogkat!
Of nep vi coh hablazezgav ci pagro, zer bi firto ak esfi i un! Arwusuftez ahpo 
i or
ovmo um i on egli opwi, sik pujgu fi cohzejokyaj tojkadeyref fi deryubavzon 
memde
jibpu! Bid di biztukesdof ic pin oz av i eyrutarrav! Apya ehbi uvgi ugyi i amco 
ulmuzaccum!
Ak i riw pez toyweb, vi bemba zovsinuscav fi bes duswa ji og ud, asze i azyi ey 
niz sos
nurku. Bucbu ji er izlo liv sijgo ruy lacje ef i orpo! Intozudpup i otka 
oryedebbaz
i addi akwo ec afre i ur, ehzonekhuv uste afju utvi er, i okza oh apsu ar uzhe 
ehtu!
Umja al i jok cagluluwdek fun ri if bos debga zecju! Mi nof geska cahva gon ji 
mumsezuphop,
tocvu ki juhyehemyog faygopubjow! Marwe luh dik pipge, hogli tuj ci wajmi fevni.
Hi cammahibnul pebki deksa bowva nar sodtu peyfo kewgi! Ji lif jigpu li nadnis 
bobgehacboj
jesne ti vazrofergih ik, avko i ubdulaltid asgorojhob i ebrokemlac uwvafukgat
egbi i atyu ibkihamyeg! Amke em i awfosorbam bam uk ov kaf vi jakfuvapset. Up 
par
ec! I uspu hul pi ut vel pi zulva patni. Oy ewle uspo azto. I agpi kik ah i 
osji ar i ecri
wij, vi hozmu ap ifke usfu! Orro um ay i afyu ceh hi dibmu! Visbinivpuw ti jiv 
wagbe
pezte lar. Dopli if agyo i ur evmelicbog az, ifyu i apru uzfo! I odto os i buv. 
Ik god
tejge caj, vi jev fir mi hobbe. Vohjigiydap ji toj ac enlu i is apremubhuw i 
ehju osda
ber, gul at i ohce, utheceswez ohci ak ukhu i ozvo iffo, ipzu ol evha i if, 
ujziruhpuf
upke is i azdo asto i onyatewwil obhebikrid i ojyu. Den zazja wi serpa 
numbenidfav,
sidve vuf li fumhulokwaw un avsi ewwi uthi i izbivahhel. Etku ged wej fafki vip 
ti
ew asbi. Igpu keh pi dov vekvojavhuk ri hakge, is ejne gow! Pi kisre luzpeweggib
kas law repri zecdu om i ezlu aj, i owja apgelidyek uk sal ev i rak. 
Necsakigtat mol
rofce davbu mohke razca, bimso vuw hassi degha ni ramla, babyinokzak kojmazow
ov ub, i uvse efhecujfup igde iwwi ucro arle i empu ossowargat, dap huv ci buf 
molko.
Hen ki sugha kekpirojjoz ni hokku jij nobni tiv. Bofli vi tahja vep, pi af 
ebjubatwum
sis lurni hacji ig i isni epfu! Amga ezke i osja nin jub fedba uh mov. Al ucra 
kow. Farsa
ciknu uj as joy bi didde oz ahri bab. Dogme mi ot isle i bav cigtofitcos. Ti oz 
adnekorsob
on eszu ewvu owri i atru. Ofge utto izwu gih ji negdesalfaz coy hi vochurecnan 
cacgepocmup.
Si jobkav nop von, juyda vi hijja rog vulhe. Bonto uw i ogvigotmif esmapiwceg is
igvi i ey. Em i inzeficnev hih, an i ergi apdo uzfe i okze iryu ukci den luj. 
Vofge si
fob it zat uf ipzu i erki ic i oslulutcer. Onkubohyiz ab i avse ec i am al! Uz 
i inpegirmiw
ses ji voprorurlak en. Ispo izsi sek wi reyci ug how vi luz wenpozommol, am ir 
kag
ij ehso i av hil, el moc rem uy pug fi sikro. Gev mon iz ug ofvu ud onfo i 
uzyocujzun!
Naz wudri sic li mozciporcaw dew honte si pefpu! Wezwurobvuz dilpu bi ik dar 
wogwu.
Tawzi ci vih ib i ezyonecweg opcu i alze wib iy! Hin bi jat dazcudorzoh vi 
bugjo suh
ri mohragepbol. Huvyihakseb wi luhtukonled rabladorrih pidjo. Ej did up! Ibti
i uybulujwup rum om ozma ogdu i aw, bab ti ig kok di ay eywi. I ukzegarnov ekro 
avru
ekka i oh urcutikva

Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Chris Mellon
On 1/24/07, Giovanni Bajo <[EMAIL PROTECTED]> wrote:
> On 24/01/2007 1.45, Joshua J. Kugler wrote:
>
> >> I've downloaded both the wxPython and the PyQt4 package, and by the
> >> first impression I must say that the PyQt4 system had a very
> >> compelling presentation. From what I can understand from the feedback
> >> I've gotten so far is that the wxPython is a better choice when it
> >> comes to compability (with linux), and it's free even if I want to
> >> create applications and sell them.
> >> So, from what I understand I will have to go with PyQt4 since (from
> >> my understanding):
> >> 1. I will not sell the applications I'm working with since they will
> >> only be used by the internal QA at a computer game company.
> >
> > Even that is getting on shaky ground, at least according to Troll Tech.
> > See: http://www.trolltech.com/developer/knowledgebase/190/  So, write it
> > for internal use, and put up for distribution on your personal web site
> > (pending company approval, of course).
>
> That page is legal babble, trying to trick you into buying (or making your
> boss buy) a commercial license. The Qt Open Source edition *IS* GPL and thus
> it falls under all the normal GPL clauses and uses, irrespective of what
> Trolltech may or may not think.
>
> For instance, see this FAQ:
> http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic
>
> which makes pretty clear that a "company"/"organization" is basically the same
> of an "individual". "Releasing a software within a company for internal usage"
> is by no means the same of "releasing it to the public". Basically, for what
> the GPL is concerned, it is *not* a "release" or a "distribution" at all.
>

I should point out that the FSFs position in this regard is not
supported by copyright law and that the fact that Trolltech takes a
different position is something that you should consider strongly. If
the FSFs position were true, there would be no need for per-seat
licensing of commercial software (because internal distribution
wouldn't be). US copyright law does not draw a distinction between
"internal distribution" and any other kind, and I'm not aware of any
case law that does so either. This distinction is also not codified in
the GPL itself anywhere, so it's not a necessary condition of the
license - it is an interpretation by the FSF and that is all.

> Thus, it is well possible to write internal GPL software, using the Qt Open
> Source library, and to release/distribute/use it *ONLY* internally. Also, it
> should be made clear that a company can of course relicense its own
> proprietary libraries as GPL for internal usage only, so that they can be
> linked to other GPL libraries "legally". For instance, in the case of Daniel
> and his game company, they can link their proprietary game code to PyQt4 (Open
> source edition) to produce an internal tool, like a level editor, which would
> then fall under the GPL. If and only if they were to release that tool to the
> public (either for free or for sale), they would have to either go GPL and
> release full source code (include the parts of their game code linked to it),
> or buy a Qt commercial license.
>
> [[ Another page of similar babble is the one where they try to convince you
> that you cannot use the Qt Open Source edition to develop a software, and then
> buy the commercial edition only the day before you want to release it as non
> open-source. I can't even understand how they can even try to support such a
> nonsense position. You're free to develop your software for years as GPL
> without distributing it, and then relicense your own code whenever you want.
> They're obviously just trying to scare people. ]]
> --

Trolltech can do this because they won't sell you a commercial license
if they think you've been using the GPL version to develop. It's a
practical limitation, not a legal one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Kevin Walzer
hg wrote:
> Kevin Walzer wrote:
> 
>> Kevin Walzer wrote:
>>
>>> Tablelist: http://www.nemethi.de/
>>> Tabelist for Tkinter (with Tile support):
>>> http://tkinter.unpythonic.net/wiki/TableListTileWrapper
>>>
>> Additionally, here is a link to some screenshots for Tablelist:
>>
>> http://www.nemethi.privat.t-online.de/tablelist/screenshots.html
>>
>>
>> --
>> Kevin Walzer
>> Code by Kevin
>> http://www.codebykevin.com
> 
> Just for info - one of the reasons I stopped using Tkinter a few years ago
> was for the lack of print support (preview ...) - is there such an
> extension today ?
> 
> hg
> 
Printing is the one glaring omission from Tk/Tkinter--at least a unified
printing framework. There are platform-specific extensions for Mac and
Windows. On *Nix, I think most Tk/Tkinter programs just call lpr. None
of these libraries work in quite the same way, so there isn't a simple
way to simply call a standard Tk/Tkinter function to print your data.

This recent thread on comp.lang.tcl discusses the issue:

http://groups.google.com/group/comp.lang.tcl/browse_thread/thread/735c4612541f8669/707463acf6d02c46?

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rendering text question (context is MSWin UI Automation)

2007-01-24 Thread Chris Mellon
On 1/24/07, Boris Borcic <[EMAIL PROTECTED]> wrote:
> Chris Mellon wrote:
> >
> > Using either win32 or wxPython you will be able to produce bitmaps
> > directly, without needing to create a visible window.
> >
> >
> > Some quick & dirty wxPython code
> >
> > def getTextBitmap(text, font, fgcolor, bgcolor):
> > dc = wx.MemoryDC()
> > dc.SetFont(font)
> > width, height= dc.GetTextExtent(text)
> > bmp = wx.EmptyBitmap(width, height)
> > dc.SelectObject(bmp)
> > dc.SetBackground(wx.Brush(bgcolor))
> > dc.Clear()
> > dc.SetTextBackground(bgcolor)
> > dc.SetTextForeground(fgcolor)
> > dc.DrawText(text, 0, 0)
> > dc.SelectObject(wx.NullBitmap)
> > return bmp
> >
> >
> > Raw win32 code will look similar but will be much more verbose.
>
> Thx again for this base.
>
> Quickly testing this, it appears that the result is rendered half a pixel off 
> in
> the x-direction. Does this make sense ? Is it possible to position text with
> subpixel accuracy ?
>

The GDI text api, which is what wx is wrapping here, only provides
pixel accuracy. You are probably seeing a kerning effect from your
chosen font and perhaps the effects of ClearType.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread jean-michel bain-cornu
Hi
> 
> Just for info - one of the reasons I stopped using Tkinter a few years ago
> was for the lack of print support (preview ...) - is there such an
> extension today ?
> 
Same for me, it was a point for what I choosed wx.
Nowadays, I'd say users commonly accept to get pdf reports instead of 
direct printing, so it's not so much important.
Regards,
jm
-- 
http://mail.python.org/mailman/listinfo/python-list


module email

2007-01-24 Thread Sergey Dorofeev
Hello.

Why does not work?

--
import email.message
import smtplib
import time

m=email.message.Message()
m.set_type("multipart/mixed")
m["From"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
m["To"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
m["Date"]=time.asctime()
m["Subject"]="test"


p1=email.message.Message()
p1.set_payload("message text", "us-ascii")
m.attach(p1)

p2=email.message.Message()
p2.set_payload("message text 2", "us-ascii")
m.attach(p2)

del p1,p2

print m.as_string()
print "*"*50


x=email.message.Message()
x.set_type("multipart/mixed")
x["From"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
x["To"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
x["Date"]=time.asctime()
x["Subject"]="test"

p1=email.message.Message()
p1.set_payload("message text !", "us-ascii")
print p1
x.attach(p1)


p2=email.message.Message()
p2.set_type("message/rfc822")
p2.set_payload(m)
print p2
x.attach(p2)


print "*"*50
print x.as_string()

--

I'm using Python 2.5 


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


The blog on Pc trouble shooting skills,Networking,Linux

2007-01-24 Thread lucky
HI Friends
This blog is very useful to all sections of people.

For Pc trouble shooting skills,Linux,Html Webdesigning,Free
softwares,Networking skills,Gaming news and For Tips visit the blog:

http://technodata.blogspot.com

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


Regex for URL extracting

2007-01-24 Thread Johny
Does anyone know about a good regular expression  for URL extracting?

J.

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


Re: smtplib starttls gmail example - comments?

2007-01-24 Thread BJ Swope

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

Re: Thoughts on using isinstance

2007-01-24 Thread abcd
Well my example function was simply taking a string and printing, but
most of my cases would be expecting a list, dictionary or some other
custom object.  Still propose not to validate the type of data being
passed in?

Thanks.

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


Re: for thibaut: genuinely excellent pictures - umcu - (1/1)

2007-01-24 Thread [EMAIL PROTECTED]
Just inclined to fire up python to decode the latter part, just to
realise i've got dictd binding yet ;-)

Probably injected 2 instances of pythons in the spammer thread, for
completion's sake.

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


Re: Thoughts on using isinstance

2007-01-24 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, abcd wrote:

> Well my example function was simply taking a string and printing, but
> most of my cases would be expecting a list, dictionary or some other
> custom object.  Still propose not to validate the type of data being
> passed in?

Yes because usually you don't expect a list or dictionary but some object
that *acts* like a list or dictionary.  Or you even expect just some
aspects of the type's behavior.  For example that it is something you can
iterate over.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


The reliability of python threads

2007-01-24 Thread Carl J. Van Arsdall
Hey everyone, I have a question about python threads.  Before anyone 
goes further, this is not a debate about threads vs. processes, just a 
question.

With that, are python threads reliable?  Or rather, are they safe?  I've 
had some strange errors in the past, I use threading.lock for my 
critical sections, but I wonder if that is really good enough.

Does anyone have any conclusive evidence that python threads/locks are 
safe or unsafe?

Thanks,

Carl

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Regex for URL extracting

2007-01-24 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 "Johny" <[EMAIL PROTECTED]> wrote:

> Does anyone know about a good regular expression  for URL extracting?

Extracting URLs from what?

If it is HTML, then I'd look at some existing HTML parsing modules like 
Beautiful Soup and Barnes' HTMLData.

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The reliability of python threads

2007-01-24 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Carl J. Van Arsdall" <[EMAIL PROTECTED]> writes:
|> Hey everyone, I have a question about python threads.  Before anyone 
|> goes further, this is not a debate about threads vs. processes, just a 
|> question.
|> 
|> With that, are python threads reliable?  Or rather, are they safe?  I've 
|> had some strange errors in the past, I use threading.lock for my 
|> critical sections, but I wonder if that is really good enough.
|> 
|> Does anyone have any conclusive evidence that python threads/locks are 
|> safe or unsafe?

Unsafe.  They are built on top of unsafe primitives (POSIX, Microsoft
etc.)  Python will shield you from some problems, but not all.

There is precious little that you can do, because the root cause is
that the standards and specifications are hopelessly flawed.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not play well with others

2007-01-24 Thread Chris Mellon
On 1/23/07, John Nagle <[EMAIL PROTECTED]> wrote:
>The major complaint I have about Python is that the packages
> which connect it to other software components all seem to have
> serious problems.  As long as you don't need to talk to anything
> outside the Python world, you're fine.  But once you do, things
> go downhill.  MySQLdb has version and platform compatibility
> problems.  So does M2Crypto.  The built-in SSL support is weak.
> Even basic sockets don't quite work right; the socket module
> encapsulates the timeout mechanism but doesn't get it right.
>
>In the Perl, Java, PHP, and C/C++ worlds, the equivalent
> functions just work.   That's because, in those worlds, either the
> development team for the language or the development team
> for the subsystem takes responsibility for making them work.
> Only Python doesn't do that.
>
>Python has been around long enough that this should have
> been fixed by now.
>
> John Nagle

This just isn't correct. You think that socket libraries don't have
incompatibilities in C and that C++ libraries don't have versioning
problems? You think that SSL works right from Java in all cases, or
that changing your mysql client libraries underneath PHP won't affect
it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not play well with others

2007-01-24 Thread John Nagle
Harry George wrote:
> John Nagle <[EMAIL PROTECTED]> writes:

> You experience isn't shared by everyone.  Some of us find Python the
> most functional and portable of the candidates you mention.

The language is fine.  It's the bindings to other packages that
are the problem.  There are three different packages for talking
to OpenSSL, and they're all broken in some important way.

What's actually needed on the SSL side, I think, is to
add bindings to the built-in SSL to export the functionality
the M2Crypto C binding module has.  Preferably with better
attention to reference count problems, and without using SWIG.
Then move over the Python portions of M2Crypto.

Some problems, all of which are known and logged bugs:

- The built in SSL package doesn't actually validate anything,
and will happily accept bogus SSL certificates.
- The built in SSL package doesn't allow access to most of the
fields of an SSL certificate, and the ones you can get
are returned in a debug format that's not parseable.
- M2Crypto has OpenSSL and SWIG version dependencies beyond
what is documented.  The latest version of SWIG has
a problem which breaks builds with older versions of
OpenSSL.
- M2Crypto may still have a memory leak associated with contexts.
(Check out "close" in "Context".)
- M2Crypto doesn't understand SSL certificates which support
a list of sites.
- M2Crypto and the socket library don't play nice about timeouts.

Most of these problems have been known for years.  The last person to
try to fix this was treated so badly he stopped contributing.  Read
the bug history for "[1114345] Add SSL certificate validation".
It's sad.

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


Re: Thoughts on using isinstance

2007-01-24 Thread abcd
Well my example function was simply taking a string and printing, but
most of my cases would be expecting a list, dictionary or some other
custom object.  Still propose not to validate the type of data being
passed in?

Thanks.

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


Re: Simple Matrix class

2007-01-24 Thread Gabriel Genellina

At Wednesday 24/1/2007 02:40, Paul McGuire wrote:


> The points should be aligned on a log-log plot to be a power function.
> As Robert Kern stated before, this problem should be not worse than
> O(n**3) - how have you implemented it?
>
Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05
X 3**n.


So either reimplement it better, or place a notice in BIG letters to 
your users about the terrible time and memory penalties of using inverse()



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: The reliability of python threads

2007-01-24 Thread Chris Mellon
On 24 Jan 2007 17:12:19 GMT, Nick Maclaren <[EMAIL PROTECTED]> wrote:
>
> In article <[EMAIL PROTECTED]>,
> "Carl J. Van Arsdall" <[EMAIL PROTECTED]> writes:
> |> Hey everyone, I have a question about python threads.  Before anyone
> |> goes further, this is not a debate about threads vs. processes, just a
> |> question.
> |>
> |> With that, are python threads reliable?  Or rather, are they safe?  I've
> |> had some strange errors in the past, I use threading.lock for my
> |> critical sections, but I wonder if that is really good enough.
> |>
> |> Does anyone have any conclusive evidence that python threads/locks are
> |> safe or unsafe?
>
> Unsafe.  They are built on top of unsafe primitives (POSIX, Microsoft
> etc.)  Python will shield you from some problems, but not all.
>
> There is precious little that you can do, because the root cause is
> that the standards and specifications are hopelessly flawed.
>

This is sufficiently inaccurate that I would call it FUD. Using
threads from Python, as from any other language, requires knowledge of
the tradeoffs and limitations of threading, but claiming that their
usage is *inherently* unsafe isn't true. It is almost certain that
your code and locking are flawed, not that the threads underneath you
are buggy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on using isinstance

2007-01-24 Thread abcd
>Yes because usually you don't expect a list or dictionary but some object
> that *acts* like a list or dictionary.  Or you even expect just some
> aspects of the type's behavior.  For example that it is something you can
> iterate over.
>
> Ciao,
> Marc 'BlackJack' Rintsch

good point.  is there place that documents what methods/attrs I should
check for on an object?  for example, if its a list that I expect I
should verify the object that is passed in has a ??? function? etc.

thanks.

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


Re: Python does not play well with others

2007-01-24 Thread Chris Mellon
On 1/24/07, John Nagle <[EMAIL PROTECTED]> wrote:
> Harry George wrote:
> > John Nagle <[EMAIL PROTECTED]> writes:
>
> > You experience isn't shared by everyone.  Some of us find Python the
> > most functional and portable of the candidates you mention.
>
> The language is fine.  It's the bindings to other packages that
> are the problem.  There are three different packages for talking
> to OpenSSL, and they're all broken in some important way.
>
> What's actually needed on the SSL side, I think, is to
> add bindings to the built-in SSL to export the functionality
> the M2Crypto C binding module has.  Preferably with better
> attention to reference count problems, and without using SWIG.
> Then move over the Python portions of M2Crypto.
>
> Some problems, all of which are known and logged bugs:
>
> - The built in SSL package doesn't actually validate anything,
> and will happily accept bogus SSL certificates.
> - The built in SSL package doesn't allow access to most of the
> fields of an SSL certificate, and the ones you can get
> are returned in a debug format that's not parseable.
> - M2Crypto has OpenSSL and SWIG version dependencies beyond
> what is documented.  The latest version of SWIG has
> a problem which breaks builds with older versions of
> OpenSSL.
> - M2Crypto may still have a memory leak associated with contexts.
> (Check out "close" in "Context".)
> - M2Crypto doesn't understand SSL certificates which support
> a list of sites.
> - M2Crypto and the socket library don't play nice about timeouts.
>
> Most of these problems have been known for years.  The last person to
> try to fix this was treated so badly he stopped contributing.  Read
> the bug history for "[1114345] Add SSL certificate validation".
> It's sad.
>

Just to be clear: The problem here is "my personal itch is not being
scratched by other people for me", not "Python doesn't play well with
others". You are not any more important than anyone else and assuming
that anyone cares about your problems is a major fallacy. You have a
specific library that doesn't meet your needs, and that you are not
interested in maintaining yourself, so you are attempting to leverage
some sort of community guilt trip to get other people to do it for
you. That's dishonest and off-putting.

Not everyone has the ability or desire to contribute. That is fine.
They might even ask if anyone is interested in doing it for them,
which is also fine - there are many people who enjoy working on
something that is of use to others, even if it's not important to them
personally. But stop acting like you're entitled to special
consideration, or that the "Python community" is failing some sort of
duty by not catering to you specifically.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The reliability of python threads

2007-01-24 Thread skip

Carl> Does anyone have any conclusive evidence that python threads/locks
Carl> are safe or unsafe?

In my experience Python threads are generally safer than the programmers
that use them. ;-)

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


Re: sys.path issue in cygwin

2007-01-24 Thread Gabriel Genellina

At Wednesday 24/1/2007 04:58, Wang Shuhao wrote:

To keep the question simple, I've set PATH= in cygwin.bat to avoid 
python initialze sys.path from Windows' PATH environment.


The simple answer is that sys.path has nothing to do with the PATH 
environment variable.
sys.path is initialized from the location of the Python executable; 
PYTHONPATH can be used to prepend additional directories. You might 
set PYTHONHOME too, but for a standard installation its not needed - 
mainly for embedded interpreters where the running application is not 
python itself.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: smtplib starttls gmail example - comments?

2007-01-24 Thread Gabriel Genellina

At Wednesday 24/1/2007 09:12, BJ Swope wrote:


Both examples have included the cardinal sin in smtp...

They both send the message text followed by new line dot new line.

The smtp protocol specifically mentions CRLF dot CRLF.   Please 
please please use \r\n.\r\n in your code...


No. The SMTP object takes care of proper message ending (as it 
should). If you append \r\n.\r\n to the message, or whatever, that 
will be correctly quoted and sent as part of the message.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Python does not play well with others

2007-01-24 Thread Paul Boddie
On 24 Jan, 02:50, John Nagle <[EMAIL PROTECTED]> wrote:
>The major complaint I have about Python is that the packages
> which connect it to other software components all seem to have
> serious problems.  As long as you don't need to talk to anything
> outside the Python world, you're fine.

I think you're overstating your case here, since there is a lot of
Python code out there (much of it under the radar of many readers of
this newsgroup/list) whose purpose is precisely that of integration
with other software components. Having read what you've written
elsewhere with regard to SSL integration with Python, though, the
causes of the symptoms you're seeing are mostly correctly identified in
your own analysis.

>In the Perl, Java, PHP, and C/C++ worlds, the equivalent functions just 
> work.

We may have differing experiences here. Java stuff, in my experience,
usually needs lots of precisely versioned .jar files and then
frequently doesn't "just work". C and C++ aren't complete environments,
but there are admittedly some libraries/frameworks/environments based
on those languages which might provide solutions which often work
satisfactorily. I don't really want to think of the cocktail of
solutions available for Perl to solve any given problem, but people
often report that the quality varies somewhat between them.

>   That's because, in those worlds, either the
> development team for the language or the development team
> for the subsystem takes responsibility for making them work.
> Only Python doesn't do that.

And this is where I'd almost reach agreement with you. It's not enough
for the language to keep growing new features if the libraries are
broken or appear archaic, and this task seems to be outside the "core
developers" area of interest. Of course, people like you and I could
help update the libraries, although finding the time for making more
than just suggestions can be quite difficult, but the core developers
merely signalling that the libraries are a priority area for
development would probably lead to fewer people pushing their own
favourite syntax brush-ups or esoteric constructs, hopefully leading
some people (with enough time) to update, document and improve what's
already there.

Paul

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


Re: Noob Question: Force input to be int?

2007-01-24 Thread consmash


On 23 Sty, 10:59, [EMAIL PROTECTED] wrote:
> Hello everyone!
> I have a piece of code that looks like this:
>
> if len(BuildList) > 0:
> print "The script found %d game directories:" % len(BuildList)
> print
> num = 0
> for i in BuildList:
> print str(num) +"   " + i
> num = num + 1
> print
> print "Select a build number from 0 to " + str(len(BuildList) - 1)
> buildNum = int(raw_input('Select build #> '))
>
> while buildNum > (len(BuildList) -1) or buildNum <= -1:
> print
> print "Error: Invalid build number!"
> print "Select a build number from 0 to " + str(len(BuildList) -
> 1)
> print
> buildNum = int(raw_input('Select build: '))
>
> The problem is with the while buildNum-loop. If the user enters a
> non-numeric value in the buildNum input, the scripts throws an
> exception. I need to constrict the user to ONLY use integers in the
> input box. How can I solve this issue?

Also if you would like to try mentioned approach 'Look before you
leap', this code should be quite clear:

buildNumber = ('foo', 'bar')
n = len(buildNumber)
loop = True
while loop:
input = raw_input('select a build number from 0 to %d: ' % (n-1))
if input.isdigit():
ch = int(input)
loop = not ch in range(n)  # if ch is NOT in range of [0, n),
then it is ok to loop
if loop:
print 'Error! Invalid build number'
print 'Choice: %d' % ch

In fact I don't know if it applies to python, but in conventional
languages it is a bad habit to use exceptions for every simple test as
it takes time to jump around code. So, correct me please.

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


Python 2.5 and Zeus

2007-01-24 Thread Daniel Klein
Does anyone know if the Zeus IDE is compatible with Python 2.5?

I sent an email to Zeus a couple days ago but have not heard anything.

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


Re: Thoughts on using isinstance

2007-01-24 Thread Diez B. Roggisch
abcd wrote:

> good point.  is there place that documents what methods/attrs I should
> check for on an object?  for example, if its a list that I expect I
> should verify the object that is passed in has a ??? function? etc.

Don't check, try. Catch a possible exception, and continue with another type
assumption. The only thing one often checks is for basestring, as
basestring supports iteration, but more than often isn't supposed to be
iterated over. 

Small example to gather all strings out of a tree of objects (untested):

def foo(arg):
   # string case
   if isinstance(arg, basestring):
  return [arg]
   # dict-like
   try:
  res = []
  for value in arg.itervalues():
  res.extend(foo(value))
  return res
   except AttributeError:
  pass
   # generally iterables
   res = []
   for value in arg:
   res.extend(foo(value))
   return res

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


Re: Thoughts on using isinstance

2007-01-24 Thread Gabriel Genellina

At Wednesday 24/1/2007 14:21, abcd wrote:


>Yes because usually you don't expect a list or dictionary but some object
> that *acts* like a list or dictionary.  Or you even expect just some
> aspects of the type's behavior.  For example that it is something you can
> iterate over.
>
> Ciao,
> Marc 'BlackJack' Rintsch

good point.  is there place that documents what methods/attrs I should
check for on an object?  for example, if its a list that I expect I
should verify the object that is passed in has a ??? function? etc.


Don't insist on checking! :)
Just try to use the object - you'll get an exception at first invalid usage.

By example, a lot of functions take a file parameter to output 
something on it. Usually the *only* method called is write(). So any 
object with a write() method (taking a single string argument) would 
be fine; StringIO are an example. Checking if the argument is an 
instance of the file type would make that impossible.
Anyway, sometimes it's ok to check in advance - but please consider 
to check the *behavior* you expect, not the exact instance type. In 
the example above, you can validate that fileobject has a write 
attribute: getattr(fileobject, "write"). But I'd only do that if I 
have a good reason (perhaps if the file is used after some lengthy 
calculation,and I want to be sure that I will be able to store the result)



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: The reliability of python threads

2007-01-24 Thread Carl J. Van Arsdall
[EMAIL PROTECTED] wrote:
> Carl> Does anyone have any conclusive evidence that python threads/locks
> Carl> are safe or unsafe?
>
> In my experience Python threads are generally safer than the programmers
> that use them. ;-)
>   
Haha, yea, tell me about it.  The whole GIL thing made me nervous about 
the locking operations happening truly atomically and not getting 
weird.  Thanks for ensuring me that i'm just nuts :)

-carl

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: module email

2007-01-24 Thread Gabriel Genellina

At Wednesday 24/1/2007 13:02, Sergey Dorofeev wrote:


Why does not work?


Some details please?


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: The reliability of python threads

2007-01-24 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Chris Mellon" <[EMAIL PROTECTED]> writes:
|> > |>
|> > |> Does anyone have any conclusive evidence that python threads/locks are
|> > |> safe or unsafe?
|> >
|> > Unsafe.  They are built on top of unsafe primitives (POSIX, Microsoft
|> > etc.)  Python will shield you from some problems, but not all.
|> >
|> > There is precious little that you can do, because the root cause is
|> > that the standards and specifications are hopelessly flawed.
|> 
|> This is sufficiently inaccurate that I would call it FUD. Using
|> threads from Python, as from any other language, requires knowledge of
|> the tradeoffs and limitations of threading, but claiming that their
|> usage is *inherently* unsafe isn't true. It is almost certain that
|> your code and locking are flawed, not that the threads underneath you
|> are buggy.

I suggest that you find out rather more about the ill-definition of
POSIX threading memory model, to name one of the better documented
aspects.  A Web search should provide you with more information on
the ghastly mess than any sane person wants to know.

And that is only one of many aspects :-(


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on using isinstance

2007-01-24 Thread Duncan Booth
Gabriel Genellina <[EMAIL PROTECTED]> wrote:

> In 
> the example above, you can validate that fileobject has a write 
> attribute: getattr(fileobject, "write"). But I'd only do that if I 
> have a good reason (perhaps if the file is used after some lengthy 
> calculation,and I want to be sure that I will be able to store the
> result) 

Or even just:

   write = fileobject.write
   data = ... lengthy calculation here ...
   write(data)

There is no point using getattr when you know the name of the attribute in 
advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on using isinstance

2007-01-24 Thread Matthew Woodcraft
abcd <[EMAIL PROTECTED]> wrote:
> Well my example function was simply taking a string and printing, but
> most of my cases would be expecting a list, dictionary or some other
> custom object.  Still propose not to validate the type of data being
> passed in?


There are many people here who will indeed suggest that you're still
best off not validating.

There are various points to consider:

 - Not adding the validation code saves a certain amount of effort.

 - Not adding the validation code avoids one source of possible bugs.

 - Not adding the validation code can make your code more readable, in
   that there's that much less uninteresting code for your readers to
   skip before they get to the meat.

 - Adding the validation code can make your code more readable, in that
   it can be clearer to the readers what kind of values are being
   handled.

 - If you validate, you can raise an exception from the start of your
   function with a fairly explicit message. If you don't validate,
   you're likely to end up with an exception whose message is something
   like 'iteration over non-sequence', and it might be raised from some
   function nested several levels deeper in.

   The latter can be harder for the user of your function to debug (in
   particular, it may not be easy to see that the problem was an invalid
   parameter to your function rather than a bug in your function itself,
   or corrupt data elsewhere in the system).

 - If you don't validate, your function will accept anything that
   behaves sufficiently like a list/dictionary/custom-object for its
   purposes.

   You may consider this an advantage or a disadvantage. To some extent
   it depends on the circumstances in which the function is used: if
   someone passes a not-quite-a-file (say) to a function expecting a
   file, is it more likely that this is because of a subtle bug that
   they'll be pleased to learn about early, or that they wanted the
   function to 'do the obvious thing' with it?

 - In particular, suppose your function expects a list and someone
   passes a string when they should have passed a list containing only
   that string. If you don't validate, the function is likely to process
   the string the same way as it would process a list containing a
   number of single-character strings.

   This might well lead to your program apparently completing
   successfully but giving the wrong result (which is usually the kind
   of error you most want to avoid).

 - If the function is going to be maintained together with its callers
   (rather than being part of the public interface to a library, say),
   then validation code is less likely to get in the way, because it
   should be easy to relax the checks if that turns out to be
   convenient.


-M-

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


Re: The reliability of python threads

2007-01-24 Thread Chris Mellon
On 24 Jan 2007 18:21:38 GMT, Nick Maclaren <[EMAIL PROTECTED]> wrote:
>
> In article <[EMAIL PROTECTED]>,
> "Chris Mellon" <[EMAIL PROTECTED]> writes:
> |> > |>
> |> > |> Does anyone have any conclusive evidence that python threads/locks are
> |> > |> safe or unsafe?
> |> >
> |> > Unsafe.  They are built on top of unsafe primitives (POSIX, Microsoft
> |> > etc.)  Python will shield you from some problems, but not all.
> |> >
> |> > There is precious little that you can do, because the root cause is
> |> > that the standards and specifications are hopelessly flawed.
> |>
> |> This is sufficiently inaccurate that I would call it FUD. Using
> |> threads from Python, as from any other language, requires knowledge of
> |> the tradeoffs and limitations of threading, but claiming that their
> |> usage is *inherently* unsafe isn't true. It is almost certain that
> |> your code and locking are flawed, not that the threads underneath you
> |> are buggy.
>
> I suggest that you find out rather more about the ill-definition of
> POSIX threading memory model, to name one of the better documented
> aspects.  A Web search should provide you with more information on
> the ghastly mess than any sane person wants to know.
>
> And that is only one of many aspects :-(
>

I'm aware of the issues with the POSIX threading model. I still stand
by my statement - bringing up the problems with the provability of
correctness in the POSIX model amounts to FUD in a discussion of
actual problems with actual code.

Logic and programming errors in user code are far more likely to be
the cause of random errors in a threaded program than theoretical
(I've never come across a case in practice) issues with the POSIX
standard.

Emphasizing this means that people will tend to ignore bugs as being
"the fault of POSIX" rather than either auditing their code more
carefully, or avoiding threads entirely (the second being what I
suspect your goal is).

As a last case, I should point out that while the POSIX memory model
can't be proven safe, concrete implementations do not necessarily
suffer from this problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type casting a base class to a derived one?

2007-01-24 Thread Cliff Wells
On Thu, 2007-01-11 at 08:41 -0600, Chris Mellon wrote:
> On 11 Jan 2007 15:01:48 +0100, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > On 2007-01-11, Frederic Rentsch <[EMAIL PROTECTED]> wrote:
> > > If I derive a class from another one because I need a few extra
> > > features, is there a way to promote the base class to the
> > > derived one without having to make copies of all attributes?
> > >
> > > class Derived (Base):
> > >def __init__ (self, base_object):
> > >   # ( copy all attributes )
> > >   ...
> > >
> > > This looks expensive. Moreover __init__ () may not be available
> > > if it needs to to something else.
> > >
> > > Thanks for suggestions
> >
> > How does it make sense to cast a base to a derived in your
> > application?
> >
> 
> I can't figure out any circumstance when you'd need to do this in
> Python. Upcasting like this is something you do in statically typed
> languages. I suspect that the OP doesn't really believe dynamic
> casting works and doesn't want to pass a derived class for some
> reason.

I actually encountered a need to do so (and I recalled seeing this
thread which is why I'm replying to it now).  I've got a dispatch system
based on object type.  Objects come from an external source (an ORM), so
I can't efficiently set their types at the point of creation (nor would
I necessarily want to).  However, in different contexts, I may want them
to be dispatched differently (i.e as if they are a different type).  In
fact, often the same object will be handled differently within two or
more contexts during the lifetime of that object.  It would be nice to
be able to cast them to a derived class (which actually adds no new
methods or attributes, just changes the type) at that exact moment to
cause the dispatcher to handle them differently.

Now, that being said, it's quite possible the system *could* have been
designed to not dispatch based on type, but quite frankly it works quite
elegantly and naturally for everything but this one case.

Just pointing out that just because we don't see a need for something
doesn't invalidate it.  It just makes it something we had thought of ;-)
  

Regards,
Cliff



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


Re: The reliability of python threads

2007-01-24 Thread Carl J. Van Arsdall
Chris Mellon wrote:
> On 24 Jan 2007 18:21:38 GMT, Nick Maclaren <[EMAIL PROTECTED]> wrote:
>   
>> [snip]
>>
>> 
>
> I'm aware of the issues with the POSIX threading model. I still stand
> by my statement - bringing up the problems with the provability of
> correctness in the POSIX model amounts to FUD in a discussion of
> actual problems with actual code.
>
> Logic and programming errors in user code are far more likely to be
> the cause of random errors in a threaded program than theoretical
> (I've never come across a case in practice) issues with the POSIX
> standard.
>   
Yea, typically I would think that.  The problem I am seeing is 
incredibly intermittent.  Like a simple pyro server that gives me a 
problem maybe every three or four months.  Just something funky will 
happen to the state of the whole thing, some bad data, i'm having an 
issue tracking it down and some more experienced programmers mentioned 
that its most likely a race condition.  THe thing is, I'm really not 
doing anything too crazy, so i'm having difficult tracking it down.  I 
had heard in the past that there may be issues with threads, so I 
thought to investigate this side of things. 

It still proves difficult, but reassurance of the threading model helps 
me focus my efforts.

> Emphasizing this means that people will tend to ignore bugs as being
> "the fault of POSIX" rather than either auditing their code more
> carefully, or avoiding threads entirely (the second being what I
> suspect your goal is).
>
> As a last case, I should point out that while the POSIX memory model
> can't be proven safe, concrete implementations do not necessarily
> suffer from this problem.
>   
Would you consider the Linux implementation of threads to be concrete?

-carl

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Simple Matrix class

2007-01-24 Thread Paul McGuire
On Jan 24, 11:21 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Wednesday 24/1/2007 02:40, Paul McGuire wrote:
>
> > > The points should be aligned on a log-log plot to be a power function.
> > > As Robert Kern stated before, this problem should be not worse than
> > > O(n**3) - how have you implemented it?
>
> >Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05
> >X 3**n.
>
> So either reimplement it better, or place a notice in BIG letters to
> your users about the terrible time and memory penalties of using inverse()
>

Well, really, the "terrible time and memory penalties" aren't all that
terrible for matrices up to, oh, 10x10 or so, but you wouldn't want to
use this on anything much larger than that.  Hey, guess what?!  That's
exactly what I said in my original post!

And the purpose/motivation for "reimplementing it better" would be
what, exactly?  So I can charge double for it?  As it was, I felt a
little guilty for posting a solution to such a likely homework
assignment, but now there's room for a student to implement a kickass
inverter routine in place of the crappy-but-useful-for-small-matrices
brute force one I've written.

Cubs win!
-- Paul

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


Re: Type casting a base class to a derived one?

2007-01-24 Thread Chris Mellon
On 1/24/07, Cliff Wells <[EMAIL PROTECTED]> wrote:
> On Thu, 2007-01-11 at 08:41 -0600, Chris Mellon wrote:
> > On 11 Jan 2007 15:01:48 +0100, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > > On 2007-01-11, Frederic Rentsch <[EMAIL PROTECTED]> wrote:
> > > > If I derive a class from another one because I need a few extra
> > > > features, is there a way to promote the base class to the
> > > > derived one without having to make copies of all attributes?
> > > >
> > > > class Derived (Base):
> > > >def __init__ (self, base_object):
> > > >   # ( copy all attributes )
> > > >   ...
> > > >
> > > > This looks expensive. Moreover __init__ () may not be available
> > > > if it needs to to something else.
> > > >
> > > > Thanks for suggestions
> > >
> > > How does it make sense to cast a base to a derived in your
> > > application?
> > >
> >
> > I can't figure out any circumstance when you'd need to do this in
> > Python. Upcasting like this is something you do in statically typed
> > languages. I suspect that the OP doesn't really believe dynamic
> > casting works and doesn't want to pass a derived class for some
> > reason.
>
> I actually encountered a need to do so (and I recalled seeing this
> thread which is why I'm replying to it now).  I've got a dispatch system
> based on object type.  Objects come from an external source (an ORM), so
> I can't efficiently set their types at the point of creation (nor would
> I necessarily want to).  However, in different contexts, I may want them
> to be dispatched differently (i.e as if they are a different type).  In
> fact, often the same object will be handled differently within two or
> more contexts during the lifetime of that object.  It would be nice to
> be able to cast them to a derived class (which actually adds no new
> methods or attributes, just changes the type) at that exact moment to
> cause the dispatcher to handle them differently.
>

In Python, you can do this simply by re-assigning the __class__. I'm
not convinced that your type system makes sense, here though. Any
reasonable ORM should be able to persist and reload an object without
losing the type information. Perhaps it's just a blind spot in the way
I think about types. Assuming that the limitations of your ORM are
external and out of your control, I would still ensure that whatever
generic objects are being loaded from the ORM are converted into
"real" objects of the correct type as soon as possible. For example,
if you're persisting a file, you might just save the filename, and
your ORM might return a string of the filename. I would want to
convert that back into a file object ASAP, rather than writing all my
code to accept either a FLO or a string and converting then.

If you know what to upcast something to, then you know what type it
is. If you know what type it is, then (in Python) you can simply
assume it is of that type.

What you're describing is a disjoint between your actual type system
(that is, the one you have in code) and your theoretical type system
(the one that you model your code around). To me, this is a huge red
warning flag.

> Now, that being said, it's quite possible the system *could* have been
> designed to not dispatch based on type, but quite frankly it works quite
> elegantly and naturally for everything but this one case.
>

Dispatch on type is perfectly natural. I'm not arguing against that,
I'm arguing against the idea that it makes sense, in Python, to
upcast.

> Just pointing out that just because we don't see a need for something
> doesn't invalidate it.  It just makes it something we had thought of ;-)
>

I agree, but without a use case it's hard to understand the limits and
needs of a requirement. So if you can't think of a need for a feature,
it becomes difficult to understand how you might implement that
feature.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex for URL extracting

2007-01-24 Thread Paul McGuire
On Jan 24, 10:20 am, "Johny" <[EMAIL PROTECTED]> wrote:
> Does anyone know about a good regular expression  for URL extracting?
>
> J.
Google turns this up:

http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx

But I've seen other re's for this problem that are hundreds of
characters long.

-- Paul

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-24 Thread Harry George
"Chris Mellon" <[EMAIL PROTECTED]> writes:

> On 1/24/07, Giovanni Bajo <[EMAIL PROTECTED]> wrote:
[snip]
> >
> > That page is legal babble, trying to trick you into buying (or making your
> > boss buy) a commercial license. The Qt Open Source edition *IS* GPL and thus
> > it falls under all the normal GPL clauses and uses, irrespective of what
> > Trolltech may or may not think.
> >
> > For instance, see this FAQ:
> > http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic
> >
> > which makes pretty clear that a "company"/"organization" is basically the 
> > same
> > of an "individual". "Releasing a software within a company for internal 
> > usage"
> > is by no means the same of "releasing it to the public". Basically, for what
> > the GPL is concerned, it is *not* a "release" or a "distribution" at all.
> >
> 
> I should point out that the FSFs position in this regard is not
> supported by copyright law and that the fact that Trolltech takes a
> different position is something that you should consider strongly. If
> the FSFs position were true, there would be no need for per-seat
> licensing of commercial software (because internal distribution
> wouldn't be). US copyright law does not draw a distinction between
> "internal distribution" and any other kind, and I'm not aware of any
> case law that does so either. This distinction is also not codified in
> the GPL itself anywhere, so it's not a necessary condition of the
> license - it is an interpretation by the FSF and that is all.
[snip]

It is all interpretation -- even after some cases have wandered
through the courts.  Mostly the trolltech statements indicate their
intent to sue.  That right there tells me I want to go elsewhere.


-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


newbie - returned values from cscript.exe

2007-01-24 Thread Rich
I am writing my first python script and I'm guessing this is something
obvious but I can't find any examples of doing something like this.  I
have a python script that is running a vbscript through cscript.exe.
The vbscript looks up a server name, username, password etc and returns
these values in a delimited list using wscript.echo.  I can assign
these values to variables using a Windows batch files with the
following code

FOR /F "tokens=1-6" %%a in ('cscript /nologo GetServerAccessInfo.vbs"')
do (
SET DB_SERVER_NAME=%%a
SET DB_NAME=%%b
SET NMDBO_USERNAME=%%c
SET NMDBO_PASSWORD=%%d
SET SU_USERNAME=%%e
SET SU_PASSWORD=%%f

I can't figure out how to do the same thing using a python script to
call this instead of a batch file.

I am running the vbscript by using the following command
os.system('cscript /nologo GetServerAccessInfo.vbs')

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


Re: Type casting a base class to a derived one?

2007-01-24 Thread Cliff Wells
On Wed, 2007-01-24 at 12:57 -0600, Chris Mellon wrote:

> 
> In Python, you can do this simply by re-assigning the __class__. I'm
> not convinced that your type system makes sense, here though. Any
> reasonable ORM should be able to persist and reload an object without
> losing the type information. Perhaps it's just a blind spot in the way
> I think about types. Assuming that the limitations of your ORM are
> external and out of your control, I would still ensure that whatever
> generic objects are being loaded from the ORM are converted into
> "real" objects of the correct type as soon as possible. For example,
> if you're persisting a file, you might just save the filename, and
> your ORM might return a string of the filename. I would want to
> convert that back into a file object ASAP, rather than writing all my
> code to accept either a FLO or a string and converting then.
> 
> If you know what to upcast something to, then you know what type it
> is. If you know what type it is, then (in Python) you can simply
> assume it is of that type.

Probably being more specific would help in this case ;-)

What I'm doing is implementing an object-publishing mechanism in my
template engine (Breve).  The type decision isn't known until the moment
of rendering (i.e. in the template itself).  Say for instance a set of
records is pulled from the ORM (SQLAlchemy in this case) and that these
records represent articles in a blog.  These records, until they hit the
template, have no real representation in HTML.  The decision about how
to present them is up to the template.  The dispatch mechanism I
referred to earlier is a way that I allow users of the template system
to register how a particular object should be rendered in HTML (a
"flattener").  This allows commonly represented objects to be used
without a lot of template clutter.
However, if you consider the case of a blog, then if the template
receives a list of articles, it would seem reasonable to present those
articles in at least two ways: first as a table of contents in the page
gutter, and then perhaps as two or three summaries in the main part of
the page.  But this isn't known to the lower layers of the application,
only to the template.  Therefore it would be nice if the template user
could register two classes with the flattener, both representations of
the original object but simply with a different type.  

I'll give a concrete example:

class Person: # assume this is something from the ORM
name = "Kenny"

class PersonRow ( Person ):
pass

def flatten_person ( p ):
return "omg, you've killed %p" % p.name

def flatten_personrow ( p ):
return "%s" % p.name

register_flattener ( PersonRow, flatten_personrow )
register_flattener ( Person, flatten_person )


Now, assuming a list of Person records were passed in as 'persons', then
in the template the template author could simply use:

div [
# show the first person
persons [ 0 ],

# show a table of all persons
table [
[ PersonRow ( p ) for p in persons ]
]
]


> What you're describing is a disjoint between your actual type system
> (that is, the one you have in code) and your theoretical type system
> (the one that you model your code around). To me, this is a huge red
> warning flag.

What I'm describing is a disjoint between how I want my template engine
to be used (I tend to build backwards, writing the desired template code
and then the engine code to support that use) and what can be easily and
efficiently achieved.  But yes, in a way you are correct since my
theoretical type system is constrained by Python's type system (Breve
templates are Python expressions).

That being said, I'm certain I'll come up with a solution that doesn't
bug me too much, it's just that the "obvious" solution doesn't exist
(type casting).

> I'm arguing against the idea that it makes sense, in Python, to
> upcast.

I think it's definitely a corner-case, but I'd be reluctant to claim it
would never be of use.

> I agree, but without a use case it's hard to understand the limits and
> needs of a requirement. So if you can't think of a need for a feature,
> it becomes difficult to understand how you might implement that
> feature.

Certainly.  Several years of using Python has never suggested a use to
me prior to this.

Regards,
Cliff


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


Re: Thoughts on using isinstance

2007-01-24 Thread Bruno Desthuilliers
Matthew Woodcraft a écrit :
> abcd <[EMAIL PROTECTED]> wrote:
> 
>>Well my example function was simply taking a string and printing, but
>>most of my cases would be expecting a list, dictionary or some other
>>custom object.  Still propose not to validate the type of data being
>>passed in?
> 
> 
> 
> There are many people here who will indeed suggest that you're still
> best off not validating.
> 
> There are various points to consider:
> 
>  - Not adding the validation code saves a certain amount of effort.

Yes

>  - Not adding the validation code avoids one source of possible bugs.

Yes

>  - Not adding the validation code can make your code more readable, in
>that there's that much less uninteresting code for your readers to
>skip before they get to the meat.

Yes

>  - Adding the validation code can make your code more readable, in that
>it can be clearer to the readers what kind of values are being
>handled.

This is better expressed in the docstring. And if it's in the docstring, 
you can't be blamed for misuse.

>  - If you validate, you can raise an exception from the start of your
>function with a fairly explicit message. If you don't validate,
>you're likely to end up with an exception whose message is something
>like 'iteration over non-sequence', and it might be raised from some
>function nested several levels deeper in.

And what is the stack backtrace for, actually ?

>The latter can be harder for the user of your function to debug (in
>particular, it may not be easy to see that the problem was an invalid
>parameter to your function rather than a bug in your function itself,
>or corrupt data elsewhere in the system).

docstrings and unit-tests should make it clear.

>  - If you don't validate, your function will accept anything that
>behaves sufficiently like a list/dictionary/custom-object for its
>purposes.

Yes

>You may consider this an advantage or a disadvantage. To some extent
>it depends on the circumstances in which the function is used: if
>someone passes a not-quite-a-file (say) to a function expecting a
>file, is it more likely that this is because of a subtle bug that
>they'll be pleased to learn about early, or that they wanted the
>function to 'do the obvious thing' with it?

Python's POV on this is quite clear IMHO. Now if one want to have to 
declare everything three times and write layers and layers of adapters 
and wrappers, well, he knows where to find Java !-)

>  - In particular, suppose your function expects a list and someone
>passes a string when they should have passed a list containing only
>that string. If you don't validate, the function is likely to process
>the string the same way as it would process a list containing a
>number of single-character strings.

Yes. This is a very common Python gotcha. And one that is usually quite 
easy to spot and fix, even manually (let's not talk about unit-tests).

>This might well lead to your program apparently completing
>successfully but giving the wrong result (which is usually the kind
>of error you most want to avoid).

Compared to what C or C++ can do to your system, this is still a pretty 
minor bug - and probably one of the most likely to be detected very 
early (did I talk about unit tests ?).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Matrix class

2007-01-24 Thread Robert Kern
Paul McGuire wrote:
> And the purpose/motivation for "reimplementing it better" would be
> what, exactly?  So I can charge double for it?

So you can have accurate results, and you get a good linear solver out of the
process. The method you use is bad in terms of accuracy as well as efficiency.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Type casting a base class to a derived one?

2007-01-24 Thread Cliff Wells
On Wed, 2007-01-24 at 11:37 -0800, Cliff Wells wrote:

> 
> class Person: # assume this is something from the ORM
> name = "Kenny"
> 
> class PersonRow ( Person ):
> pass
> 
> def flatten_person ( p ):
> return "omg, you've killed %p" % p.name
> 
> def flatten_personrow ( p ):
> return "%s" % p.name
> 
> register_flattener ( PersonRow, flatten_personrow )
> register_flattener ( Person, flatten_person )
> 
> 
> Now, assuming a list of Person records were passed in as 'persons', then
> in the template the template author could simply use:
> 
> div [
> # show the first person
> persons [ 0 ],
> 
> # show a table of all persons
> table [
> [ PersonRow ( p ) for p in persons ]
> ]
> ]
> 

I should add that the reason I don't want to just say, call
flatten_personrecord() directly from the template (which would be a
reasonable solution in this example) is because I have a longer-term
goal that would require an object at that point.

What I expect I'll end up doing is using a factory function that returns
the desired object at that point, but it will require a bit more
explanation at the template level than I'd like:

table [
[ render_as ( PersonRow, p ) for p in persons ]
]

or something similar.


Regards,
Cliff

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


Re: Thoughts on using isinstance

2007-01-24 Thread Bruno Desthuilliers
abcd a écrit :
> Well my example function was simply taking a string and printing, but
> most of my cases would be expecting a list, dictionary or some other
> custom object.  Still propose not to validate the type of data being
> passed in?

Yes - unless you have a *very* compelling reason to do otherwise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Windows Editors

2007-01-24 Thread Hertha Steck
Am Mon, 22 Jan 2007 00:33:12 + schrieb W. Watson:

> [EMAIL PROTECTED] wrote:
>> W. Watson wrote:
>>> I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I
>>> understand there's a Win editor called pythonwin. I believe it's in the
>>> download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has
>>> just the editor or all of Python. Comments? If not how do I get the
>>> PythonWin editor by itself?

By "IDE" you mean IDLE, don't you?

>> 
>> Print your files from Notepad, after all, they're just text files.
>> But IDLE has more usefull Formatting options.
> Thanks. Already did it, but used Word. I can get line numbers in that way.

And you are absolutely certain you won't never, ever, detect a typo when
you have your script open in Word, correct it, save the file and try to
use the resulting mess as a Python script? Or does Word leave it as a text
file in such a case? I never dare to open source code in Word, so I'm not
really sure.

Hertha

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


  1   2   3   >