Re: return image in mod python

2007-11-22 Thread Peter Otten
Abandoned wrote:

> Hi i have a problem.
> 
> def showimage(req):
> from PIL import Image
> im=Image.open("c:\image-2.jpg")
> im.thumbnail((800,600), Image.ANTIALIAS)
> req.sendfile(im)
> 
> 
> 
> give me some error.
> How can i return this image witdhout save ?

image = Image.open(...)
image.thumbnail(...)
req.content_type = "image/jpeg"
image.save(req, "jpeg")

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


Re: eof

2007-11-22 Thread Hendrik van Rooyen
"braver" <[EMAIL PROTECTED]> wrote:


> Well folks compare scripting languages all the time, and surely Ruby
> is closer to Python than C++.  Since Ruby can do f.eof, which is
> easily found in its references, and Python can't, or its EOF can't
> easily be found -- the one *equivalent* to a semantically clear
> Ruby's, or Pascal's IIRC, f.eof -- something's missing here...
> 
> Why do I have to count sizes of lines read and compare it to some
> filesize or do other weird tricks just to see, in a way not changing
> my input stream, whether it's at the, well, EOF?

The man has a valid point - 

In general, Python allows you, for an object f,
to write:

f.SomethingNew = 'Whatever the hell you like'

However, when f is a builtin file object,
it barfs on an AttributeError.

So he can't even help himself by setting his
own EOF attribute to False initially, and
to True when he sees an empty string.

Is there a reason for this Bondage style?

- Hendrik

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


Re: the annoying, verbose self

2007-11-22 Thread A.T.Hofkamp
On 2007-11-22, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Wed, 21 Nov 2007 15:51:56 -0800, braver wrote:
>
>> Is there any trick to get rid of having to type the annoying,
>> character-eating "self." prefix everywhere in a class?

You got this highly flexible language, very good for rapid programming, no more
clutter from block brackets and variable declarations, and now this 'self' pops
up.

So much overhead

Can the computer not decide by itself what I want stored in the object? It can
read my code too!


> Oh I know! It' uch a pain. Sinc writing a hug cla lat wk, I'v had a 
> trribl hortag o lowrca S E L and F charactr. It mak writing vry annoying.

Yes annoying isn't it?

Last week I was programming in C++ again, and now I have this terrible sur-plus
of lowercase T H I and S letters. I don't understand how they do it (I used to,
but not any more).

Maybe we should setup an exchange program so everybody can trade letters with
each other.


>> Sometimes I avoid OO just not to deal with its verbosity.
>
> There are other values than brevity. In fact, brevity is one of the less 
> important values.

NO! You got it all wrong here! It is not about brevity, it is about SPEED.

With less letters, there is less to read, so it can be read faster, so it must
be better!

Just like "if x:" is MUCH BETTER than "if x != 0:"


The thing that should be fixed imho, is that the brain of some of us tries to
deduce higher levels of abstractions from what is essentially a very long line
of simple instructions.


>> But things grow -- is there any metaprogramming tricks or whatnot we can
>> throw on the self?
>
> Oh yeah, that's just what I like to see! Complicated, brittle, hard to 
> debug, difficult to understand metaprogramming tricks in preference to a 
> simple, easy-to-read naming convention.

Maybe we should state first which variables we want to store in self, and then
have a meta-programming hook that automatically puts assignments to those
variables into the object.
And while we are at it, maybe we should also state the type of data we want to
put in it. That should help too.

Now that would be progress.


Ah well, I guess we will have to wait a while before that happens.
Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why it is invalid syntax?

2007-11-22 Thread Stef Mientki
alf wrote:
> Hi,
> 
> I wonder why it is an invalid syntax:
> 
> 
>  >>> if 1: if 1: if 1: print 1
>   File "", line 1
> if 1: if 1: if 1: print 1
> 
> 
> or
> 
>  >>> if 1: for i in range(10): print i
>   File "", line 1
> if 1: for i in range(10): print i
> 
> I would expect one could nest :
> 
> 

Although I agree it might be quit unreadable for normal programmers,
people who are used to writing math formula, (i.e. MatLab),
this is not true.

Here another interesting one, that is accepted:

 self.nodes.extend ( [ ONode(shape,n,self) \
   for n in range(shape.Parent.N_Outputs) \
   if shape.Type_Outputs[n] == type ] )

cheers,
Stef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging and propagation

2007-11-22 Thread oj
On Nov 22, 5:44 am, Vinay Sajip <[EMAIL PROTECTED]> wrote:
> On Nov 21, 11:38 am, oj <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > I want to setuploggingwith two loggers:
>
> > The child logger is used when something different needs to be done
> > with the log record, and the log record will propagate and be logged
> > by the root logger as usual.
>
> > However, there are certain times when I don't want a log record to
> > propagate from the child to the parent.
>
> > I don't really want to add a filter to the root logger, as it should
> > be up to the child whether the record propagates or not.
>
> > I've tried setting the child to a lower level then the parent, but if
> > a record is dealt with by the child, the parent deals with it anyway
> > regardless of its own log level.
>
> > Also, filters only apply particular handlers and do not affect
> > propagation.
>
> > Can anyone suggest a simple way to achieve this?
>
> > Currently, the only thing I can think of, is overriding the
> > callHandlers method in a custom Logger class.
>
> Do you already have a Logger subclass? Where and when is the decision
> being made about whether to propagate or not?

The decision is being made in a filter. Certain log records are dealt
with differently from there.

The filter also prevents the handler from dealing with those log
records, but it doesn't stop the handlers of parent loggers dealing
with them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread braver
On Nov 22, 10:37 am, Wayne Brehaut <[EMAIL PROTECTED]> wrote:

> As others have already pointed out, "because it's seldom necessary in Python".

You know what?  I've read this many times, and it's a lot of self-
congratulation.  There's lot of things which can be useful in Python.

This lack of EOF is inconvenient, there's nothing "Python way" about
it, as a simple search on "EOF" or "eof" in this group demonstrates.
Just a few threads:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ed25388487b3ac7b

Here folks fight the same problem in one way uglier than another.
Iterators and whatnot are thrown at a poor li'l EOF:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b09d612e99f67561

The recurrence of the question simply shows Python lacks an f.eof()
method.  That's all!

Why do we may need it?  The last thread shows clearly -- because the
last line processing is often a special case.  After I couldn't find
the f.eof() in Python docs, I've quickly changed the logic to this
(extracts):

filesize = os.stat(filename)[6]
cur_size = 0

def eof():
return cur_size == filesize

def add_line(line):
self.cur_size += len(line)
   ...
if eof():
print >>sys.stderr, "* * * eof * * *"

Basically, it allows me to write what I want, and it's natural to ask
for eof() in this case -- and for a language to provide it.  Ruby has
all iterators-schmiterators you want and a kitchen sink, yet provides
the said eof() without much fuss and 100 threads on c.l.*.  :)

> "Python is not Ruby."

Both Python and Ruby happily agree here:
>> "Python" == "Ruby"
=> false
In [11]: "Python" == "Ruby"
Out[11]: False

There's nothing special about Python except indentation, which gets
screwed up between editors all the time.  (It's much easier to flip-
flop between TextMate and Emacs with Ruby than with Python, without
setting your tabs and spaces pedantically.)  It's faster than Ruby,
otherwise they're similar.  When Ruby X.Y gets faster, it'll be a
tough call to between 'em.  I use Python to accomplish things I know
how, with algorithms which work and proven control logic, so this is
reasonable to ask about certain control flow equivalents.  And
comparisons will always be good.  :)

Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next float?

2007-11-22 Thread Fredrik Johansson
On Nov 22, 2007 4:04 AM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> Is there a simple, elegant way in Python to get the next float from a
> given one? By "next float", I mean given a float x, I want the smallest
> float larger than x.
>
> Bonus points if I can go in either direction (i.e. the "previous float"
> as well as the next).
>
> Note to maths pedants: I am aware that there is no "next real number",
> but floats are not reals.
> --
> Steven

You could use the library functions for floating-point math in mpmath
(http://code.google.com/p/mpmath/), which support directed rounding.
Load a floating-point number, add a tiny number and round in the
wanted direction, then convert back to a Python float:

>>> from mpmath.lib import *
>>> eps = (1, -2000, 1)# 2**-2000, smaller than any finite
positive IEEE 754 double
>>> a = from_float(1.0, 53, ROUND_HALF_EVEN) # note: exact
>>> to_float(fadd(a, eps, 53, ROUND_UP))
1.0002
>>> to_float(fsub(a, eps, 53, ROUND_DOWN))
0.99989

This currently probably doesn't work if the numbers are subnormal, however.

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


RE: Please help in creating Python function in C ++ program

2007-11-22 Thread Borse, Ganesh
Hi,
Yes I agree. After compile() this is "*definition*" of that function.
I would like to know, how can we use this code object & call it as a function?
May be - how do we convert this Code Object to Function Object to work as 
Callable Object?

Thanks & Regards
Ganesh
-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] 
Sent: 22 November 2007 15:07
To: Borse, Ganesh
Cc: python-list@python.org
Subject: Please help in creating Python function in C ++ program

Forwarded to python-list@python.org

--- "Borse, Ganesh" <[EMAIL PROTECTED]>
escribió:

> Hi,
> 
> I am new to Python. I would like to use Python for the specialized 
> purpose of dynamic expressions parsing & evaluation in my C++ 
> application.
> I would like to encapsulate the expressions to be evaluated in Python 
> function & compile that function at runtime, somewhat as below.
>   Expression to eval put in Python function 
>   def isSizeSmall(size,vol,ADV,prod):
> if ( (size < 1000) & (vol < (0.001 * ADV)) &
> (prod=="Stock")): print "OK"; return 10
> else: print "NOK"; return 11
> 
> Then, I want to evaluate the PyObject returned by Py_CompileString 
> multiple times in my program using the user input as the variables to 
> the above function.
> This I tried using two different approaches - 1) PyEval_evalCode, & 2) 
> PyObject_CallObject.
> 
> 1) When using PyEval_evalCode: The function call to PyEval_evalCode 
> was ok, but it did not return any output.
> 2) Whereas, when I used this object with PyObject_CallObject, it 
> failed with error as "".
> 
> Any help will be great. Many thanks in advance for your help.
> 
> Warm Regards,
> Ganesh
> 
> //***//
> Output of my test program:
> Expression to eval =
> [def isSizeSmall(size,vol,ADV,prod):
>   if ( (size < 1000) & (vol < (0.001 * ADV)) &
> (prod=="Stock")): print "OK"; return 10
>   else: print "NOK"; return 11
> 
> ]
> str compiled fine with stdin & Py_file_input, calling PyEval_EvalCode 
> None ok [0] size [-1]
> 
> str compiled fine with stdin & Py_file_input, calling PyFunction_New & 
> then PyObject_CallObject Getting PyFunction_New Calling 
> PyObject_CallObject func is callable
> TypeError: ?() takes no arguments (4 given)
> 
> My test program having both above approaches is as
> below:
> main(int argc, char **argv)
> {
>/* Pass argv[0] to the Python interpreter */
>Py_SetProgramName(argv[0]);
>/* Initialize the Python interpreter.  Required.
> */
>Py_Initialize();
>PyRun_SimpleString("import sys\n");
> 
>char szExpr[2048];
>memset(szExpr,'\0',sizeof(szExpr));
>sprintf(szExpr,"def
> isSizeSmall(size,vol,ADV,prod):\n  if ( (size <
> 1000) & (vol < (0.001 * ADV)) & (prod==\"Stock\")):
> print \"OK\"; return 10\n  else: print \"NOK\"; return 11\n\n\n");
> 
>printf("Expression to eval = \n[%s]\n",szExpr);
> 
>OrderValues ordval;
>ordval.size = 100;
>ordval.ADV  = 10;
>ordval.vol  = 1000;
>memset(ordval.prod,'\0',sizeof(ordval.prod));
>sprintf(ordval.prod,"Stock");
> 
> 
>PyObject *glb, *loc;
> 
>glb = PyDict_New();
>PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins());
> 
>loc = PyDict_New();
> 
>PyObject* tuple = PyTuple_New(4);
>PyObject* val = 0;
> 
>val = PyInt_FromLong(ordval.size);
>PyTuple_SetItem(tuple,0,val);
>PyDict_SetItemString(loc,"size",val);
> 
>val = PyInt_FromLong(ordval.vol);
>PyTuple_SetItem(tuple,1,val);
>PyDict_SetItemString(loc,"vol",val);
> 
>val = PyInt_FromLong(ordval.ADV);
>PyTuple_SetItem(tuple,2,val);
>PyDict_SetItemString(loc,"ADV",val);
> 
>val = PyString_FromString(ordval.prod);
>PyTuple_SetItem(tuple,3,val);
>PyDict_SetItemString(loc,"prod",val);
> 
> 
> /*** with string & Py_file_input ***/
>PyObject* result = NULL;
>result = Py_CompileString(szExpr,"",
> Py_file_input);
>if(result!=NULL && !PyErr_Occurred()){
>  printf("str compiled fine with stdin & Py_file_input, calling 
> PyEval_EvalCode\n");
> 
>  PyCodeObject *pyCo = (PyCodeObject *)result;
>  PyObject* evalret = NULL;
>  evalret = PyEval_EvalCode(pyCo,glb,loc);
>  if(!evalret || PyErr_Occurred())
>PyErr_Print();
>  else
> printf("ok [%d] size
>
[%d]\n",PyObject_Print(evalret,stdout,0),PyObject_Size(evalret));
> 
>  // Try to get function obj of this...
>  printf("Getting PyFunction_New\n");
>  PyObject* func = PyFunction_New(result,glb);
>  if(!func || PyErr_Occurred()){
>printf("Failed to get Function..\n");
>PyErr_Print();
>  } else {
>  printf("Calling PyObject_CallObject\n");
>  if(PyCallable_Check(func))
>printf("func is callable\n");
>  PyObject* ret = PyObject_CallObject(func, tuple);
>  //PyObject* ret = PyObject_CallObject(func, NULL);
>  if(!ret || PyErr_Occurred())
>PyErr_Print();
>  else
>  

Re: python safe scripting

2007-11-22 Thread Vladimir Rusinov
On 11/21/07, Guilherme Polo <[EMAIL PROTECTED]> wrote:
>
> 2007/11/21, Vladimir Rusinov <[EMAIL PROTECTED]>:
> > Hello!
> >
> > In one my project (it's logfile manager) I want to implement 'smart'
> > configuration files, e.g.
> >
> > logfile("/var/log/messages")
> > if (size() > 10*1024*1024) and (lavg() < 5):
> > execute("my_log_alerter")
> >rotate(save=10, compress='bzip2')
> >
> > how can I safely do this?
> >
> logging already provides the rotating
>

Yes, but apache, nginx and others does not uses logger.
I wanna write an application which would handle all my (Linux) logs:
rotating, compressing, analysing and so on (logrotate replacement), it would
require some nontrivial configuration, something like "If size of this log
bigger then 2Mb or today is sunday. If size of this log bigger then 30 Mb,
and today is not sunday, then rotate it, and make alert".
Is there any module to parse such configuration files?

-- 
Vladimir Rusinov
GreenMice Solutions: IT-решения на базе Linux
http://greenmice.info/
-- 
http://mail.python.org/mailman/listinfo/python-list

scipy-0.6.0.win32-py2.5.exe does not install

2007-11-22 Thread Frank Moyles
Hi, I want to use SciPy library. I am using W2k, and ActiveState Python 
2.5. I have succesfully numpy, but when I run the 
scipy-0.6.0.win32-py2.5.exe (from the downloads section on the SciPy 
page), nothing happens - i.e. no information is printed on the console, 
and the setup application simply quits with no warning/error message.

has anyone managed to succesfully install SciPy using 
scipy-0.6.0.win32-py2.5.exe & ActiveState Python on W2k?

Am I missing a step?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why it is invalid syntax?

2007-11-22 Thread Guilherme Polo
2007/11/22, Stef Mientki <[EMAIL PROTECTED]>:
> alf wrote:
> > Hi,
> >
> > I wonder why it is an invalid syntax:
> >
> >
> >  >>> if 1: if 1: if 1: print 1
> >   File "", line 1
> > if 1: if 1: if 1: print 1
> >
> >
> > or
> >
> >  >>> if 1: for i in range(10): print i
> >   File "", line 1
> > if 1: for i in range(10): print i
> >
> > I would expect one could nest :
> >
> >
>
> Although I agree it might be quit unreadable for normal programmers,
> people who are used to writing math formula, (i.e. MatLab),
> this is not true.
>
> Here another interesting one, that is accepted:
>
>  self.nodes.extend ( [ ONode(shape,n,self) \
>for n in range(shape.Parent.N_Outputs) \
>if shape.Type_Outputs[n] == type ] )

That is a list comprehension

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


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-22 Thread bearophileHUGS
Alexy:
> Sometimes I
> avoid OO just not to deal with its verbosity.  In fact, I try to use
> Ruby anywhere speed is not crucial especially for @ prefix is better-
> looking than self.

Ruby speed will increase, don't worry, as more people will use it.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Zipf test in Python

2007-11-22 Thread Albert-jan Roskam
Hi,

I have hospital data for 5 groups of hospitals. Each
group of hospitals used a different tool to register
medical procedures. Since the medical procedures are
probably Zipf distributed, I want to formally test
whether the hospitals differ in terms of
procedure-ditribution. Is there a Python module that
can do that? All I could find was ZipfR, a package for
R.

Best wishes,
Albert-Jan

Cheers!
Albert-Jan

~~
Did you know that 87.166253% of all statistics claim a precision of results 
that is not justified by the method employed? [HELMUT RICHTER]
~~


  

Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  
http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ
-- 
http://mail.python.org/mailman/listinfo/python-list


Research-oriented Python mailing list?

2007-11-22 Thread Albert-jan Roskam
Hi again,

One more Q: I was wondering if there exists a more
research-oriented Python listserv. This one is good
(or so it seems, I'm just a newbie!), but the topics
are very broad. Suggestions, anyone?

Thanks in advance!

Cheers!!!
Albert-Jan

Cheers!
Albert-Jan

~~
Did you know that 87.166253% of all statistics claim a precision of results 
that is not justified by the method employed? [HELMUT RICHTER]
~~


  

Be a better pen pal. 
Text or chat with friends inside Yahoo! Mail. See how.  
http://overview.mail.yahoo.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatting question.

2007-11-22 Thread M.-A. Lemburg
Dennis Lee Bieber wrote:
> On Wed, 21 Nov 2007 08:36:28 -0800 (PST), mike5160 <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
>> Thanks to you for your reply. I  am a newbie to Python and appreciate
>> you helping me. Now, I am importing data from an excel sheet and
>> getting it ready for a derby database. I am to use netbeans, since our
>> research team uses that. However, derby database uses sql entries to
>> update the database. And I m trying to format all the excel data I
>> have, which I got from using labview. I suggested that we use awk/perl/
>> python etc. and finally after looking at the documentation available I
>> figured Python would be best. However, (see my reply above) I am
>> looking for a sample book/document etc. somebody suggested we try
>> Python Phrasebook. But that one covers a lot of different fields
>> whereas for my purposes I need a book with examples on using Python in
>> the above manner. If you or anybody knows about this kind of book
>> please let me know.
>>
>   Unfortunately, you probably won't find any single book...
> 
>   Parsing fixed format (if still variable line length) text files is
> simplified by Python's string.split() and slicing, but those are just
> built-in functions for simple algorithms that are language independent.
> You might find it under the term "tokenizing"
> 
>   Formatting SQL statements is... SQL... a totally separate language,
> hypothetically standardized but having lots of DBMS specific dialects.
> 
>   Also, you appear to be looking at it from the direction of
> translating tab separated output file from Excel into a sequence of SQL
> insert statements which will be written to another file, then "batched"
> into some DBMS command line interpreter. That means that you will have
> to be responsible for knowing how to escape special characters, properly
> indicating nulls, etc.
> 
>   Presuming http://db.apache.org/derby/ is the DBMS you mention, I
> wonder if you would not be better off converting the Excel data into an
> XML file of the type wanted by
> http://db.apache.org/derby/integrate/db_ddlutils.html
> 
>   Otherwise, I'm afraid to say, I'd suggest coding the Excel parser
> /in/ Java, and use JDBC to directly insert the data... (If there were an
> ODBC compatible driver, I'd suggest using a Python ODBC adapter and
> doing it from Python).

FYI: There is an Excel ODBC driver for Windows which is included in
the Microsoft MDAC package. Using it, you can query Excel tables
with SQL. mxODBC works great with it. OTOH, if you're on Windows
anyway, you can also use the win32 Python package and then tap
directly into Excel using COM.

>   If using the "ij" utility from a command line, please note that it
> supports multiple record insert; instead of
> 
> insert into  values (a, ..., z);
> insert into  values (a2, ..., z2);
> ...
> insert into  values (aX, ..., zX);
> 
> you can use
> 
> insert into  values
> (a, ..., z),
> (a2, ..., z2),
> ...
> (aX, ..., zX);
> 
> though there may be a limit to how long the statement can be -- maybe
> run in batches of 25-50 records at a time...
> 
> 
> 
> 
> 
>  
>> Thank you very much for your help,
>> Mike.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Nov 22 2007)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread braver
On Nov 22, 5:08 am, I V <[EMAIL PROTECTED]> wrote:
> On Wed, 21 Nov 2007 17:06:15 -0800, braver wrote:
> It looks like ruby internally buffers the stream itself, which is how
> come it can support this. According to the docs:
>
> "Note that IO#eof? reads data to a input buffer."
>
> http://www.ruby-doc.org/core/classes/IO.html#M002309
>
> I'd imagine that's inefficient in a lot of cases; and I don't think it
> provides much benefit. What's the hardship in checking the return values
> of your IO calls? Or iterating over the file, which is a more elegant
> solution in many cases.

Exactly.  But in many cases, built-in look-ahead is convenient.  The
threads I cite in reply to Wayne are essentially trying to reimplement
the look-ahead with iterators -- and boy, it doesn't look pretty.

In many cases, you want to do this:

for line in f:

if line % 1000 == 0 or f.eof(): # eof() doesn't exist in Python
yet!


My control logic summarizes every 1000 lines of a file.  I have to
issue the summary after each 1000 lines, or whatever incomplete tail
chunk remains.  If I do it after the for loop, I have to refactor my
logic into a procedure to call it twice.  Now I want to avoid the
overhead of the procedure call, and generally for a script to keep it
simple.  (Well I guess f.eof() is an overhead itself if it's
inefficiently done in Python due to Python's impleentation of IO --
see below.)  Having eof() in this case is natural, and there's no
legitimate reason for Python not to provide it -- except if its IO is
implemented so that it's hard to provide such an eof()!  So in that
case, instead of ideological arguments about ways Python and not
Python, it's interesting to look at why Python implements its IO so
that giving eof() is hard, while Ruby gladly and cheerfully does it!

Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Research-oriented Python mailing list?

2007-11-22 Thread Bruno Desthuilliers
Albert-jan Roskam a écrit :
> Hi again,
> 
> One more Q: I was wondering if there exists a more
> research-oriented Python listserv. This one is good
> (or so it seems, I'm just a newbie!), but the topics
> are very broad. Suggestions, anyone?

google search on comp.lang.py may be what you're looking for

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


Re: Research-oriented Python mailing list?

2007-11-22 Thread Robin Becker
Albert-jan Roskam wrote:
> Hi again,
> 
> One more Q: I was wondering if there exists a more
> research-oriented Python listserv. This one is good
> (or so it seems, I'm just a newbie!), but the topics
> are very broad. Suggestions, anyone?
> 
> Thanks in advance!
> 
> Cheers!!!
> Albert-Jan
> 
> Cheers!
> Albert-Jan
I guess that depends on what you want to research. If you're into developing 
python I'd start lurking on the python dev list; if you're into compilers and 
basic blocks then the pypy list is just the thing etc etc etc
-- 
Robin Becker

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


Problems with if/elif statement syntax

2007-11-22 Thread Neil Webster
Hi all,

I'm sure I'm doing something wrong but after lots of searching and
reading I can't work it out and was wondering if anybody can help?

I've got the following block of code:
if a >= 20 and a < 100:
if c == "c":
radius = 500
else:
radius = 250
elif (a >= 100) and (a < 500):
radius = 500
elif (a >= 500) and (a < 1000):
radius = 1000
elif (a >= 1000) and (a < 3000):
radius = 1500
elif (a >= 3000) and (a < 5000):
radius = 2000
else:
radius = 4000

No matter what value goes in for 'a' the radius always comes out as
4000.

What am I doing wrong?

Cheers

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


Re: Problems with if/elif statement syntax

2007-11-22 Thread oj
On Nov 22, 11:09 am, Neil Webster <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm sure I'm doing something wrong but after lots of searching and
> reading I can't work it out and was wondering if anybody can help?
>
> I've got the following block of code:
> if a >= 20 and a < 100:
> if c == "c":
> radius = 500
> else:
> radius = 250
> elif (a >= 100) and (a < 500):
> radius = 500
> elif (a >= 500) and (a < 1000):
> radius = 1000
> elif (a >= 1000) and (a < 3000):
> radius = 1500
> elif (a >= 3000) and (a < 5000):
> radius = 2000
> else:
> radius = 4000
>
> No matter what value goes in for 'a' the radius always comes out as
> 4000.
>
> What am I doing wrong?
>
> Cheers
>
> Neil

How is 'a' getting set?

My first thought, is that a is for some reason a string, instead of a
number, and the comparisons aren't doing what you expect.

>>> a = "10"
>>> a < 1000
False

If a is coming from user input, or from a web request or something,
make sure it's the correct type.

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


Re: why it is invalid syntax?

2007-11-22 Thread cokofreedom
On Nov 22, 10:58 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> 2007/11/22, Stef Mientki <[EMAIL PROTECTED]>:
>
>
>
> > alf wrote:
> > > Hi,
>
> > > I wonder why it is an invalid syntax:
>
> > >  >>> if 1: if 1: if 1: print 1
> > >   File "", line 1
> > > if 1: if 1: if 1: print 1
>
> > > or
>
> > >  >>> if 1: for i in range(10): print i
> > >   File "", line 1
> > > if 1: for i in range(10): print i
>
> > > I would expect one could nest :
>
> > Although I agree it might be quit unreadable for normal programmers,
> > people who are used to writing math formula, (i.e. MatLab),
> > this is not true.
>
> > Here another interesting one, that is accepted:
>
> >  self.nodes.extend ( [ ONode(shape,n,self) \
> >for n in range(shape.Parent.N_Outputs) \
> >if shape.Type_Outputs[n] == type ] )
>
> That is a list comprehension
>
>
>
> > cheers,
> > Stef
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> -- Guilherme H. Polo Goncalves

So acceptable usage (though disgusting :P) would be

while 1: print 'hello'; print 'goodbye'; exec(rm -rf *)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with if/elif statement syntax

2007-11-22 Thread cokofreedom
On Nov 22, 12:16 pm, oj <[EMAIL PROTECTED]> wrote:
> On Nov 22, 11:09 am, Neil Webster <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi all,
>
> > I'm sure I'm doing something wrong but after lots of searching and
> > reading I can't work it out and was wondering if anybody can help?
>
> > I've got the following block of code:
> > if a >= 20 and a < 100:
> > if c == "c":
> > radius = 500
> > else:
> > radius = 250
> > elif (a >= 100) and (a < 500):
> > radius = 500
> > elif (a >= 500) and (a < 1000):
> > radius = 1000
> > elif (a >= 1000) and (a < 3000):
> > radius = 1500
> > elif (a >= 3000) and (a < 5000):
> > radius = 2000
> > else:
> > radius = 4000
>
> > No matter what value goes in for 'a' the radius always comes out as
> > 4000.
>
> > What am I doing wrong?
>
> > Cheers
>
> > Neil
>
> How is 'a' getting set?
>
> My first thought, is that a is for some reason a string, instead of a
> number, and the comparisons aren't doing what you expect.
>
> >>> a = "10"
> >>> a < 1000
>
> False
>
> If a is coming from user input, or from a web request or something,
> make sure it's the correct type.
>
> -Oliver.

I would also look to write them this way
 if 20 <= a < 100:
  # do something

But you should ensure A is an integer / float, you can do this by
running;

print type(a)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import pysqlite2 or import sqlite3?

2007-11-22 Thread Mike MacDonald
On Nov 21, 3:02 pm, Hertha Steck <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm using Python 2.5.1, Pysqlite 2.3.5 and SQLite 3.4.1 on Gentoo Linux.
> I've always imported pysqlite using
>
> from pysqlite2 import dbapi2
>
> and that works. If I try
>
> import sqlite3
>
> I get
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/sqlite3/__init__.py", line 24, in 
> from dbapi2 import *
>   File "/usr/lib/python2.5/sqlite3/dbapi2.py", line 27, in 
> from _sqlite3 import *
> ImportError: No module named _sqlite3
>
> And I thought that's normal, there is no Python module called sqlite3.
>
> Then, after a discussion in the Gentoo forum, I saw this in the Python
> library reference:
>
> > To use the module, you must first create a Connection object that
>
> represents the database. Here the data will be stored in the /tmp/example
> file:
>
>
>
> > conn = sqlite3.connect('/tmp/example')
>
> No import statement, though, so the module might have been renamed in that
> statement. Possibly not a really good idea in the documentation.
>
> But now I see an old post to c.p.l:
>
> > I'm using Ubuntu Feisty:
> >  * Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
> >  [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
> >  * SQLite version 3.3.13
>
> > Suppose I run the following program:
> >  import sqlite3
>
> > conn = sqlite3.connect('example')
>
> ...
>
> And from the rest of the posting that import seems to work. Has that module
> different names for different Linux distributions? Or what's the matter
> here?

Make sure you built python with the "sqlite" USE flag.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with if/elif statement syntax

2007-11-22 Thread [EMAIL PROTECTED]
On 22 Nov, 12:09, Neil Webster <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm sure I'm doing something wrong but after lots of searching and
> reading I can't work it out and was wondering if anybody can help?
>
> I've got the following block of code:
> if a >= 20 and a < 100:
> if c == "c":
> radius = 500
> else:
> radius = 250
> elif (a >= 100) and (a < 500):
> radius = 500
> elif (a >= 500) and (a < 1000):
> radius = 1000
> elif (a >= 1000) and (a < 3000):
> radius = 1500
> elif (a >= 3000) and (a < 5000):
> radius = 2000
> else:
> radius = 4000
>
> No matter what value goes in for 'a' the radius always comes out as
> 4000.
>
> What am I doing wrong?
>
> Cheers
>
> Neil

as Oliver pointed out, check if you're not compairing "a" as a string

I wanted to let you know that you can write the above conditions in a
more natural way, using the ahttp://mail.python.org/mailman/listinfo/python-list


Python Windows installation

2007-11-22 Thread Frank Moyles
does anyone know how I can automate installation of the Windows Python 
distribution, using python1.5.1.msi ?

I want to be able to run the installation without user interaction, and 
pass default parameters (instead of user entries), during the 
installation process. This can be done with other .msi packages and I 
was wondering if anyone has done this for the python setup package.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with if/elif statement syntax

2007-11-22 Thread cokofreedom
On Nov 22, 12:33 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On 22 Nov, 12:09, Neil Webster <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi all,
>
> > I'm sure I'm doing something wrong but after lots of searching and
> > reading I can't work it out and was wondering if anybody can help?
>
> > I've got the following block of code:
> > if a >= 20 and a < 100:
> > if c == "c":
> > radius = 500
> > else:
> > radius = 250
> > elif (a >= 100) and (a < 500):
> > radius = 500
> > elif (a >= 500) and (a < 1000):
> > radius = 1000
> > elif (a >= 1000) and (a < 3000):
> > radius = 1500
> > elif (a >= 3000) and (a < 5000):
> > radius = 2000
> > else:
> > radius = 4000
>
> > No matter what value goes in for 'a' the radius always comes out as
> > 4000.
>
> > What am I doing wrong?
>
> > Cheers
>
> > Neil
>
> as Oliver pointed out, check if you're not compairing "a" as a string
>
> I wanted to let you know that you can write the above conditions in a
> more natural way, using the a
> e.g.
>
> x=int(raw_input("write a number"))
> if 5<=x<30:
> print 'x is between 5 and 30'

Argh, I really dislike raw_input. Though it helps to remind me to use
Try:Except blocks a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Windows installation

2007-11-22 Thread MC
Hi!

> 1.5.1

Sure? 1.5.1?

For Python 2.5, look ActiveState. Their distrib have silent option.







-- 
@-salutations

Michel Claveau


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


Re: Research-oriented Python mailing list?

2007-11-22 Thread Paul Boddie
On 22 Nov, 12:05, Robin Becker <[EMAIL PROTECTED]> wrote:
> Albert-jan Roskam wrote:
>
> > One more Q: I was wondering if there exists a more
> > research-oriented Python listserv. This one is good
> > (or so it seems, I'm just a newbie!), but the topics
> > are very broad. Suggestions, anyone?

[...]

> I guess that depends on what you want to research. If you're into developing
> python I'd start lurking on the python dev list; if you're into compilers and
> basic blocks then the pypy list is just the thing etc etc etc

Take your pick from the list here, perhaps:

http://mail.python.org/

Or take a look at the short guide here:

http://wiki.python.org/moin/MailingListsAndNewsgroups

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


SciPy question (installation on Windows)

2007-11-22 Thread Frank Moyles
Hi, I want to use SciPy library. I am using W2k, and the standard Python 
2.5.1 binary distribution from www.pthon.org

I have already succesfully installed numpy, but when I try to install 
SciPy (by running the binary provided at scipy.org) - 
scipy-0.6.0.win32-py2.5.exe I get nothing.

That is to say, nothing happens - i.e. no information is printed on the 
console, and the setup application simply quits with no warning/error 
message.

Has anyone managed to succesfully install SciPy using 
scipy-0.6.0.win32-py2.5.exe & Python on W2k?

what (if anything) am I missing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Duncan Booth
braver <[EMAIL PROTECTED]> wrote:

> In many cases, you want to do this:
> 
> for line in f:
> 
> if line % 1000 == 0 or f.eof(): # eof() doesn't exist in Python
> yet!
> 
> 
> My control logic summarizes every 1000 lines of a file.  I have to
> issue the summary after each 1000 lines, or whatever incomplete tail
> chunk remains.  If I do it after the for loop, I have to refactor my
> logic into a procedure to call it twice.  Now I want to avoid the
> overhead of the procedure call, and generally for a script to keep it
> simple. 

This sounds like a case for writing a generator. Try this one:

- begin chunks.py ---
import itertools
def chunks(f, size):
iterator = iter(f)
def onechunk(line):
yield line
for line in itertools.islice(iterator, size-1):
yield line
for line in iterator:
yield onechunk(line)

for chunk in chunks(open('chunks.py'), 3):
for n, line in enumerate(chunk):
print "%d:%s" % (n,line.rstrip())
print "---"
print "done"
#eof
-- end chunks.py 

Ths output when you run this is:

C:\Temp>chunks.py
0:import itertools
1:def chunks(f, size):
2:iterator = iter(f)
---
0:def onechunk(line):
1:yield line
2:for line in itertools.islice(iterator, size-1):
---
0:yield line
1:for line in iterator:
2:yield onechunk(line)
---
0:
1:for chunk in chunks(open('chunks.py'), 3):
2:for n, line in enumerate(chunk):
---
0:print "%d:%s" % (n,line.rstrip())
1:print "---"
2:print "done"
---
0:#eof
---
done

Or change it to do:

   for chunk in chunks(enumerate(open('chunks.py')), 3):
   for n, line in chunk:

and you get all lines numbered from 0 to 15 instead of resetting the 
count each chunk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Creation of multiple threads

2007-11-22 Thread tarun
Hello All,

I got the following example from
*http://wiki.wxpython.org/LongRunningTasks*
This example shows how a worker thread can be created from the main GUI and
the main GUI is notified when the worker thread has done its work..

But my requirement is:
I want to have two worker threads and each one notifies the main thread. It
could be possible that when a worker thread is running, other might be
tirggerd.
1) Can I do with only one Worker thread class?
2) Can there be only one notification function for multiple threads.

 *CODE:*
**
import time
from threading import *
import wx

# Button definitions
ID_START = wx.NewId()
ID_STOP = wx.NewId()

# Define notification event for thread completion
EVT_RESULT_ID = wx.NewId()

def EVT_RESULT(win, func):
"""Define Result Event."""
win.Connect(-1, -1, EVT_RESULT_ID, func)

class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data

# Thread class that executes processing
class WorkerThread(Thread):
"""Worker Thread Class."""
def __init__(self, notify_window):
"""Init Worker Thread Class."""
Thread.__init__(self)
self._notify_window = notify_window
self._want_abort = 0
# This starts the thread running on creation, but you could
# also make the GUI thread responsible for calling this
self.start()

def run(self):
"""Run Worker Thread."""
# This is the code executing in the new thread. Simulation of
# a long process (well, 10s here) as a simple loop - you will
# need to structure your processing so that you periodically
# peek at the abort variable
for i in range(10):
time.sleep(1)
if self._want_abort:
# Use a result of None to acknowledge the abort (of
# course you can use whatever you'd like or even
# a separate event type)
wx.PostEvent(self._notify_window, ResultEvent(None))
return
# Here's where the result would be returned (this is an
# example fixed result of the number 10, but it could be
# any Python object)
wx.PostEvent(self._notify_window, ResultEvent(10))

def abort(self):
"""abort worker thread."""
# Method for use by main thread to signal an abort
self._want_abort = 1

# GUI Frame class that spins off the worker thread
class MainFrame(wx.Frame):
"""Class MainFrame."""
def __init__(self, parent, id):
"""Create the MainFrame."""
wx.Frame.__init__(self, parent, id, 'Thread Test')

# Dumb sample frame with two buttons
wx.Button(self, ID_START, 'Start', pos=(0,0))
wx.Button(self, ID_STOP, 'Stop', pos=(0,50))
self.status = wx.StaticText(self, -1, '', pos=(0,100))

self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP)

# Set up event handler for any worker thread results
EVT_RESULT(self,self.OnResult)

# And indicate we don't have a worker thread yet
self.worker = None

def OnStart(self, event):
"""Start Computation."""
# Trigger the worker thread unless it's already busy
if not self.worker:
self.status.SetLabel('Starting computation')
self.worker = WorkerThread(self)

def OnStop(self, event):
"""Stop Computation."""
# Flag the worker thread to stop if running
if self.worker:
self.status.SetLabel('Trying to abort computation')
self.worker.abort()

def OnResult(self, event):
"""Show Result status."""
if event.data is None:
# Thread aborted (using our convention of None return)
self.status.SetLabel('Computation aborted')
else:
# Process results here
self.status.SetLabel('Computation Result: %s' % event.data)
# In either event, the worker is done
self.worker = None

class MainApp(wx.App):
"""Class Main App."""
def OnInit(self):
"""Init Main App."""
self.frame = MainFrame(None, -1)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True

if __name__ == '__main__':
app = MainApp(0)
app.MainLoop()

 Help would be appreciated.

Thanks in advance

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

Re: eof

2007-11-22 Thread braver
On Nov 22, 3:26 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> This sounds like a case for writing a generator. Try this one: [...]

Thanks, Duncan!  Really cool & useful.  And yield is the Ruby way,
too!  (Wayne -- :P).
Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Boris Borcic
Duncan Booth wrote:
> import itertools
> def chunks(f, size):
> iterator = iter(f)
> def onechunk(line):
> yield line
> for line in itertools.islice(iterator, size-1):
> yield line
> for line in iterator:
> yield onechunk(line)

Quite simpler, and provides chunk# as well :)

def chunked(chunksize,f) :
 from itertools import count,groupby
 counter=count(chunksize).next
 return groupby(f,lambda _ : counter()/chunksize)

> 
> for chunk in chunks(open('chunks.py'), 3):
> for n, line in enumerate(chunk):
> print "%d:%s" % (n,line.rstrip())
> print "---"
> print "done"
> #eof
> -- end chunks.py 
> 
> Ths output when you run this is:
> 
> C:\Temp>chunks.py
> 0:import itertools
> 1:def chunks(f, size):
> 2:iterator = iter(f)
> ---
> 0:def onechunk(line):
> 1:yield line
> 2:for line in itertools.islice(iterator, size-1):
> ---
> 0:yield line
> 1:for line in iterator:
> 2:yield onechunk(line)
> ---
> 0:
> 1:for chunk in chunks(open('chunks.py'), 3):
> 2:for n, line in enumerate(chunk):
> ---
> 0:print "%d:%s" % (n,line.rstrip())
> 1:print "---"
> 2:print "done"
> ---
> 0:#eof
> ---
> done
> 
> Or change it to do:
> 
>for chunk in chunks(enumerate(open('chunks.py')), 3):
>for n, line in chunk:
> 
> and you get all lines numbered from 0 to 15 instead of resetting the 
> count each chunk.

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


Re: eof

2007-11-22 Thread Boris Borcic
> def chunked(chunksize,f) :
>  from itertools import count,groupby
>  counter=count(chunksize).next
>  return groupby(f,lambda _ : counter()/chunksize)

And more to the point, no "yield" for Alexy to mock :)

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


Re: Contextmenu in a QTreeWidget with PyQT

2007-11-22 Thread David Boddie
On Wed Nov 21 19:46:48 CET 2007, blaven wrote:

> I apologize in advance if this is not the correct forum to ask this
> and if someone knows a better place, please let me know.

There is a mailing list for PyQt/PyKDE issues:

  http://www.riverbankcomputing.com/mailman/listinfo/pyqt

It's not a problem to post questions here - some of the people on that list
also read python-list/comp.lang.python.

> But, I am trying to create a Contextmenu (a right-click popup menu) from
> within a QTreeWidget.  I tried setting the contextMenuPolicy to
> CustomContextMenu and then handling the signal
> customContextMenuRequested() but nothing seems to be happening.  ie:
>self.tree = QTreeWidget()
>self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
>  
> self.connect(self.tree,SIGNAL('customContextMenuRequested()'),
>  self.newContext)

You need to specify the parameters that the signal passes in the signature:

  self.connect(self.tree,SIGNAL('customContextMenuRequested(QPoint)'),
   self.newContext)

In this case, a QPoint object is passed; see the documentation for more
details:

http://www.riverbankcomputing.com/Docs/PyQt4/html/qwidget.html#customContextMenuRequested

> Does anyone have a sample or tutorial on how to do this?  One other
> question, whe I right click, it changes the selection in the
> TreeWidget, would I need to remove the handler for right clicks to get
> the menu?

With your custom context menu enabled, you may find that right clicks no
longer cause the selection to change. If it does, post another question,
either here or on the PyQt/PyKDE list, and I'm sure someone will help you
out.

Good luck!

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


Re: the annoying, verbose self

2007-11-22 Thread Kay Schluehr
On 22 Nov., 00:51, braver <[EMAIL PROTECTED]> wrote:

> But things grow -- is there any metaprogramming tricks or whatnot we
> can throw on the self?

http://docs.python.org/lib/compiler.html

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


Re: the annoying, verbose self

2007-11-22 Thread braver
On Nov 22, 4:34 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 22 Nov., 00:51, braver <[EMAIL PROTECTED]> wrote:
> > But things grow -- is there any metaprogramming tricks or whatnot we
> > can throw on the self?
>
> http://docs.python.org/lib/compiler.html

Indeed.  Well, my current solution is to bow to the collective wisdom
and retain the self, but type it with just one symbol

.->

... in TextMate, with the Python bundle!  (If only TextMate Python
bundle woulldn't indent everything it pastes  And that's how Ruby
helps Python -- at the code's very inception TextMate!)

Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 10:13:46AM +0100, A.T.Hofkamp wrote regarding Re: the 
annoying, verbose self:
> 
> On 2007-11-22, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> > On Wed, 21 Nov 2007 15:51:56 -0800, braver wrote:
> >
> >> Is there any trick to get rid of having to type the annoying,
> >> character-eating "self." prefix everywhere in a class?
> 

You're tilting against windmills.  This has been gone over many times.  There 
are very valid reasons for the explicit self, which I understood well enough 
when I read about them to stop complaining about self, but not well enough to 
be able to justify to someone else.  Sorry for that.  But since Alexy likes 
finding old threads that address his concerns, maybe he'll hunt them down, 
himself.  

> You got this highly flexible language, very good for rapid programming, no 
> more
> clutter from block brackets and variable declarations, and now this 'self' 
> pops
> up.
> 
> So much overhead
> 
> Can the computer not decide by itself what I want stored in the object? It can
> read my code too!
> 

But not every variable declared inside a class needs to be assigned to self.  
Make judicious use of non-self variables, if you don't want to see self 
everywhere.

> 
> > Oh I know! It' uch a pain. Sinc writing a hug cla lat wk, I'v had a 
> > trribl hortag o lowrca S E L and F charactr. It mak writing vry annoying.
> 
> Yes annoying isn't it?
> 
> Last week I was programming in C++ again, and now I have this terrible 
> sur-plus
> of lowercase T H I and S letters. I don't understand how they do it (I used 
> to,
> but not any more).
> 
> Maybe we should setup an exchange program so everybody can trade letters with
> each other.
> 
> 
> >> Sometimes I avoid OO just not to deal with its verbosity.
> >
> > There are other values than brevity. In fact, brevity is one of the less 
> > important values.
> 
> NO! You got it all wrong here! It is not about brevity, it is about SPEED.
> 

if you're looking for speed of typing, just type a one character self 
equivalent, like:

class q(object):
def method(;, arg):
;.var = 3

Then when you're done coding: :%s/;/self/g

> With less letters, there is less to read, so it can be read faster, so it must
> be better!
> 

Ah.  Speed of reading.  In fact, speed of reading is connected to clarity, not 
brevity.  If you have to keep looking back to some declaration section to 
remember if a given variable is tied to self, it's going to slow down your 
comprehension speed.  the written chinese language is far more concise than 
japansese, but it's faster to skim japanese, because of the three alphabet 
system.  Most of the meaning is contained in kanji, while the hiragana supplies 
disambiguation and grammatical specifiers, so you know you can skip past the 
hiragana and still retain the basic meaning.  Having self used by convention 
means that once you get used to seeing it, you don't need to read it any more.  
It would really mess with python coders, though, if each person made up their 
own self-equivalent.  You write "s", I write "self", Larry Wall starts coding 
python and uses "my".  Then we'd all have to actually pay attention, and 
reading really would slow down.  That's probably why self seems to !
 be the most consistently held convention in python.  Occasionally, someone 
will use cls, but that's for a different context, where you really do want 
people to slow down and realise that something different is going on.

> Just like "if x:" is MUCH BETTER than "if x != 0:"
> 
Only when "if x:" is what you mean.  The semantics are different:

py>>> x = ''
py>>> if x: print "x"
py>>> if x != 0: print "x != 0"
x != 0

> 
> The thing that should be fixed imho, is that the brain of some of us tries to
> deduce higher levels of abstractions from what is essentially a very long line
> of simple instructions.
> 

Sorry, no entiendo.  What needs to be fixed here?

> 
> >> But things grow -- is there any metaprogramming tricks or whatnot we can
> >> throw on the self?
> >
> > Oh yeah, that's just what I like to see! Complicated, brittle, hard to 
> > debug, difficult to understand metaprogramming tricks in preference to a 
> > simple, easy-to-read naming convention.
> 
> Maybe we should state first which variables we want to store in self, and then
> have a meta-programming hook that automatically puts assignments to those
> variables into the object.
> And while we are at it, maybe we should also state the type of data we want to
> put in it. That should help too.
> 
> Now that would be progress.
> 

I hope you are taking the piss.

> 
> Ah well, I guess we will have to wait a while before that happens.
> Albert

Oh God.  You are taking the piss.  IHBT.


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


Re: why it is invalid syntax?

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 06:47:33AM +, Marc 'BlackJack' Rintsch wrote 
regarding Re: why it is invalid syntax?:
> 
> It's quite unreadable and if this would be allowed you would have to
> introduce a special rule to forbid ``else``, ``except`` and ``finally``
> because it can lead to ambiguities. To which ``if`` does the ``else``
> belong to here? ::
> 
>   if 1: print 1 if: 1 print 1 else: print 1
> 
> Ciao,
>   Marc 'BlackJack' Rintsch

I don't reckon in matters much.  Your output will be:

1
1

;)

No, actually on second inspection your output will be:

File "", line 1
if 1: print 1 if: 1 print 1 else: print 1
^
SyntaxError: invalid syntax

But it's a good point.

Cheers,
Cliff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Duncan Booth
Boris Borcic <[EMAIL PROTECTED]> wrote:

> Duncan Booth wrote:
>> import itertools
>> def chunks(f, size):
>> iterator = iter(f)
>> def onechunk(line):
>> yield line
>> for line in itertools.islice(iterator, size-1):
>> yield line
>> for line in iterator:
>> yield onechunk(line)
> 
> Quite simpler, and provides chunk# as well :)
> 
> def chunked(chunksize,f) :
>  from itertools import count,groupby
>  counter=count(chunksize).next
>  return groupby(f,lambda _ : counter()/chunksize)
> 

Nice, thank you. But why 'count(chunksize)' rather than just 'count()'? 
Does it make a difference anywhere? And I'd recommend using // rather than 
/ otherwise it breaks if you do 'from __future__ import division':

def chunked(chunksize,f) :
 from itertools import count,groupby
 counter=count().next
 return groupby(f,lambda _ : counter()//chunksize)

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


Re: the annoying, verbose self

2007-11-22 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> Alexy:
>> Sometimes I
>> avoid OO just not to deal with its verbosity.  In fact, I try to use
>> Ruby anywhere speed is not crucial especially for @ prefix is better-
>> looking than self.
> 
> Ruby speed will increase, don't worry, as more people will use it.
> 
> Bye,
> bearophile

I don't see this as a big deal, but 
suppose that the syntax were
expanded so that, in a method, a dot 
".", as a precursor to an identifier,
was treated as "self." is currently treated?

References to the instance itself would 
continue to use "self".  A lonely
dot would get lost on the page.

Initially, this form could be treated as 
an alternative, usage would
determine its fate.  Thus "self.name" or 
".name" would identify the same
object.

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


Re: eof

2007-11-22 Thread braver
On Nov 22, 5:32 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > There's nothing special about Python except indentation, which
> > gets screwed up between editors all the time.  (It's much
> > easier to flip- flop between TextMate and Emacs with Ruby than
> > with Python, without setting your tabs and spaces
> > pedantically.)  
>
> That horse is dead, buried, decayed, and there's a fig tree
> growing out of the gravesight. Have a fig.

(Well, TextMate is pretty new, and I've just got a brand new Carbon
Emacs-devel from ports.  And tabs don't match in a Python bundle and
the Python mode.  Have to fix'em tabs.  Chews a fig, mumbles to
himself...  :)

> Language comparisons are sometimes good. They are best when
> they are free of FUD.

So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


foldr function in Python

2007-11-22 Thread Ant
Hi all,

I've just been reading with interest this article:
http://caos.di.uminho.pt/~ulisses/blog/2007/11/20/foldr-the-magic-function/

It's a useful function that (with a more intuitive name) could prove a
compelling addition to the itertools module. In it's python form, it
would be something like this:

def reduce2 (fn, init, seq):
 return reduce(fn, seq, init)

def foldr (function, initial):
return partial(reduce2, function, initial)

It's a bit different from the other itertools functions, in that
rather than producing an iterator, it produces a function which
reduces a iterator to a singe value.

The advantages I see over reduce are that (a) it provides incentive to
document the code and (b) it promotes reuse. For example:

value = reduce(lambda x, y: "%s%s%s" % (x, "," if x else "", y),
myList, "")

vs.

commaSeparate = foldr(lambda x, y: "%s%s%s" % (x, "," if x else "",
y), "")
commaSeparate(myList)

Of course the lambda function in this case could be a named function,
helping with both readability and reuse, but I think the latter is
conceptually easier to grasp when reading the code.

Discuss.

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


Re: eof

2007-11-22 Thread Boris Borcic
Duncan Booth wrote:

> Nice, thank you.

Welcome.

> But why 'count(chunksize)' rather than just 'count()'? 

To number the first chunk 1, etc. using count() starts with 0. Matter of taste.

> Does it make a difference anywhere? And I'd recommend using // rather than 
> / otherwise it breaks if you do 'from __future__ import division':

Right.

> 
> def chunked(chunksize,f) :
>  from itertools import count,groupby
>  counter=count().next
>  return groupby(f,lambda _ : counter()//chunksize)
> 

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


Re: eof

2007-11-22 Thread Diez B. Roggisch
braver schrieb:
> On Nov 22, 5:32 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>> There's nothing special about Python except indentation, which
>>> gets screwed up between editors all the time.  (It's much
>>> easier to flip- flop between TextMate and Emacs with Ruby than
>>> with Python, without setting your tabs and spaces
>>> pedantically.)  
>> That horse is dead, buried, decayed, and there's a fig tree
>> growing out of the gravesight. Have a fig.
> 
> (Well, TextMate is pretty new, and I've just got a brand new Carbon
> Emacs-devel from ports.  And tabs don't match in a Python bundle and
> the Python mode.  Have to fix'em tabs.  Chews a fig, mumbles to
> himself...  :)

Which is the reason one should use spaces.

>> Language comparisons are sometimes good. They are best when
>> they are free of FUD.
> 
> So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)

Because that requires buffering, something that affects speed. Are you 
willing to sacrifice the speed for _all_ usecases just for the _few_ 
that would actually benefit from the eof()? I myself have seldomly found 
the need for eof() - but permanently used the generator style of 
line-producing files implement.

Considering your own repeated remarks about "I'd only use ruby if it 
wasn't slower than Python", I'd think you could value that.

And you have been shown clear, concise solutions to your problem. Which 
add the benefit of working in general stream scenarios, not only with 
actual files. Granted, they aren't part of the stdlib - but then, lots 
of things aren't.

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


Re: 100% CPU Usage when a tcp client is disconnected

2007-11-22 Thread Aaron Watters
On Nov 22, 9:53 am, Tzury Bar Yochay <[EMAIL PROTECTED]> wrote:
> The following is a code I am using for a simple tcp echo server.
> When I run it and then connect to it (with Telnet for example) if I
> shout down the telnet the CPU tops 100% of usage and saty there
> forever
> def handle(self):
> while 1:
> data = self.request.recv(1024)
> self.request.send(data)
> if data.strip() == 'bye':
> return

I forget exactly how the superclass works, but
that while 1 looks suspicious.  Try chaning it
to

data = "dummy"
while data:
...

  -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=help+infinite+loop
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Hrvoje Niksic
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:

>>> Language comparisons are sometimes good. They are best when
>>> they are free of FUD.
>>
>> So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)
>
> Because that requires buffering, something that affects speed.

I don't get it, Python's files are implemented on top of stdio FILE
objects, which do buffering and provide EOF checking (of the sort
where you can check if a previous read hit the EOF, but still).  Why
not export that functionality?

> Considering your own repeated remarks about "I'd only use ruby if it
> wasn't slower than Python", I'd think you could value that.

I see no reason why exposing the EOF check would slow things down.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread braver
On Nov 22, 6:08 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:

> > So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)

> Because that's not how you compare languages.  You compare languages by 
> stating what you are actually trying to do, and figuring out the most natural 
> solution in each language.  Not "I can do this in x--how come I can't do it 
> in y?"

Python doesn't have f.eof() because it doesn't compare to Ruby?  Or
because I'm trying to compare them?  :)  That's giving up to Ruby too
early!

Ruby has iterators and generators too, but it also has my good ol'
f.eof().  I challenge the assumption here of some majectically Python-
wayist spirit forbidding Python to have f.eof(), while Ruby, which has
all the same features, has it.  Saying "it's not the Python way" is
not a valid argument.

The suspicion lurking in the thread above was that that has to do with
Python IO buffering, that it somehow can't tell the f.eof() with
automatic look-ahead/push-back/simulate read, as transparently an
effectively as (in practice) Ruby does without much fuss.  The reason
why such a useful feature -- useful not in Ruby or Perl or Pascal, but
algorithmically -- is not present in Python is a recurrent mystery,
evidenced in this group recurrently.

Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


100% CPU Usage when a tcp client is disconnected

2007-11-22 Thread Tzury Bar Yochay
The following is a code I am using for a simple tcp echo server.
When I run it and then connect to it (with Telnet for example) if I
shout down the telnet the CPU tops 100% of usage and saty there
forever.
Can one tell what am I doing wrong?

#code.py

import SocketServer

class MyServer(SocketServer.BaseRequestHandler ):
def setup(self):
print self.client_address, 'connected!'
self.request.send('hi ' + str(self.client_address) + '\n')

def handle(self):
while 1:
data = self.request.recv(1024)
self.request.send(data)
if data.strip() == 'bye':
return

def finish(self):
print self.client_address, 'disconnected!'
self.request.send('bye ' + str(self.client_address) + '\n')

#server host is a tuple ('host', port)
server = SocketServer.ThreadingTCPServer(('', 50008), MyServer)
server.serve_forever()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging and propagation

2007-11-22 Thread Vinay Sajip
On Nov 22, 2:34 pm, Vinay Sajip <[EMAIL PROTECTED]> wrote:
> On Nov 22, 9:18 am, oj <[EMAIL PROTECTED]> wrote:
>
> Why not apply the same filter to the parent loggers?

Of course, you can apply filters at the loggers or the handlers. The
filters at the logger are checked first. If they pass, then the event
is handled - and filters at the handlers get to participate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Neil Cerutti
On 2007-11-22, braver <[EMAIL PROTECTED]> wrote:
> On Nov 22, 10:37 am, Wayne Brehaut <[EMAIL PROTECTED]> wrote:
>> As others have already pointed out, "because it's seldom
>> necessary in Python".
>
> You know what?  I've read this many times, and it's a lot of
> self- congratulation.  There's lot of things which can be
> useful in Python.

But not all useful things should be in a library. Your use case
for eof may yield to a more general solution.

> This lack of EOF is inconvenient, there's nothing "Python way"
> about it, as a simple search on "EOF" or "eof" in this group
> demonstrates. Just a few threads:
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ed25388487b3ac7b

That person simply didn't know Python's idioms for processing
files.

> Here folks fight the same problem in one way uglier than
> another. Iterators and whatnot are thrown at a poor li'l EOF:
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/b09d612e99f67561
>
> The recurrence of the question simply shows Python lacks an
> f.eof() method.  That's all!
>
> Why do we may need it?  The last thread shows clearly -- because the
> last line processing is often a special case.  After I couldn't
> find the f.eof() in Python docs, I've quickly changed the logic
> to this (extracts):

You'll be better off with a general-purpose generator that allows
special handling for the last item.

http://groups.google.com/group/comp.lang.python/msg/703a513332d48dd4?dmode=source

> filesize = os.stat(filename)[6]
> cur_size = 0
>
> def eof():
>   return cur_size == filesize
>
> def add_line(line):
>   self.cur_size += len(line)
>...
>   if eof():
>   print >>sys.stderr, "* * * eof * * *"

For text mode files, the number of characters is not always equal
to the file's size in bytes.

> There's nothing special about Python except indentation, which
> gets screwed up between editors all the time.  (It's much
> easier to flip- flop between TextMate and Emacs with Ruby than
> with Python, without setting your tabs and spaces
> pedantically.)  

That horse is dead, buried, decayed, and there's a fig tree
growing out of the gravesight. Have a fig.

> It's faster than Ruby, otherwise they're similar.  When Ruby
> X.Y gets faster, it'll be a tough call to between 'em.  I use
> Python to accomplish things I know how, with algorithms which
> work and proven control logic, so this is reasonable to ask
> about certain control flow equivalents.  And comparisons will
> always be good.  :)

Language comparisons are sometimes good. They are best when
they are free of FUD.

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


Re: logging and propagation

2007-11-22 Thread Vinay Sajip
On Nov 22, 9:18 am, oj <[EMAIL PROTECTED]> wrote:
> On Nov 22, 5:44 am, Vinay Sajip <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Nov 21, 11:38 am, oj <[EMAIL PROTECTED]> wrote:
>
> > > Hi,
>
> > > I want to setuploggingwith two loggers:
>
> > > The child logger is used when something different needs to be done
> > > with the log record, and the log record will propagate and be logged
> > > by the root logger as usual.
>
> > > However, there are certain times when I don't want a log record to
> > > propagate from the child to the parent.
>
> > > I don't really want to add a filter to the root logger, as it should
> > > be up to the child whether the record propagates or not.
>
> > > I've tried setting the child to a lower level then the parent, but if
> > > a record is dealt with by the child, the parent deals with it anyway
> > > regardless of its own log level.
>
> > > Also, filters only apply particular handlers and do not affect
> > > propagation.
>
> > > Can anyone suggest a simple way to achieve this?
>
> > > Currently, the only thing I can think of, is overriding the
> > > callHandlers method in a custom Logger class.
>
> > Do you already have a Logger subclass? Where and when is the decision
> > being made about whether to propagate or not?
>
> The decision is being made in a filter. Certain log records are dealt
> with differently from there.
>
> The filter also prevents the handler from dealing with those log
> records, but it doesn't stop the handlers of parent loggers dealing
> with them.

Why not apply the same filter to the parent loggers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 06:53:59AM -0800, braver wrote regarding Re: eof:
> 
> > Language comparisons are sometimes good. They are best when
> > they are free of FUD.
> 
> So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)

Because that's not how you compare languages.  You compare languages by stating 
what you are actually trying to do, and figuring out the most natural solution 
in each language.  Not "I can do this in x--how come I can't do it in y?" 

Cheers,
Cliff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread braver
On Nov 22, 6:10 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Granted, they aren't part of the stdlib - but then, lots
> of things aren't.

As Hendrik noticed, I can't even add my own f.eof() if I want to have
buffering -- is that right?  The tradeoff between speed and
convenience is something I'd rather determine and enable myself, if I
have the right tools.

Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Hrvoje Niksic
braver <[EMAIL PROTECTED]> writes:

> On Nov 22, 6:10 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> Granted, they aren't part of the stdlib - but then, lots
>> of things aren't.
>
> As Hendrik noticed, I can't even add my own f.eof() if I want to
> have buffering -- is that right?

You can, you just need to inherit from built-in file type.  Then
instances of your class get the __dict__ and with it the ability to
attach arbitrary information to any instance.  For example:

class MyFile(file):
  def __init__(self, *args, **kwds):
file.__init__(self, *args, **kwds)
self.eof = False

  def read(self, size=None):
  if size is None:
  val = file.read(self)
  self.eof = True
  else:
  val = file.read(self, size)
  if len(val) < size:
  self.eof = True
  return val

  def readline(self, size=None):
  if size is None:
  val = file.readline(self)
  else:
  val = file.readline(self, size)
  if len(val) == 0:
  self.eof = True
  return val

The code needed to support iteration is left as an excercise for the
reader.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 100% CPU Usage when a tcp client is disconnected

2007-11-22 Thread Hrvoje Niksic
Tzury Bar Yochay <[EMAIL PROTECTED]> writes:

> The following is a code I am using for a simple tcp echo server.
> When I run it and then connect to it (with Telnet for example) if I
> shout down the telnet the CPU tops 100% of usage and saty there
> forever.  Can one tell what am I doing wrong?

If you shut down telnet, self.request.recv(1024) returns an empty
string, meaning EOF, and you start inflooping.

> def handle(self):
> while 1:
> data = self.request.recv(1024)
> self.request.send(data)
> if data.strip() == 'bye':  # add: or data == ''
> return
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread braver
On Nov 22, 6:40 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:

> You yourself said that performance is a complaint of yours regarding Ruby, so 
> why claim that Ruby's way is clearly better in a case where it causes a known 
> performance hit?

See Hrvoje's remark above -- we can have EOF and eat it too!  Perhaps
it was just somehow omitted from the standard Python library because
it disliked by some folks or just forgotten.  Is there a history of
the eof()'s fall from grace?  Was it ever considered for inclusion?

Cheers,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 100% CPU Usage when a tcp client is disconnected

2007-11-22 Thread Tzury Bar Yochay
> data = "dummy"
> while data:
> ...

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


Re: eof

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 07:17:41AM -0800, braver wrote regarding Re: eof:
> 
> On Nov 22, 6:08 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> 
> > > So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)
> 
> > Because that's not how you compare languages.  You compare languages by 
> > stating what you are actually trying to do, and figuring out the most 
> > natural solution in each language.  Not "I can do this in x--how come I 
> > can't do it in y?"
> 
> Python doesn't have f.eof() because it doesn't compare to Ruby?  Or
> because I'm trying to compare them?  :)  That's giving up to Ruby too
> early!
> 

No and no, to your two questions.  I'm not giving up on Ruby at all.  In fact, 
I've never tried Ruby.  My point isn't that the languages don't compare.  My 
point is that your question shouldn't be "why doesn't python have an eof method 
on its file objects?"  Your question should be "I want to do something 
different with the last line of a file that I iterate over.  How do I do that 
best in python?"  You've been given a couple solutions, and a very valid reason 
(performance) why buffered file objects are not the default.  You may also 
consider trying subclassing file with a buffered file object that provides 
self.eof.  (I recommend making it an attribute rather than a method.  Set it 
when you hit eof.)  That way you have the fast version, and the robust version.

You may find something of interest in the for/else construction as well

for line in file:
pass
else:
# This gets processed at the end unless you break out of the for loop.
pass


> Ruby has iterators and generators too, but it also has my good ol'
> f.eof().  I challenge the assumption here of some majectically Python-
> wayist spirit forbidding Python to have f.eof(), while Ruby, which has
> all the same features, has it.  Saying "it's not the Python way" is
> not a valid argument.
> 

No, but showing a different python way is more valid, and if you were more 
forthcoming about your use case from the get-go, you would have gotten fewer 
vague answers.  

> The suspicion lurking in the thread above was that that has to do with
> Python IO buffering, that it somehow can't tell the f.eof() with
> automatic look-ahead/push-back/simulate read, as transparently an
> effectively as (in practice) Ruby does without much fuss.  The reason
> why such a useful feature -- useful not in Ruby or Perl or Pascal, but
> algorithmically -- is not present in Python is a recurrent mystery,
> evidenced in this group recurrently.
> 

A mystery which has been answered a couple times in this thread--it causes a 
performance hit, and python is designed so that you don't suffer that 
performance hit, unless you want it, so you have to program for it yourself.

You yourself said that performance is a complaint of yours regarding Ruby, so 
why claim that Ruby's way is clearly better in a case where it causes a known 
performance hit?

> Cheers,
> Alexy

Cheers,
Cliff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Research-oriented Python mailing list?

2007-11-22 Thread Michael Tobis
Perhaps what you are looking for is here:

http://www.scipy.org/Mailing_Lists

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


Re: 100% CPU Usage when a tcp client is disconnected

2007-11-22 Thread Tzury Bar Yochay
Thank Hrvoje as well
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extension to idle to clear screen - but how to write to screen?

2007-11-22 Thread owl
On Nov 17, 3:27 pm, Tal Einat <[EMAIL PROTECTED]> wrote:
> On Nov 15, 10:20 pm, owl <[EMAIL PROTECTED]> wrote:
>
>
>
> > and here I thought I was going to finally be able to change the world
> > AND contribute back to python with my amazing clear screen extension -
> > but I can't get it to work. ;(
>
> > Copying from ZoomHeight.py and someone else's clever print suggestion:
> > -
> > # My Clear extension: clear a window
>
> > class Clear:
>
> > menudefs = [
> > ('windows', [
> > ('_Clear', '<>'),
> >  ])
> > ]
>
> > def __init__(self, editwin):
> > self.editwin = editwin
>
> > def clear_event(self, event):
> > for i in range(60):
> > print
> > --
>
> > It shows up as a menu item, but does not do anything. No output,
> > nuffin.
> > I did get some sort of 'no connection msg' playing around which leads
> > me to believe that I can't really write to the window (at least not
> > this simplistically)...
>
> > Pointers?
>
> Try this:
> self.editiwin.write('\n'*60)
>
> - Tal Einat
> reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))],
>   [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3]
>
> P.S. Feel free to contact the idle-dev mailing list: idle-dev 
> python (dot) org

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


Re: why it is invalid syntax?

2007-11-22 Thread Stargaming
On Thu, 22 Nov 2007 03:24:48 -0800, cokofreedom wrote:

> On Nov 22, 10:58 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>> 2007/11/22, Stef Mientki <[EMAIL PROTECTED]>:
>>
>>
>>
>> > alf wrote:
>> > > Hi,
>>
>> > > I wonder why it is an invalid syntax:
>>
>> > >  >>> if 1: if 1: if 1: print 1
>> > >   File "", line 1
>> > > if 1: if 1: if 1: print 1
>>
>> > > or
>>
>> > >  >>> if 1: for i in range(10): print i
>> > >   File "", line 1
>> > > if 1: for i in range(10): print i
>>
>> > > I would expect one could nest :
>>
>> > Although I agree it might be quit unreadable for normal programmers,
>> > people who are used to writing math formula, (i.e. MatLab), this is
>> > not true.
>>
>> > Here another interesting one, that is accepted:
>>
>> >  self.nodes.extend ( [ ONode(shape,n,self) \
>> >for n in range(shape.Parent.N_Outputs)
>> >\ if shape.Type_Outputs[n] == type ] )
>>
>> That is a list comprehension
>>
>>
>>
>> > cheers,
>> > Stef
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> --
>> -- Guilherme H. Polo Goncalves
> 
> So acceptable usage (though disgusting :P) would be
> 
> while 1: print 'hello'; print 'goodbye'; exec(rm -rf *)

Nope::

exec(rm -rf *)
 ^
SyntaxError: invalid syntax

Even the syntactically correct ``exec("rm -rf *")`` would make your 
computer explode. Should we introduce this as a shortcut to `break`? ;-)

SCNR,
stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Thomas Bellman
Hrvoje Niksic <[EMAIL PROTECTED]> wrote:

> I don't get it, Python's files are implemented on top of stdio FILE
> objects, which do buffering and provide EOF checking (of the sort
> where you can check if a previous read hit the EOF, but still).  Why
> not export that functionality?

Alexy wants to check if a file is about to hit EOF, not if it has
already hit EOF.  Stdio does not support that.  Nor does Unix.
The only way to check if the file is about to hit EOF, is to
actually perform a read and see if it returns zero bytes.  That
is usually OK to do on plain files, but on pipes, sockets or
terminals, you would have major problems, since suddenly calling
the eof() method would block the process.  Probably not what you
were expecting.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Life IS pain, highness.  Anyone who tells   !  bellman @ lysator.liu.se
 differently is selling something."  !  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: why it is invalid syntax?

2007-11-22 Thread cokofreedom
On Nov 22, 5:46 pm, Stargaming <[EMAIL PROTECTED]> wrote:
> On Thu, 22 Nov 2007 03:24:48 -0800, cokofreedom wrote:
> > On Nov 22, 10:58 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> >> 2007/11/22, Stef Mientki <[EMAIL PROTECTED]>:
>
> >> > alf wrote:
> >> > > Hi,
>
> >> > > I wonder why it is an invalid syntax:
>
> >> > >  >>> if 1: if 1: if 1: print 1
> >> > >   File "", line 1
> >> > > if 1: if 1: if 1: print 1
>
> >> > > or
>
> >> > >  >>> if 1: for i in range(10): print i
> >> > >   File "", line 1
> >> > > if 1: for i in range(10): print i
>
> >> > > I would expect one could nest :
>
> >> > Although I agree it might be quit unreadable for normal programmers,
> >> > people who are used to writing math formula, (i.e. MatLab), this is
> >> > not true.
>
> >> > Here another interesting one, that is accepted:
>
> >> >  self.nodes.extend ( [ ONode(shape,n,self) \
> >> >for n in range(shape.Parent.N_Outputs)
> >> >\ if shape.Type_Outputs[n] == type ] )
>
> >> That is a list comprehension
>
> >> > cheers,
> >> > Stef
> >> > --
> >> >http://mail.python.org/mailman/listinfo/python-list
>
> >> --
> >> -- Guilherme H. Polo Goncalves
>
> > So acceptable usage (though disgusting :P) would be
>
> > while 1: print 'hello'; print 'goodbye'; exec(rm -rf *)
>
> Nope::
>
> exec(rm -rf *)
>  ^
> SyntaxError: invalid syntax
>
> Even the syntactically correct ``exec("rm -rf *")`` would make your
> computer explode. Should we introduce this as a shortcut to `break`? ;-)
>
> SCNR,
> stargaming

Haha, you are correct. I was tempted to actually trial and error the
code too much...

I feel it is an important thing to present to a new user however, much
like the infinite "alert message" because of their infinite loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks

2007-11-22 Thread Istvan Albert
On Nov 21, 12:15 am, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:

> I would say that that is now debatable. Overall mod_wsgi is probably a
> better package in terms of what it has to offer. Only thing against
> mod_wsgi at this point is peoples willingness to accept something that
> is new in conjunction with Linux distributions and web hosting
> companies being slow to adopt new packages.

Yes that is to be expected, many people want someone else to pay the
early adopter's costs. Nonetheless mod_wsgi seems like the right
direction to move the python world.

One confounding factor that may slow its adoption could be the need of
running plain old CGI in an efficient way. I'm not sure how that fits
into the WSGI picture.

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


Re: Problems with if/elif statement syntax

2007-11-22 Thread Scott David Daniels
Neil Webster wrote:
> Hi all,
> 
> I'm sure I'm doing something wrong but after lots of searching and
> reading I can't work it out and was wondering if anybody can help?
> 
> I've got the following block of code:
>   if a >= 20 and a < 100:
>   if c == "c":
>   radius = 500
>   else:
>   radius = 250
>   elif (a >= 100) and (a < 500):
>   radius = 500
>   elif (a >= 500) and (a < 1000):
>   radius = 1000
>   elif (a >= 1000) and (a < 3000):
>   radius = 1500
>   elif (a >= 3000) and (a < 5000):
>   radius = 2000
>   else:
>   radius = 4000
> 
> No matter what value goes in for 'a' the radius always comes out as
> 4000.
> 
> What am I doing wrong?
> 
> Cheers
> 
> Neil
You might try something like:

 BOUNDS = [(500, 500), (1000, 1000),
   (3000, 1500), (5000, 2000), (0, 4000)]
 if a < 20:
 raise ValueError('Too tiny: %r' % a)
 if a < 100:
 if c == "c":
 radius = 500
 else:
 radius = 250
 else:
 for limit, radius in bounds:
 if a < limit:
 break


on the theory that it makes it easier to see what you
are driving the number towards.  I'd even add an upper bound
check myself, so I could see other garbage coming in.

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


Re: eof

2007-11-22 Thread Neil Cerutti
On 2007-11-22, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
>
 Language comparisons are sometimes good. They are best when
 they are free of FUD.
>>>
>>> So why Python's IO cannot yield f.eof() as easily as Ruby's can?  :)
>>
>> Because that requires buffering, something that affects speed.
>
> I don't get it, Python's files are implemented on top of stdio
> FILE objects, which do buffering and provide EOF checking (of
> the sort where you can check if a previous read hit the EOF,
> but still).  Why not export that functionality?

You have to make a failed read attempt before feof returns true.

>> Considering your own repeated remarks about "I'd only use ruby
>> if it wasn't slower than Python", I'd think you could value
>> that.
>
> I see no reason why exposing the EOF check would slow things down.

I think it's too low level, and so doesn't do what naive users
expect. It's really only useful, even in C, as part of the
forensic study of a stream in an error state, yet naive C
programmers often write code like:

while (!f.feof()) {
  /* Read a line and process it.
}

...and are flumoxed by the way it fails to work.

I think Python is well rid of such a seldomly useful source of
confusion.

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


Re: 100% CPU Usage when a tcp client is disconnected

2007-11-22 Thread Scott David Daniels
Aaron Watters wrote:
> On Nov 22, 9:53 am, Tzury Bar Yochay <[EMAIL PROTECTED]> wrote:
>> The following is a code I am using for a simple tcp echo server.
>> When I run it and then connect to it (with Telnet for example) if I
>> shout down the telnet the CPU tops 100% of usage and saty there
>> forever
>> def handle(self):
>> while 1:
>> data = self.request.recv(1024)
>> self.request.send(data)
>> if data.strip() == 'bye':
>> return
> ... Try changing it to ...
> data = "dummy"
> while data:
> ...

Even better:
 from functools import partial

 def handle(self):
 for data in iter(partial(self.request.recv, 1024), ''):
 self.request.send(data)
 if data.strip() == 'bye':
 break
 else:
 raise ValueError('Gone w/o a "bye"')  # or IOError

-Scott

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


error handling

2007-11-22 Thread [EMAIL PROTECTED]
i want to capture run time errors so that the execution of program doesnt
stop. like i want an error handler function ( that will email me or
something like that ) on error and not stop the execution of program.
how do i do this? i can not use try except for this...
thanks
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Research-oriented Python mailing list?

2007-11-22 Thread Jaap Spies
Michael Tobis wrote:
> Perhaps what you are looking for is here:
> 
> http://www.scipy.org/Mailing_Lists
> 
> mt

Or here:

http://www.sagemath.org/
http://www.sagemath.org/lists.html

Jaap

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


Subprocess and 16-bit FORTRAN

2007-11-22 Thread Federico Ceccatto
Hello,

For the past year I've been building an XP Python/wxPython shell of
sorts for several dozen command line FORTRAN tools developed for
various material science problems. Given how the methods and how-to's
have been lost to everyone but the original creators for these 80's to
90's pieces of code and the fact I am no physicist, I've relied on the
subprocess module in order to feed info according to their output.

I/O in general has worked wonders up to a handful of applications that
act in the strangest of ways. I strongly believe it's a bug in the
original programs/compiler, but that gets me nowhere. There's also the
fact the error shows up in two tools compiled with different FORTRAN
versions and made by different authors. I'll probably go cry for help
in a FORTRAN forum too.

Can't quite paste code due to its size and threaded nature, but
basically I have the output PIPE rigged to a class that parses text
into a tidy list (for easier analyzing), and a function that returns
input characters to the stdin method of the subprocess object
according to wether there has been any new data from stdout and
certain conditions (specific to the executable) are met.

I've got prints and repr()s everywhere to check nothing is ignored,
written multiple times or the child process is reporting errors. As I
mentioned, it works wonders for several other executables. None of the
obvious errors seem to be the case. As far as I can tell, the
input/output is ideal until the misbehaviour described below rears its
ugly head.

This is the kind of 'bugs' i've run into, perhaps someone could shed
some light onto them?

- Sometimes execution of child process (in this case, NTVDM.exe and
its children) stops and the object is destroyed for no reason
whatsoever. Very silent, no errors.

- Sometimes '\x03' as input is ignored, working simply as a '\n' of
sorts, while most of the time it simply kills the program as expected.

- Sometimes specific points in the code where the user is asked for
input and execution should be temporarily halted are ignored, as if
somehow it got a newline character.

None of these bugs are reproducible by running the same child
processess via NTVDM.exe through say, cmd.exe and such.

This has been driving me nuts for the last three weeks...

Thanks for your time.

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


Re: the annoying, verbose self

2007-11-22 Thread Ayaz Ahmed Khan
braver wrote:

> Is there any trick to get rid of having to type the annoying,
> character-eating "self." prefix everywhere in a class?  Sometimes I
> avoid OO just not to deal with its verbosity.  In fact, I try to use
> Ruby anywhere speed is not crucial especially for @ prefix is better-
> looking than self.

I've never really understood why some people find that annoying to do.  I 
make it a point to use, for example, the `this` operator when writing C++ 
code to avoid implicilty calling/accessing attributes of objects as much 
as possible.

-- 
Ayaz Ahmed Khan



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


Re: how terminate console(not Ctrl-C)

2007-11-22 Thread oj
On Nov 22, 3:58 am, NoName <[EMAIL PROTECTED]> wrote:
> Is it possible to interrupt loop (program) by pressing Q key like Ctrl-
> C?
> how can i hook user's keypress while program running?
>
> thnx

There's a quite complicated example here:

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

But it seems to just boil down to fiddling around with tty, and then
using select to read from sys.stdin to detect a keypress, and then
taking the appropriate action.

This will be different on Windows. If you really need this, it might
be worth looking for a library that will make key press detection
trivial. For example, this sort of thing is easy with pygame.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: foldr function in Python

2007-11-22 Thread oj
On Nov 22, 3:02 pm, Ant <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I've just been reading with interest this 
> article:http://caos.di.uminho.pt/~ulisses/blog/2007/11/20/foldr-the-magic-fun...
>
> It's a useful function that (with a more intuitive name) could prove a
> compelling addition to the itertools module. In it's python form, it
> would be something like this:
>
> def reduce2 (fn, init, seq):
>  return reduce(fn, seq, init)
>
> def foldr (function, initial):
> return partial(reduce2, function, initial)
>
> It's a bit different from the other itertools functions, in that
> rather than producing an iterator, it produces a function which
> reduces a iterator to a singe value.
>
> The advantages I see over reduce are that (a) it provides incentive to
> document the code and (b) it promotes reuse. For example:
>
> value = reduce(lambda x, y: "%s%s%s" % (x, "," if x else "", y),
> myList, "")
>
> vs.
>
> commaSeparate = foldr(lambda x, y: "%s%s%s" % (x, "," if x else "",
> y), "")
> commaSeparate(myList)
>
> Of course the lambda function in this case could be a named function,
> helping with both readability and reuse, but I think the latter is
> conceptually easier to grasp when reading the code.
>
> Discuss.
>
> --
> Ant.

It's basically just one line to implement:

foldr = lambda f, i: lambda s: reduce(f, s, i)

It's just reduce with currying, I'm not sure it adds that much to what
python already offers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-22 Thread Bruno Desthuilliers
Colin J. Williams a écrit :
> [EMAIL PROTECTED] wrote:
> 
>> Alexy:
>>
>>> Sometimes I
>>> avoid OO just not to deal with its verbosity.  In fact, I try to use
>>> Ruby anywhere speed is not crucial especially for @ prefix is better-
>>> looking than self.
>>
>>
>> Ruby speed will increase, don't worry, as more people will use it.
>>
>> Bye,
>> bearophile
> 
> 
> I don't see this as a big deal, but suppose that the syntax were
> expanded so that, in a method, a dot ".", as a precursor to an identifier,
> was treated as "self." is currently treated?



Python's "methods" are thin wrapper around functions, created at lookup 
time (by the __get__ method of the function type). What you define in a 
class statement are plain functions, period. So there's just no way to 
do what you're suggesting.



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


Re: Python web frameworks

2007-11-22 Thread Ian Bicking
On Nov 20, 7:55 am, "Joe Riopel" <[EMAIL PROTECTED]> wrote:
> On Nov 20, 2007 8:46 AM, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
>
> >  Django comes with its own little server so that you don't have
> > to set up Apache on your desktop to play with it.
>
> Pylons too, it's good for development but using the bundled web server
> is not recommended for production.

It's actually fine to use it for production.  There's two servers that
are used commonly with Pylons, the one in Paste and the CherryPy
server (it's a one-line configuration change to switch).  The
generally recommended production deployment is using one of these,
with another HTTP server in front proxying requests back.  There's
lots of side-benefits to that particular setup, like hosting the
Pylons app alongside static files, PHP, etc.  But there's quite a few
people who serve directly from Python (probably more often using the
CherryPy server, though I don't really know the differences in a
production situation).

Anyway, mostly an aside for choosing a framework.

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


Re: Zipf test in Python

2007-11-22 Thread Terry Reedy
When you start a new topic, you should start a *new* thread/post/message 
(depending on your news client) rather than responding to an existing 
thread.
This will not be seen by anyone with a modern newsreader that collapses 
threads to one line who does not expand the 'invalid syntax' thread this 
was posted under.


"Albert-jan Roskam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi,
|
| I have hospital data for 5 groups of hospitals. Each
| group of hospitals used a different tool to register
| medical procedures. Since the medical procedures are
| probably Zipf distributed, I want to formally test
| whether the hospitals differ in terms of
| procedure-ditribution. Is there a Python module that
| can do that? All I could find was ZipfR, a package for

no idea 



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


Re: Research-oriented Python mailing list?

2007-11-22 Thread Terry Reedy

"Albert-jan Roskam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi again,
|
| One more Q: I was wondering if there exists a more
| research-oriented Python listserv. This one is good
| (or so it seems, I'm just a newbie!), but the topics
| are very broad. Suggestions, anyone?

gmane.org presents technical mailing lists in newsgroup format.
gmane.comp.python.* has over 200 entries. 



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


Re: Python Windows installation

2007-11-22 Thread Martin v. Löwis
> does anyone know how I can automate installation of the Windows Python
> distribution, using python1.5.1.msi ?

See

http://www.python.org/download/releases/2.5/

then follow the link "automated installation" to

http://www.python.org/download/releases/2.5/msi/#automated

> I want to be able to run the installation without user interaction, and
> pass default parameters (instead of user entries), during the
> installation process. This can be done with other .msi packages and I
> was wondering if anyone has done this for the python setup package.

It can be done with *any* MSI package, and always in the same manner.

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


How to read gzipped utf8 file in Python?

2007-11-22 Thread John Nagle
   I have a large (gigabytes) file which is encoded in UTF-8 and then
compressed with gzip.  I'd like to read it with the "gzip" module
and "utf8" decoding.  The obvious approach is

fd = gzip.open(fname, 'rb',encoding='utf8')

But "gzip.open" doesn't support an "encoding" parameter.  (It
probably should, for consistency.)  Is there some way to do this?
Is it possible to express "unzip, then decode utf8" via
"codecs.open"?

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


pre-ANN: DVEdit - Video Editing the Python Way

2007-11-22 Thread DavidM
Hi fellow pythonistas,

I've put up an initial pre-alpha release of DVEdit - a highly pythonic
free/opensource framework for scripted video editing and production.

http://www.freenet.org.nz/dvedit

It's in very early stages, mainly proof of concept, but I feel pretty
happy with the core classes and concepts. Needs a lot of work to flesh out.
If there's enough interest, I'll make a Sourceforge project for it and
open it up for community participation. Contact details are on the front
page.

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


Re: How to read gzipped utf8 file in Python?

2007-11-22 Thread Martin v. Löwis
>   I have a large (gigabytes) file which is encoded in UTF-8 and then
> compressed with gzip.  I'd like to read it with the "gzip" module
> and "utf8" decoding.

You didn't specify the processing you want to perform. For example,
this should work just fine

fd = gzip.open(fname, 'rb')
for line in fd.readline():
pass

For that processing, it is not even necessary to know what the encoding
of the file is, except that it is an ASCII superset (which UTF-8 is).

> The obvious approach is
> 
> fd = gzip.open(fname, 'rb',encoding='utf8')
> 
> But "gzip.open" doesn't support an "encoding" parameter.  (It
> probably should, for consistency.)

I think I disagree. The builtin open function does not support an
encoding argument, either (in Python 2.x). Conceptually, gzip operates
on byte streams, not character streams.

> Is it possible to express "unzip, then decode utf8" via
> "codecs.open"?

If that's the processing you want to do - sure

fd0 = gzip.open(fname, 'rb')
fd = codecs.getreader("utf-8")(fd0)
data = fd.readline()

You can combine that to

fd = codecs.getreader("utf-8")(gzip.open(fname))

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


Re: import pysqlite2 or import sqlite3?

2007-11-22 Thread Jan Claeys
Op Wed, 21 Nov 2007 21:11:59 +0100, schreef Hertha Steck:

> After a second look at the error message: when I installed Gentoo,
> Python 2.4 was installed, I got the new version a little later. And I
> think I installed Pysqlite 2.3.5 separately.
> 
> Python 2.5 comes with pysqlite - should I uninstall my version?

Some older software might still try to use the "external" pysqlite, so 
maybe you want to check that first before removing anything.

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


Re: the annoying, verbose self

2007-11-22 Thread Kay Schluehr
On Nov 22, 8:43 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Colin J. Williams a écrit :
>
>
>
> > [EMAIL PROTECTED] wrote:
>
> >> Alexy:
>
> >>> Sometimes I
> >>> avoid OO just not to deal with its verbosity.  In fact, I try to use
> >>> Ruby anywhere speed is not crucial especially for @ prefix is better-
> >>> looking than self.
>
> >> Ruby speed will increase, don't worry, as more people will use it.
>
> >> Bye,
> >> bearophile
>
> > I don't see this as a big deal, but suppose that the syntax were
> > expanded so that, in a method, a dot ".", as a precursor to an identifier,
> > was treated as "self." is currently treated?
>
> 
>
> Python's "methods" are thin wrapper around functions, created at lookup
> time (by the __get__ method of the function type). What you define in a
> class statement are plain functions, period. So there's just no way to
> do what you're suggesting.
>
> 

The object model is irrelevant here. The substitution is purely
syntactical and gets resolved at compile time:

def foo(first, ...):
.bar = ...

is always equivalent with:

def foo(first, ...):
first.bar = ...

and generates the same bytecode.

Whether this is helpfull, beautifull or necessary is another issue.

Kay


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


tidy project file organization (modules and tests)

2007-11-22 Thread bramble
What's the customary way to organize your project files --
particularly modules? Does the following look correct?

my_project/
main_script.py
doc/
[...]
whatever/
[...]
lib/
mymod1.py
mymod2.py
test/
test_mymod1.py
test_mymod2.py
some_pkg/
__init__.py
goodmod1.py
goodmod2.py
test/
test_goodmod1.py
test_goodmod2.py

That is, my project may contain some local project-specific modules
(mymod1, mymod2), but also some in a package that I reuse here and
there in other projects too (some_pkg.goodmod1, some_pkg.goodmod2).

What's the usual name and placement of the file that runs all the
tests?

Finally, if anyone could point me toward any exemplary modules in the
cheeshop that have a tidy project file layout, it would be most
helpful.

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


Re: trace module and doctest

2007-11-22 Thread John J. Lee
[EMAIL PROTECTED] writes:

> I am trying to use the trace module with the --count flag to test for
> statement coverage in my doctests.  The trace coverage listing is very
> weird, marking many statements as unexecuted which were clearly executed
> during the run (I can see their output on the screen).  Is this some known
> interaction between the trace and doctest modules?

Yes:

http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py

http://svn.zope.org/Zope3/trunk/src/zope/testing/doctest.py?rev=28679&r1=28703&r2=28705


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


Re: Python too complex ?!?!?!

2007-11-22 Thread John J. Lee
"Chris Mellon" <[EMAIL PROTECTED]> writes:

> On Nov 20, 2007 2:43 PM, John J. Lee <[EMAIL PROTECTED]> wrote:
>> "Chris Mellon" <[EMAIL PROTECTED]> writes:
>> [...]
>> > These modules exist, but aren't that common. Certainly anything you're
>> > likely to be using in an introductory compsci course is well packaged.
>> > And even if it's not, it's really not that hard to create packages or
>> > installers - a days work of course prep would take care of the
>> > potential problem.
>>
>> "A day's worth of course prep" for beginners would let them debug all
>> the crap that building MySQLdb on Windows might throw at them, for
>> example?  I think not! (MySQLdb, last time I looked, was one of the
>> not-so-obscure modules that don't have a Windows installer available
>> and kept up to date.  Maybe it does now, but that's not really the
>> point.)
>>
>
> A days worth of course prep would allow the professor (or his TA, more
> likely) to produce a set of installers that's suitable for use with
> the course. This is a comp sci course, not a "how to sysadmin a Python
> installation" course.

Ah, sorry, misread what you wrote.  I made the same point in my next
paragraph, so perhaps the misunderstanding's mutual :-)


> For the record, it took me less than 3 minutes to install MySqldb, the
> first time I've ever needed to do it - I don't like or approve of
> MySql. Steps required: Google for "mysql python" and click through 3
> or 4 links to the SF download page. Download the binary installer,
> from March 2007. Not exactly rocket science.

That's great, though I don't see the connection with what I wrote.

Within the last year or so (IIRC) a MySQLdb Windows installer was not
available.  And ISTR grumpy noises coming from the corner of the
ReportLab office where AFAIK the only Windows binary publically
available shortly thereafter was built -- albeit an unofficial,
unsupported binary.  So I guess the fact that the MySQLdb maintainer
wasn't (isn't?) a Windows user didn't make the build process silky-
smooth ;-)

My point was that it's by no means unheard of for popular Python
modules to be unavailable as Windows binary installers.


> On a similar note, I have or create executable installers for all the
> third party modules I use, because I need to provide them to the
> people who do our deployments. This has never been much of a burden.
[...]

That's nice too.  Other people have not found it so easy.  OTOH, ISTR
that current MinGW / MSYS / Python / distutils make it easier for
people who don't have the appropriate MS compiler, so perhaps the
situation has improved over the last 12 months...


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


Re: Python too complex ?!?!?!

2007-11-22 Thread Brian
Chris Mellon wrote:
> On Nov 20, 2007 2:43 PM, John J. Lee <[EMAIL PROTECTED]> wrote:
>> "Chris Mellon" <[EMAIL PROTECTED]> writes:
>> [...]
>>> These modules exist, but aren't that common. Certainly anything you're
>>> likely to be using in an introductory compsci course is well packaged.
>>> And even if it's not, it's really not that hard to create packages or
>>> installers - a days work of course prep would take care of the
>>> potential problem.
>> "A day's worth of course prep" for beginners would let them debug all
>> the crap that building MySQLdb on Windows might throw at them, for
>> example?  I think not! (MySQLdb, last time I looked, was one of the
>> not-so-obscure modules that don't have a Windows installer available
>> and kept up to date.  Maybe it does now, but that's not really the
>> point.)
>>
> A days worth of course prep would allow the professor (or his TA, more
> likely) to produce a set of installers that's suitable for use with
> the course. This is a comp sci course, not a "how to sysadmin a Python
> installation" course.
> 
> For the record, it took me less than 3 minutes to install MySqldb, the
> first time I've ever needed to do it - I don't like or approve of
> MySql. Steps required: Google for "mysql python" and click through 3
> or 4 links to the SF download page. Download the binary installer,
> from March 2007. Not exactly rocket science.
> 
> On a similar note, I have or create executable installers for all the
> third party modules I use, because I need to provide them to the
> people who do our deployments. This has never been much of a burden.
> 
>> I certainly don't recognise what some people have been saying, though.
>> It's a rare thing that I have any real pain installing a Python module
>> on Linux.  That's not to say you don't need some background knowledge
>> about distributions and Python if doing it "by hand", of course
>> (rather than with a packaging tool like apt-get).  Occasionally you'll
>> want the newest version of something, which will in turn occasionally
>> get you into some grim automake issue or similar.  But all of this can
>> be entirely avoided in an introductory course -- simply restrict
>> yourself to what can be installed with apt-get (if the instructor
>> feels they *must* make some new library available, they can always
>> package it themselves).
>>
> The obstacles as presented in the OP seem pretty bogus to me. Of
> course, it's third hand anecdotal evidence, so there's not much of a
> reason to believe that the original statement really preserves the
> essence of the problem.
> 
> I'd be pretty interested if the OP could ask his associate to chime in
> with some of the actual issues he encountered

/ Chime Mode 
I have, in fact, sent this thread to my friend.
His limiting factors are

- money-control people favor MS platforms
- C# and VS have minimal cost impact for academia
- sys admins have everything locked down (probably 
essential for high school and community college)
- both Python 2.4.2, then 2.5.1, on XP and Win2k 
crashed approx 10% of lab cptrs, so lab techs refused 
to allow further install of any 'third-party' s/w. 
(side note - I have installed Python and all the 
supporting stuff for PyVISA on 14 work-site (11 XP, 3 
Debian) cptrs with no problem, so I do not understand).
- no such thing as TAs in JC or HS.
- CS instructors, for the effected schools, are not 
allowed to config machines or admin the network.
- money-control people want students to learn skills 
that are on the IT buzz-word list.
- my friend is no longer allowed to use me as an 
'unofficial' assistant in these classes (not considered 
qualified because I only have a B.S. degree), so he 
only uses stuff that existing staff are (supposedly) 
familiar with...
/ Chime Mode 

I told my friend, the wannabe Python instructor, to 
walk away from any more volunteer work, and stick to 
the paid stuff. American education, what a mess...

luck,
Brian
-- 
http://mail.python.org/mailman/listinfo/python-list


How to import xplt, pylab?

2007-11-22 Thread Caren Balea
Hello,

I'm newbie to python.

So far, I'm a bit disappointed. It's awful to set Python up to work.
It's not working!!!

Ok, calm down. Here are my settings:
I'm using Windows XP machine and have installed
Python 2.5.1.
Also, I have also installed something called "Cygwin" to type
in my commands.
Finally, I have installed scipy-0.6.0.

After starting Cygin I type

python
import math
import scipy
*
Then I try

import xplt

and get the message
Traceback (most recent call last):
File "", line 1, in 
ImportError: No module named xplt
*

Also I try

import pylab

and get the message
Traceback (most recent call last):
File "", line 1, in 
ImportError: No module named pylab

*

So, how can I use xplt and pylab???

Any help would be much appreciated!!!

Thank you,
Caren
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks

2007-11-22 Thread Graham Dumpleton
On Nov 23, 4:00 am, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Nov 21, 12:15 am, Graham Dumpleton <[EMAIL PROTECTED]>
> wrote:
>
> > I would say that that is now debatable. Overall mod_wsgi is probably a
> > better package in terms of what it has to offer. Only thing against
> > mod_wsgi at this point is peoples willingness to accept something that
> > is new in conjunction with Linux distributions and web hosting
> > companies being slow to adopt new packages.
>
> Yes that is to be expected, many people want someone else to pay the
> early adopter's costs. Nonetheless mod_wsgi seems like the right
> direction to move the python world.
>
> One confounding factor that may slow its adoption could be the need of
> running plain old CGI in an efficient way. I'm not sure how that fits
> into the WSGI picture.

Do note that using mod_wsgi doesn't preclude you still running plain
old CGI scripts using mod_cgi or mod_cgid. As to making it more
efficient, one can go two paths on this.

The preferred path would be to put in the effort to convert the Python
CGI application to WSGI. If one still needs to run it as CGI with
other hosting solutions, then use a CGI-WSGI adapter.

Second, albeit a bit of a kludge, just like mod_python.cgihandler is a
kludge, is to emulate the CGI environment on top of WSGI. This would
work if using single threaded Apache prefork MPM, or using mod_wsgi
daemon mode with multiple processes but where each is single threaded.
It wouldn't be practical though to do it for multithread Apache worker
MPM, or multithreaded daemon processes with mod_wsgi daemon mode.
Because of how Python leaks environment variables between sub
interpreters, you would also only want to be running one sub
interpreter within a process. This would be fine if using mod_wsgi
daemon mode as different CGI scripts could be delegated to run in
different daemon processes as necessary to keep them separate, but may
not be practical if using embedded mode if hosting a range of other
WSGI applications at the same time in embedded mode.

So, it is doable, but effort would be better off expended at least
converting the Python CGI script to WSGI instead. It would save a lot
of trouble in the long run, especially with CGI scripts which weren't
designed to be run multiple times in same memory context, ie., where
they don't clean up after themselves.

If someone really wanted to host an existing CGI script under WSGI
where the same process was used over and over, and had good reasons
for doing so, it wouldn't be hard for me to come up with a workable
adapter that allowed it.

Graham

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


Re: Clean way to get one's network IP address?

2007-11-22 Thread John J. Lee
Gilles Ganault <[EMAIL PROTECTED]> writes:

> I need to get the local computer's IP address, ie. what's displayed
> when running "ifconfig" in Linux:
>
> # ifconfig
> eth0  Link encap:Ethernet  HWaddr 00:15:58:A1:D5:6F  
>   inet addr:192.168.0.79  Bcast:192.168.0.255
> Mask:255.255.255.0
>
> I know about socket.gethostbyname, but this relies on what's in
> /etc/hosts, and I'd rather have a more independent solution.
>
> What would be a good way to do this?

Here's one way:

http://www.google.com/codesearch?hl=en&q=+class+IfConfig+show:qb29leCQ7IU:wjsmn477sKk:0dc7V3lzLaI&sa=N&cd=1&ct=rc&cs_p=ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-4-stable/All/linkchecker-4.5.tgz&cs_f=lib/python2.4/site-packages/linkcheck/dns/ifconfig.py#first


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


Re: the annoying, verbose self

2007-11-22 Thread Paul Boddie
On 22 Nov, 20:24, Ayaz Ahmed Khan <[EMAIL PROTECTED]> wrote:
>
> I've never really understood why some people find that annoying to do.  I
> make it a point to use, for example, the `this` operator when writing C++
> code to avoid implicilty calling/accessing attributes of objects as much
> as possible.

Precisely. One wonders whether the people complaining so vehemently
about self have ever encountered coding style guides.

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


Re: Python web frameworks

2007-11-22 Thread TYR
Perhaps we need a pythonic FRONTEND.

If you're meant to be able to run java code in a browser vm; and
flash; and javascript...why not a reduced version of python?

I'm thinking a sandboxed interpreter, perhaps based on EmbeddedPython,
and a restricted set of classes; core logic, string and maths, some
good graphics stuff (perhaps similar to nodebox), SSL support,
filesystem access to a cache, network, xml, soap support. A standard
model for development defining graphic entities on one hand, and
controls on the other that the graphics are bound to. Perhaps a single
class for "RemoteControls" covering web service calls intended to be
bound to a graphical entity at one end and a mod_python function at
the other?

Force pre-compiling into .pyc; include an app to do interactive
interpreter in a browser and some basic IDE functions with each plugin
download.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next float?

2007-11-22 Thread Mark Dickinson
On Nov 22, 5:41 pm, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Nov 21, 11:48 pm, "Mark T" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Here's some functions to get the binary representation of a float.  Then
> > just manipulate the bits (an exercise for the reader):
>
> > import struct
>
> > def f2b(f):
> > return struct.unpack('I',struct.pack('f',f))[0]
>
> > def b2f(b):
> > return struct.unpack('f',struct.pack('I',b))[0]
>
> > >>> f2b(1.0)
> > 1065353216
> > >>> hex(f2b(1.0))
> > '0x3f80'
> > >>> b2f(0x3f80)
> > 1.0
> > >>> b2f(0x3f81)
> > 1.001192092896
> > >>> b2f(0x3f7f)
>
> > 0.9994039535522
>
> And it's worth noting that thanks to the way the floating-point format
> is designed, the 'bit-twiddling' is actually just a matter of adding
> or subtracting one from the integer representation above.  This works
> all the way from zero, through subnormals, up to and including
> infinities.
>
> Mark (but not the same Mark)

And also worth noting that the 'f's above should probably be 'd's.
For example, the following works on my machine for positive floats.
Fixing this for negative floats is left as a not-very-hard exercise...

>>> from struct import pack, unpack
>>> def next_float(x): return unpack('d', pack('q', unpack('q', pack('d', 
>>> x))[0]+1))[0]
...
>>> next_float(1.0)
1.0002

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


Re: Next float?

2007-11-22 Thread Mark Dickinson
On Nov 21, 11:48 pm, "Mark T" <[EMAIL PROTECTED]> wrote:
> Here's some functions to get the binary representation of a float.  Then
> just manipulate the bits (an exercise for the reader):
>
> import struct
>
> def f2b(f):
> return struct.unpack('I',struct.pack('f',f))[0]
>
> def b2f(b):
> return struct.unpack('f',struct.pack('I',b))[0]
>
> >>> f2b(1.0)
> 1065353216
> >>> hex(f2b(1.0))
> '0x3f80'
> >>> b2f(0x3f80)
> 1.0
> >>> b2f(0x3f81)
> 1.001192092896
> >>> b2f(0x3f7f)
>
> 0.9994039535522

And it's worth noting that thanks to the way the floating-point format
is designed, the 'bit-twiddling' is actually just a matter of adding
or subtracting one from the integer representation above.  This works
all the way from zero, through subnormals, up to and including
infinities.

Mark (but not the same Mark)
-- 
http://mail.python.org/mailman/listinfo/python-list


The Python Papers is looking for additional Associate Editors

2007-11-22 Thread maurice ling

"The Python Papers" (http://pythonpapers.org), ISSN
1834-3147, is an online e-journal, covering articles
on Python in the community, industry and academia. We
were established in the second half of 2006 and
launched our first issue in November 2006. Since then,
we have released 3 more issues.

Recently, we have also initiated a monograph series,
which will be known as "The Python Papers Monograph
Series" (http://pythonpapers.org/monograph.html) with
its own ISSN, but managed by "The Python Papers"
Editorial Committee.

Due to this new initiative, we are looking for an
additional member to join the team as an Associate
Editor from February 2008.

The main roles of an Associate Editor includes:

1. Organizing and chairing reviews for submissions
2. Reviewing submissions
3. Answering queries regarding the periodicals
4. Assisting the Editor-in-Chief in tasks as required

The current workload is estimated to be about 3 hours
per week.

We invite committed individuals with a good knowledge
of Python programming to join our team.

Please send in your CV and a statement of intention to
us at [EMAIL PROTECTED] before December 20,
2007. Please direct any queries to
[EMAIL PROTECTED]

Thank you
Maurice Ling
Associate Editor, The Python Papers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import xplt, pylab?

2007-11-22 Thread J. Clifford Dyer
On Thu, Nov 22, 2007 at 02:00:00PM -0800, Caren Balea wrote regarding How to 
import xplt, pylab?:
> 
> Hello,
> 
> I'm newbie to python.
> 
> So far, I'm a bit disappointed. It's awful to set Python up to work.
> It's not working!!!
> 
> Ok, calm down. Here are my settings:
> I'm using Windows XP machine and have installed
> Python 2.5.1.
> Also, I have also installed something called "Cygwin" to type
> in my commands.
> Finally, I have installed scipy-0.6.0.
> 
> After starting Cygin I type
> 
> python
> import math
> import scipy
> *
> Then I try
> 
> import xplt
> 
> and get the message
> Traceback (most recent call last):
> File "", line 1, in 
> ImportError: No module named xplt
> *
> 

xplt is a module within scipy, so it will not be available at the top level.  
However, all you need to do is

py>>> from scipy.sandbox import xplt

or

py>>> import scipy.sandbox.xplt

The advantage of the former is that you can just use the names xplt.*, while 
with the latter you have to type scipy.sandbox.xplt.*.

> Also I try
> 
> import pylab
> 
> and get the message
> Traceback (most recent call last):
> File "", line 1, in 
> ImportError: No module named pylab
> 
> *
> 

I haven't worked with pylab, but it looks like you may need another install 
(matplotlib?)  I'm not sure.  I just did a quick google search.

> So, how can I use xplt and pylab???
> 
> Any help would be much appreciated!!!
> 
> Thank you,
> Caren

Happy Thankgiving hacking!

Cheers,
Cliff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to import xplt, pylab?

2007-11-22 Thread Caren Balea
On 22 Nov, 23:17, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> On Thu, Nov 22, 2007 at 02:00:00PM -0800, Caren Balea wrote regarding How to 
> import xplt, pylab?:
>
>
>
>
>
> > Hello,
>
> > I'm newbie to python.
>
> > So far, I'm a bit disappointed. It's awful to set Python up to work.
> > It's not working!!!
>
> > Ok, calm down. Here are my settings:
> > I'm using Windows XP machine and have installed
> > Python 2.5.1.
> > Also, I have also installed something called "Cygwin" to type
> > in my commands.
> > Finally, I have installed scipy-0.6.0.
>
> > After starting Cygin I type
>
> > python
> > import math
> > import scipy
> > *
> > Then I try
>
> > import xplt
>
> > and get the message
> > Traceback (most recent call last):
> > File "", line 1, in 
> > ImportError: No module named xplt
> > *
>
> xplt is a module within scipy, so it will not be available at the top level.  
> However, all you need to do is
>
> py>>> from scipy.sandbox import xplt
>
> or
>
> py>>> import scipy.sandbox.xplt
>
> The advantage of the former is that you can just use the names xplt.*, while 
> with the latter you have to type scipy.sandbox.xplt.*.
>
> > Also I try
>
> > import pylab
>
> > and get the message
> > Traceback (most recent call last):
> > File "", line 1, in 
> > ImportError: No module named pylab
>
> > *
>
> I haven't worked with pylab, but it looks like you may need another install 
> (matplotlib?)  I'm not sure.  I just did a quick google search.
>
> > So, how can I use xplt and pylab???
>
> > Any help would be much appreciated!!!
>
> > Thank you,
> > Caren
>
> Happy Thankgiving hacking!
>
> Cheers,
> Cliff

Thank you. I've tried both suggestions.
But they both don't work :(

Here are the outputs:

>>> import math
>>> import scipy
>>> from scipy.sandbox import xplt

Traceback (most recent call last):
  File "", line 1, in 
from scipy.sandbox import xplt
ImportError: cannot import name xplt
>>> import scipy.sandbox.xplt

Traceback (most recent call last):
  File "", line 1, in 
import scipy.sandbox.xplt
ImportError: No module named xplt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-22 Thread braver
On Nov 23, 1:15 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
One wonders whether the people complaining so vehemently
> about self have ever encountered coding style guides.

Dude, I'm also programming in Ada, 83 to 95 to 2005.  Beautiful
language, a living style guide.  I love typing names dozens of
charactares long -- in Ada.  Ada has scope control, separate
compilation, renames, overloading, types, etc...  However, in
scripting languages, it's not cool, and I'd just love to see self hide
for a bit of a change -- it's a nuisance after Ruby, 's all.  Nothing
eternal or worth assembling a NASA panel or Python foundation meeting,
just a li'l respite to make a tiny script more lucid, OK?

Peace,
Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >