ANN: Twisted version 2.0

2005-03-25 Thread Christopher Armstrong
http://twistedmatrix.com/

TASMANIA (DP) -- Found on the Internet on 2005-03-22 by an anonymous
programmer, Twisted 2.0 was obtained by local authorities and kept
isolated for public safety and further study.  On 2005-03-25, however,
nano-probes were released from the package's surface and propagated
the software to the public.

Version 2.0 is said to have originated from ancient underground ruins
somewhere in Australia, but their existence has not yet been verified.
Christopher Armstrong, enslaved release archaeologist, was only able
to say Aieeya!  Release??  What release?  I just found this here
tablet under some sand.  Ia!  Project lead Glyph Lefkowitz was not
available for comment, as he has fled the planet in fear of the
repercussions of the software's new release.

Record-keeper Mary Gardiner said It will be interesting to see if the
Twisted Sumo distribution collapses into a singularity.  I guess
there's a potential that Earth will be destroyed.

As of this release, radix's soul, which has been included in Twisted
since version 0.8.0, has been split off from the main project and
given back to him to maintain in a separate sub-project.



Twisted 2.0 is a major upgrade, changing many things not only in the
code but also in the structure of the project.  As of 2.0, Twisted was
split up into many sub-projects which you can read about in the
Twisted Split FAQ[1].

2.0 also marks the first release including the migration to the Zope
Interface framework as opposed to Twisted's own built-in
interface/adapter system.  Another FAQ was made available[2] for those
curious about the change.

Many, tons, and lots of other changes have been made in this release.
The NEWS[3] file contains a high-level overview of most of these
changes.  Changes in now-split subprojects are available on their
individual project pages[4].

Tarballs are currently available at the twistedmatrix.com site, and
packages for win32, Debian, and other OSes are currently on the way.

1: http://twistedmatrix.com/projects/core/documentation/upgrades/2.0/split.html
2: 
http://twistedmatrix.com/projects/core/documentation/upgrades/2.0/components.html
3: http://twistedmatrix.com/projects/core/NEWS.txt
4: http://twistedmatrix.com/projects/


WHAT IS TWISTED?

Twisted is an event-based framework for internet applications which
works on Python 2.2.X and 2.3.X.  The following are the (important)
modules included with Twisted:

  - twisted.application
A Service system that allows you to organize your application in
hierarchies with well-defined startup and dependency semantics,
  - twisted.cred
A general credentials and authentication system that facilitates
pluggable authentication backends,
  - twisted.enterprise
Asynchronous database access, compatible with any Python DBAPI2.0
modules,
  - twisted.internet
Low-level asynchronous networking APIs that allow you to define
your own protocols that run over certain transports,
  - twisted.manhole
A tool for remote debugging of your services which gives you a
Python interactive interpreter,
  - twisted.protocols
Basic protocol implementations and helpers for your own protocol
implementations,
  - twisted.python
A large set of utilities for Python tricks, reflection, text
processing, and anything else,
  - twisted.spread
A secure, fast remote object system,
  - twisted.trial
A unit testing framework that integrates well with Twisted-based code.


Twisted supports integration of the Tk, GTK+, GTK+ 2, Qt, Mac OS X, or
wxPython event loop with its main event loop. The Win32 event loop is
also supported.

For more information, visit http://www.twistedmatrix.com, or join the
list at
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

There are many official Twisted subprojects, including clients and
servers for web, mail, DNS, and more. You can find out more about
these projects at http://twistedmatrix.com/projects/



-- 
  Twisted   |  Christopher Armstrong: International Man of Twistery
   Radix|-- http://radix.twistedmatrix.com
|  Release Manager, Twisted Project
  \\\V///   |-- http://twistedmatrix.com
   |o O||  Founding Member, Hobart Hacking Society
wvw-+-- http://hackingsociety.org/chapters/hash
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ANN: PythonDoc 2.1 beta 3 (march 25, 2005)

2005-03-25 Thread Fredrik Lundh
PythonDoc is a documentation tool for Python, inspired by JavaDoc.

Like JavaDoc, PythonDoc scans your Python code for doc comments,
and generates API documentation in XML and HTML formats.  Python-
Doc supports basic JavaDoc tags like @param and @return, and adds
a few Python-specific tags.  You can use PythonDoc comments to
describe module-level variables and constants, functions, classes,
methods, and attributes.  PythonDoc comes with a standard HTML
generator, but you can plug in your own output handlers, or use
XSLT or other tools to process the PythonDoc XML format.

PythonDoc 2.1b3 parses docstrings and adds them to the XML model.
It also includes some minor bug fixes. See the README file for
details.

Downloads:

http://effbot.org/downloads#pythondoc
http://effbot.org/downloads#elementtree

Documentation:

http://effbot.org/zone/pythondoc.htm

enjoy /F

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Python for a 10-14 years old?

2005-03-25 Thread Paul Rubin
You might like the book Mindstorms, by Seymour Papert.  The intro
is here:

http://www.papert.org/articles/GearsOfMyChildhood.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded python example: PyString_FromString doesnt work?

2005-03-25 Thread Denis S. Otkidach
On Thu, 24 Mar 2005 21:12:18 + David Harris wrote:

DH int
DH main(int argc, char *argv[])
DH {
DH PyObject *pName, *s, *pModule, *pDict, *pFunc;
DH PyObject *pArgs, *pValue;
DH int i;
DH 
DH if (argc  3) {
DH fprintf(stderr,Usage: call pythonfile funcname [args]\n);
DH return 1;
DH }
DH 
DH 
DH Py_Initialize();
[...]
DH Calling the program gives an error;
DH [EMAIL PROTECTED]:~/source/python ./test_String script1.py  multiply 4
DH 5 import went bang...
DH ImportError: No module named script1.py
DH script1.py exists and it is in the same directory as the executable
DH so its not a path error or that kind of stuff.

I believe you have to call Py_SetProgramName before Py_Initialize, or
otherwise let Python know that it should look for modules in this
directory. See http://python.org/doc/current/api/embedding.html#l2h-40

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anonymus functions revisited : tuple actions

2005-03-25 Thread George Sakkis
Kay Schluehr [EMAIL PROTECTED] wrote:

 To make my intention clear for another time, also for George who
 mistrusts these exercises alltogether. I want to derive a syntax and
 semantics for anonymus functions ( called tuple-actions ) that are
 generalizations of rules that are already used implicitely within
 Python e.g. tuple-unpacking. This is done by progressive interpretation
 and extension. They are not there by means of an accident, what Guido
 claims about the current lambda which he feels to be sticked onto the
 language.

 Regards,
 Kay


I'd be glad to see a well-formulated view of the proposed tuple actions, 
provided I (and suspect
others) can get through the syntax burden first. Expressions such as 
While((i)-(0), (i)-i3,
(i)-(i+1), (res)-(res+i**2)) do not remind me the python I know and love. 
Alternatively, if it's
not easy to come up with a grokable syntax, I would still be ok with it if it 
remained under the
hood for the most part, like other obscure features such as metaclasses and 
descriptors; for
instance I wouldn't mind at all if the traditional control flow primitives were 
implemented as
functions using your idea, as long as I didn't have to know the details (and as 
long as other
things, e.g. execution speed, were the same).

As for the forthcoming - as it seems - deprecation or removal of lambdas, I'm 
in the minority that
thinks it's a step in the wrong direction. The way they ended up in the 
language may be a historic
accident, but I would favor a solution that improved them instead of removing 
them. The notion of
'anonymous functions' alone reveals a misconception in my opinion: that 
functions *have to* have a
name to be 'normal'. Still, a name is just a binding to an object that exists 
independently of the
name. We don't find 'anonymous strings', tuples, lists, etc. bad, so why should 
functions be
different ? In this respect, functions are not 100% first class objects. 
Instead of removing
lambdas, I would prefer to see them upgraded, perhaps with a new syntax, 
accepting more than one
expressions and statements instead of a single expression. Sure, one can define 
named functions
locally to avoid polluting the global scope, but why should he ? Just imagine 
how would python look
like with a similar rule for other primitive types. Anyway, I guess I can live 
without lambdas but
I'll miss them.

George



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


Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Antoon Pardon
Op 2005-03-24, Paul L. Du Bois schreef [EMAIL PROTECTED]:
 Has anyone written a Queue.Queue replacement that avoids busy-waiting?
 It doesn't matter if it uses os-specific APIs (eg
 WaitForMultipleObjects).  I did some googling around and haven't found
 anything so far.

I started once, using the Timer class in the Threading Module to
break the lock. However the Timer class uses the same kind of
sleep-polling loop, to delay the exection and allow an intermediate
cancel, as the loop that is used in Queue.Queue, so that was no
gain.

I have still played with the idea, but haven't worked anything out
since then.

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


Grouping code by indentation - feature or ******?

2005-03-25 Thread Tim Tyler
What do you guys think about Python's grouping of code via indentation?

Is it good - perhaps because it saves space and eliminates keypresses?

Or is it bad - perhaps because it makes program flow dependent on 
invisible, and unpronouncable characters - and results in more
manual alignment issues by preventing code formatters from managing
indentation?

Python is certainly pretty unorthodox in this area.

How would you have dealt with the issue of how to group statements?
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Peter Otten
Tim Tyler wrote:

 What do you guys think about Python's grouping of code via indentation?

This is a Python newsgroup. Assume that we all have been brainwashed.

 How would you have dealt with the issue of how to group statements?

Off the top of my head I can think of one other way: associate a wav file
with every grouping level and have your editor play it while you are
editing that particular level.

I think that would be very effective to get a Pythonista acknowledge the
merits of C/Pascal grouping markers -- noisy, but not *that* noisy...

Peter




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


Re: Python docs [was: function with a state]

2005-03-25 Thread John Bokma
Xah Lee wrote:

 The Python doc is relatively lousy, from content organization to the
 tech writing quality.

So write your own or fork the current one. I doubt if that's a problem.

Did you read Dive into Python?

-- 
John   Small Perl scripts: http://johnbokma.com/perl/
   Perl programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html

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


Re: Python docs [was: function with a state]

2005-03-25 Thread John Bokma
Martin Ambuhl wrote:

 Apologies to these various newsgroups, but I have no idea which one Xah 
 Lee actually reads or posts from.  F'ups set.

Probably none, since they are all crowded with crazy linux zealots :-D.

-- 
John   Small Perl scripts: http://johnbokma.com/perl/
   Perl programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html

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


Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Paul Rubin
Antoon Pardon [EMAIL PROTECTED] writes:
 I started once, using the Timer class in the Threading Module to
 break the lock. However the Timer class uses the same kind of
 sleep-polling loop, to delay the exection and allow an intermediate
 cancel, as the loop that is used in Queue.Queue, so that was no
 gain.

I've never checked this code but it wouldn't have occurred to me that
Queue uses any kind of timeout loop.  Can't it work the obvious way
with a semaphore?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing closed source modules

2005-03-25 Thread Fuzzyman

Dave Brueck wrote:
 Jiri Barton wrote:
[snip..]

Hello Dave,


 Protecting code in any language is pretty tough and/or futile, but
you can
 Google the archives if you're interested in reading more on that.


It's certainly something lot's of people are interested in. I guess it
depends who your audience is. If ytour code isn't for *mass*
distribution - the chances of people putting a lot of effort into
breaking it are greatly reduced. I don't htink it's necessarily futile.

 Anyway, you can create a module on the fly like this (untested):

 import new, sys
 name = 'MyModule'
 m = sys.modules[name] = new.module(name)
 exec codeStr in m.__dict__

 where codeStr is a string that contains the source code of your
module (e.g.
 from file('somemodule.py').read() ).


This is one of the better solutions I've seen. (Probably because it's
*not* very complex). The stored modules can be well encrypted.
Obviously the decryption code will be in the main code - but I guess it
can be obfuscated pretty well.

I like it.

Regards,

Fuzzy
http://www.voidspace.org.uk/python

 You can combine the above with whatever mechanism you come up with
for
 distributing the code itself. You could store it in an encrypted
archive file,
 you could download it on the fly from a remote server over a secure
connection, etc.
 
 -Dave

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


Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
 I started once, using the Timer class in the Threading Module to
 break the lock. However the Timer class uses the same kind of
 sleep-polling loop, to delay the exection and allow an intermediate
 cancel, as the loop that is used in Queue.Queue, so that was no
 gain.

 I've never checked this code but it wouldn't have occurred to me that
 Queue uses any kind of timeout loop.  Can't it work the obvious way
 with a semaphore?

And how is this semaphore going to be released if the timeout is
reached?

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


Re: embedded python example: PyString_FromString doesnt work?

2005-03-25 Thread Brano Zarnovican
 wierd. does:
http://www.python.org/doc/2.3.­2/ext/pure-embedding.html work
 for you ?

Yes. It does.

 ./test_String script1.py  multiply 4 5

Don't run it with the .py suffix. The argv[1] is a module name, not a
filename..

Even if you do, it may not find the module. Depending of what you have
in PYTHONPATH. Try also:

export PYTHONPATH=.

 I believe you have to call Py_SetProgramName before Py_Initialize,

Yes. This is another way to affect the search path.

BranoZ

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


POST data with 401 authentication using urllib(2)

2005-03-25 Thread Pieter Edelman
Hi all,

I'm trying to submit some data using a POST request to a HTTP server with
BASIC authentication with python, but I can't get it to work. Since it's
driving me completely nuts, so here's my cry for help.

The server is an elog logbook server (http://midas.psi.ch/elog/). It is
protected with a password and an empty username. I can login both using
urllib and urllib2 (suppose the password is foobar, the logbook is
running on port 8181, and I need the directory Artikelen)

urllib:
class AuthenticatedURL(urllib.FancyURLopener) :
  def prompt_user_passwd(this, host, realm):
return(, foobar)

url = AuthenticatedURL()
data = 
f = url.open(http://localhost:8181/Artikelen;)

urllib2:
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password('Artikelen', 'localhost:8181', '', 'foobar')
opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener)
f = urllib2.urlopen('http://localhost:8181/Artikelen')

So far so good. But I want to submit some data via CGI. I can do this by
making a GET request out of the URL:
f = url.open(http://localhost:8181/Artikelen/?cmd=Submitreply_to=80;)
This works as advertised (also with urllib2).

However, since I also need to upload files, I want to do this via a POST
request (as it is donenormally via the web interface). However, if I try
this using either urllib or urllib2, it throws an exception:

data = {cmd : Submit, reply_to : 80}

urllib:
f = url.open(http://localhost:8181/Artikelen/;, urllib.urlencode(data))
Traceback (most recent call last):
  File login.py, line 12, in ?
f = url.open(http://pde.dyndns.org:8181;, data)
  File /usr/lib/python2.3/urllib.py, line 183, in open
return getattr(self, name)(url, data)
  File /usr/lib/python2.3/urllib.py, line 308, in open_http
return self.http_error(url, fp, errcode, errmsg, headers, data)
  File /usr/lib/python2.3/urllib.py, line 323, in http_error
return self.http_error_default(url, fp, errcode, errmsg, headers)
  File /usr/lib/python2.3/urllib.py, line 551, in http_error_default
return addinfourl(fp, headers, http: + url)
  File /usr/lib/python2.3/urllib.py, line 837, in __init__
addbase.__init__(self, fp)
  File /usr/lib/python2.3/urllib.py, line 787, in __init__
self.read = self.fp.read
AttributeError: 'NoneType' object has no attribute 'read'

urllib2:
f = urllib2.urlopen('http://localhost:8181/Artikelen/',
  urllib.urlencode(data))
Traceback (most recent call last):
  File login2.py, line 11, in ?
f = urllib2.urlopen('http://localhost:8181/Artikelen/', data)
  File /usr/lib/python2.3/urllib2.py, line 129, in urlopen
return _opener.open(url, data)
  File /usr/lib/python2.3/urllib2.py, line 326, in open
'_open', req)
  File /usr/lib/python2.3/urllib2.py, line 306, in _call_chain
result = func(*args)
  File /usr/lib/python2.3/urllib2.py, line 901, in http_open
return self.do_open(httplib.HTTP, req)
  File /usr/lib/python2.3/urllib2.py, line 895, in do_open
return self.parent.error('http', req, fp, code, msg, hdrs)
  File /usr/lib/python2.3/urllib2.py, line 346, in error
result = self._call_chain(*args)
  File /usr/lib/python2.3/urllib2.py, line 306, in _call_chain
result = func(*args)
  File /usr/lib/python2.3/urllib2.py, line 659, in http_error_401
host, req, headers)
  File /usr/lib/python2.3/urllib2.py, line 638, in http_error_auth_reqed
return self.retry_http_basic_auth(host, req, realm)
  File /usr/lib/python2.3/urllib2.py, line 648, in retry_http_basic_auth
return self.parent.open(req)
  File /usr/lib/python2.3/urllib2.py, line 326, in open
'_open', req)
  File /usr/lib/python2.3/urllib2.py, line 306, in _call_chain
result = func(*args)
  File /usr/lib/python2.3/urllib2.py, line 901, in http_open
return self.do_open(httplib.HTTP, req)
  File /usr/lib/python2.3/urllib2.py, line 895, in do_open
return self.parent.error('http', req, fp, code, msg, hdrs)
  File /usr/lib/python2.3/urllib2.py, line 352, in error
return self._call_chain(*args)
  File /usr/lib/python2.3/urllib2.py, line 306, in _call_chain
result = func(*args)
  File /usr/lib/python2.3/urllib2.py, line 412, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error -1:

In fact, I get these exact same errors if data is empty. I'm
wondering if this is supported in python. I can't find anything about it
in TFM. If it's not supported, does anybody have an idea how to do it? If
it is supported, can anybody tell what I'm dowing wrong?

Any help is greatly appreciated.

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


Re: Python docs [was: function with a state]

2005-03-25 Thread axel
In comp.lang.perl.misc Xah Lee [EMAIL PROTECTED] wrote:
 The Python doc is relatively lousy, from content organization to the
 tech writing quality.

Which has precisely what to do with most of the groups to which you
cross-posted?

 Problem: They all have the same priority (which is higher than that of
 the Boolean operations).
 
 However, the ?they? pronoun from the context of previous sentence,
 refers to ?the comparison operation?, not ?operator?. So, it
 conjures the reader to think about some ?operation precedence?,
 which in itself cannot be ruled out as nonsense depending on the
 context. Very fucking stupid confusional writing.

The meaning is perfectly plain. By the way did you perhaps mean
'confusing' or 'confused'? I normally regard language flames
otiose but here, since you are trying to correct other people's
writing, fair game.

 And, from pure writing aspect, the sentence ?...(which is ...)?  is
 some kind of a juvenile latch on. If the author intent to make that

Do you mean... 'if the author's intent is to make' or 'if the author
intends to'?

 point, say it in its own sentence. e.g. The comparison operators have
 higher precedence than boolean operators. It would be better to not
 mention this at all. For practical considerations, very rare is the
 case of mixing boolean and comparison operators, and if so, parenthesis
 are likely used and is indeed a good practice. The proper place for

Should that not be 'parentheses are likely to be used'?

It is not rare at all. Besides, little asides like this are an ideal
way to reinforce thoughts about operator preference and more helpful
then memorising a table.

 Problem: Comparisons can be chained arbitrarily; for example, x  y =
 z is equivalent to x  y and y = z, except that y is evaluated only
 once (but in both cases z is not evaluated at all when x  y is found
 to be false).
 
 Drop the word ?arbitrarily?. It has no meaning here.

I suggest you look up the meaning of the word.
 
 the whole sentence is one fucked up verbiage of pell-mell thinking and
 writing. Here's one example of better:
 
 Comparisons can be chained, and is evaluated from left to right. For
 example, x  y = z is equivalent to (x  y) = z.

You mean 'are evaluated'. Your rephrasing is also incomplete since
it doesn't note that z will not be evaulated if x  y is false.

 With respect to documentation style, it is questionable that this
 aspect needs to be mentioned at all. In practice, if programers need to
 chain comparisons, they will readily do so. This is not out of ordinary
 in imperative languages, and evaluation from left to right is also not
 extraordinary to cost a mention.

Really? In a reference manual such matters should be fully specified
regardless of what happens in other languages.
 
 Problem:  and != are alternate spellings for the same operator. != is
 the preferred spelling;  is obsolescent
 
 In general, when something is obsolete or might go defunct in the
 future, consider not even mentioning that construct. If necessary, add
 it in a obscure place, and not adjacent to critical info. In many
 places of Python documentation, this is breached.

Really? Actually it is very important to mention it in the correct
place in a reference manual. Do you understand the concept of
maintaining old code?
 
 I'm in fact somewhat surprised by this poor quality in writing. The

Really? The writing in the manual seems simple, straight-forward and
clear to me (knowing no Python). Unlike your writing.

 more egregious error is the hardware-oriented organization aka
 technical drivel.

What on earth does this mean?

 The Python doc, though relatively incompetent, but the author have
 tried the best. This is in contrast to documentations in unix related
 things (unix tools, perl, apache, and so on etc), where the writers
 have absolutely no sense of clear writing, and in most cases don't give
 a damn and delight in drivel thinking of it as literary.

I think that this is an excellent description of your own writing.

Axel

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


Re: embedded python example: PyString_FromString doesnt work?

2005-03-25 Thread David Harris
On Fri, 25 Mar 2005 11:09:35 +0300, Denis S. Otkidach wrote:

 DH Calling the program gives an error;
 DH [EMAIL PROTECTED]:~/source/python ./test_String script1.py  multiply 4
 DH 5 import went bang...
 DH ImportError: No module named script1.py
 DH script1.py exists and it is in the same directory as the executable
 DH so its not a path error or that kind of stuff.
 
 I believe you have to call Py_SetProgramName before Py_Initialize, or
 otherwise let Python know that it should look for modules in this
 directory. See http://python.org/doc/current/api/embedding.html#l2h-40

excellent!! that was the tip (+ PySys_SetArgv) the worked ...

This now works:

int
main(int argc, char *argv[])
{
PyObject *pName, *s, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;

Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
pName = PyString_FromString(argv[1]);
...
}

Thanks a bunch denis :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An Abridged Python Tutorial

2005-03-25 Thread bruno modulix
Michael Spencer wrote:
An Abridged Python Tutorial
(snip fine piece of art)

applaude
--
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])
--
http://mail.python.org/mailman/listinfo/python-list


Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Paul Rubin
Antoon Pardon [EMAIL PROTECTED] writes:
  I've never checked this code but it wouldn't have occurred to me that
  Queue uses any kind of timeout loop.  Can't it work the obvious way
  with a semaphore?
 
 And how is this semaphore going to be released if the timeout is
 reached?

I meant a semaphore to synchronize the queue when adding or removing
objects.  Timeout would be handled with sigalarm or select.

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


Re: Anonymus functions revisited

2005-03-25 Thread Duncan Booth
Ron wrote:
 It's interesting that there is a whole is_type_() group of functions
 in the inspect module, but not a is_defined().  Maybe I just haven't
 found it yet.

I've never found any need for an is_defined function. If in doubt I just 
make sure and initialise all variables to a suitable value before use. 
However, I'll assume you have a good use case.

 
 
 #
 
 def if_not_defined(v, dv=None, lv=locals()):
 if lv.has_key(v):
 return lv[v]
 return dv

I don't see the point of the default argument. locals() at the global level 
simply returns globals, so you might as well use that. A more useful 
default would be the caller's locals.

 
 def is_defined(v, lv=locals()):
 if lv.has_key(v):
 return True
 False

Same comments, plus the whole 'if on a boolean to return a boolean' is a 
bit redundant.

Try something on these lines:

 import inspect
 def is_defined(name, lv=None):
if lv is None:
lv = inspect.currentframe().f_back.f_locals
return name in lv

 is_defined('abc')
False
 abc = 3
 is_defined('abc')
True
 def f(x):
print is_defined('x')
print is_defined('y')
y = 0
print is_defined('y')


 f(2)
True
False
True

 
 # Shorten names and pass locals() with lambas for 
 # convenience.   (This needs to be in the function 
 # where they are used or it will break.  
 # Another use for lamba!   ;)
 
 ifnd = lambda v, dv, lv=locals(): if_not_defined(v,dv,lv)
 isa = lambda v, lv=locals(): is_defined(v, lv)

There is no need for lambda here, it adds nothing. Use a 'def'.

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


Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
  I've never checked this code but it wouldn't have occurred to me that
  Queue uses any kind of timeout loop.  Can't it work the obvious way
  with a semaphore?
 
 And how is this semaphore going to be released if the timeout is
 reached?

 I meant a semaphore to synchronize the queue when adding or removing
 objects.

Last I looked there was a lock used for that.

The loop is only for when you cant remove or add an element immediatly
and there is a timeout.

 Timeout would be handled with sigalarm or select.

How is select going to help? IMO you can't put a Queue in a select call.
And it is doubtfull if working with sigalarm will do the trick.

First of all is the problem the signal module in python is very limited.
IIRC all signals are routed to the main thread. So breaking a lock
by having the thread signaled is impossible in python.

You may provide your own signal module, but that may not be enough.
The last time I experimented with a pthreads in C, locks didn't
break by signalling the thread. That might be a bug, but I wouldn't
know since I'm not familiar with the pthread specifications.

-- 
Antoon Pardon

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


Re: winapi32.GetFileVersionInfo() - problem

2005-03-25 Thread Heiko Wundram
 snip the fourth and hopefully last repost

Do you actually think anybody will reply to your mail if you keep reposting at 
this frequency? It'll rather make most people here kill-file you.

One post is enough; we've seen your problem, and it seems as though nobody 
here has a better solution than what Dennis Lee Bieber has already offered.

Just to make sure you understand what he said, I'll repeat it here: Your DLL 
doesn't contain a resources section, which in turn contains the version 
information you're asking for. So, please start reading MSDN and the VC++ 
documentation on how to add this information to your DLL.

If you wish to catch the exception that's raised (because the resource block 
isn't present), use something like the following:

try:
d = win32api.GetFileVersionInfo(fname,r\)
except:
d = None

if d is None:
print No version info in file!
else:
do something with the version info

-- 
--- Heiko.


pgpcvIOsraTHA.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Paul Rubin
Antoon Pardon [EMAIL PROTECTED] writes:
  I meant a semaphore to synchronize the queue when adding or removing
  objects.
 
 Last I looked there was a lock used for that.

OK, that amounts to the same thing.
 
 The loop is only for when you cant remove or add an element immediatly
 and there is a timeout.

  Timeout would be handled with sigalarm or select.
 
 How is select going to help? IMO you can't put a Queue in a select call.
 And it is doubtfull if working with sigalarm will do the trick.

You could open a socket to your own loopback port and then select on
it, or something like that.  The select call takes a timeout parameter.

 First of all is the problem the signal module in python is very limited.
 IIRC all signals are routed to the main thread. So breaking a lock
 by having the thread signaled is impossible in python.

A signal handler in the main thread could release a lock that the
thread is waiting on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie] smtplib.login()?

2005-03-25 Thread PA
On Mar 25, 2005, at 11:04, PA wrote:
What am I doing wrong? Why is the user name being encoded twice?
Ok... turns out that this is/was a bug in the python smtplib as  
recently as Dec 6 2004:

Patch #1075928: AUTH PLAIN in smtplib.
smtplib can not log in to some server using command AUTH PLAIN, it  
sends
``user\0user\0pass'' to the server, but ``\0user\0pass'' has better
compatibility.

http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/ 
smtplib.py

Sigh...
Cheers
--
PA, Onnay Equitursay
http://alt.textdrive.com/
--
http://mail.python.org/mailman/listinfo/python-list


SimpleRPCServer

2005-03-25 Thread Esben Pedersen
I am trying to restrict some of the methods available by RPC to whether 
the user is connected through a ssh-tunnel eg. connecting from localhost.

class UserRPC:
'''Methods available to users'''
pass
class AdminRPC(UserRPC):
'''Methods available only when connecting from localhost'''
pass
class RPCServer(SimpleXMLRPCServer):
def _dispatch(self, method, args):
if user_is_connecting_from_localhost():
return getattr(AdminRPC(), method)(*args)
return getattr(UserRPC(), method)(*args)
What i don't know is how to the client ip. I would think I should 
override the _marshalled_dispatch method but I can't quite grasp it all.

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


gnuplot -reverse

2005-03-25 Thread Cousin Stanley
Experimenting with the gnuplot package under Debian Linux,
I've found that the  -reverse  option when used to start
gnuplot from the command-line will produce plots
that are color-reversed and render with white text
on a black background 
However, I'm too dense to see how to easily achieve
the same effect when using the python-gnuplot package 
Any clues would be greatly appreciated 
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
--
http://mail.python.org/mailman/listinfo/python-list


Re: Queue.Queue-like class without the busy-wait

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, Paul Rubin schreef http:
 Antoon Pardon [EMAIL PROTECTED] writes:
  I meant a semaphore to synchronize the queue when adding or removing
  objects.
 
 Last I looked there was a lock used for that.

 OK, that amounts to the same thing.
  
 The loop is only for when you cant remove or add an element immediatly
 and there is a timeout.

  Timeout would be handled with sigalarm or select.
 
 How is select going to help? IMO you can't put a Queue in a select call.
 And it is doubtfull if working with sigalarm will do the trick.

 You could open a socket to your own loopback port and then select on
 it, or something like that.  The select call takes a timeout parameter.

Well maybe you could use an os.pipe as a timeout lock then. When the lock is
instantiated you put one byte in it. Aquiring the lock is implemented by
reading one byte, releasing the lock is implemented by writing a byte.
Aquiring the lock with a timeout would make use of select.

It would require carefull coding, since you want to prevent the thread
blocking because of select returning indicating it could be read, but
between the select and the actual read an other thread already consumed
the byte.

 First of all is the problem the signal module in python is very limited.
 IIRC all signals are routed to the main thread. So breaking a lock
 by having the thread signaled is impossible in python.

 A signal handler in the main thread could release a lock that the
 thread is waiting on.

This wouldn't work. A thread would have no way knowing for what
purpose the lock was released, because the lock was released
by the thread holding the lock or because the signal handler
released the lock, both would look the same for the thread
aquiring the lock.

There is also the problem you can't direct which thread will
aquire the lock. Suppose you have two threads waiting on a
lock, one plain, one with a timeout. Your signal handler
kicks in and releases the lock. There is a good chance
the first thread will now aquire the thread and the thread
that used a timeout will continue to be blocked.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to move insert to position in Text widget (Tkinter)

2005-03-25 Thread Harlin Seritt
I am working on a Find Text dialog box. Once you find a string in a
Text widget, how do you at least move the cursor to that index
(position)? Even better how can one 'select' the string one finds?

---code---
def searchText():
while 1:
pos = self.mainEdit.search(findString.get(), 1.0,
stopindex=END)
if not pos:
break

print pos
start = pos + +1c
break
---end code---

thanks,

Harlin Seritt

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


modern kjbuckets anywhere?

2005-03-25 Thread Robin Becker
I'm trying to get pySimplex working in Python 2.4, but I find that 
kjbucketsmodule.c makes reference to rename2.h which doesn't seem to be 
present in Python 2.4.

I suppose that kjbucketsmodule.c needs to be brought up to date. It 
occurs to me that someone may have already done this so is there a 
modern version of the source on the web somewhere?
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: Archives and magic bytes

2005-03-25 Thread Jim
This is something I've recently thought about; perhaps you wouldn't
mind some points?

1) I've been running 'file' via os.popen, and I've had trouble with it
incorrectly spotting file types (Fedora Core 1).  I can name a specific
example where it thinks a plain text README file is HTML (despite that
the configuration file for 'file' at least looks right).  That makes me
suspicious of its ability to spot more obscure types.

(No, I haven't tried to get the latest 'file'; the days are long but
they are filled with negative time and in the end I don't always get
done what I should.)

2) Watch out for someone giving you, say, a bogus /bin/ls in a .zip
file.  You may want to look into chroot (which I believe requires you
to run as root), or at least examine the output of unzip -l

3) You might also have to worry about the possibility that unpacking a
bundle will fill up your disk's partition.  At least for a while you
hold both the bundle and the unpacked bundle.

4) Using os.popen to unpack the bundle has a lot of advantages,
including that during debugging you can test the stuff from the command
line and feel that you completely understand which steps are working (I
think I use popen2, IIRC, and capture stderr for error messages).

Perhaps this is mostly a reflection on me as a programmer :-} but I
found the job surprisingly tricky.

Jim

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


Re: modern kjbuckets anywhere?

2005-03-25 Thread Robin Becker
Robin Becker wrote:
I'm trying to get pySimplex working in Python 2.4, but I find that 
kjbucketsmodule.c makes reference to rename2.h which doesn't seem to be 
present in Python 2.4.

I suppose that kjbucketsmodule.c needs to be brought up to date. It 
occurs to me that someone may have already done this so is there a 
modern version of the source on the web somewhere?
seems that gadfly.sf.net might be what I'm looking for
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to move insert to position in Text widget (Tkinter)

2005-03-25 Thread Fredrik Lundh
Harlin Seritt wrote:

I am working on a Find Text dialog box. Once you find a string in a
 Text widget, how do you at least move the cursor to that index
 (position)?

widget.mark_set(INSERT, pos)

 Even better how can one 'select' the string one finds?

widget.tag_add(SEL, pos, endpos)

to remove an existing selection, use

widget.tag_remove(SEL, 1.0, END)

/F 



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


Interface selection

2005-03-25 Thread ias0nas
Hello,

How can I select on wich interface a socket will connect to?
Say I have a pc with one network card and a 56K modem, how can I select
on wich interface will the socket connect?

Thank you

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Skip Montanaro

 What do you guys think about Python's grouping of code via
 indentation?

Peter This is a Python newsgroup. Assume that we all have been
Peter brainwashed.

+1 QOTW.

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


Re: How to move insert to position in Text widget (Tkinter)

2005-03-25 Thread Harlin Seritt
Frederik,

Thanks! Just looking at your site (effbot and pythonware). I don't know
what I'd do without it!

Cheers,

Harlin

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, Tim Tyler schreef [EMAIL PROTECTED]:
 What do you guys think about Python's grouping of code via indentation?

 Is it good - perhaps because it saves space and eliminates keypresses?

I think it was a mistake, but I'm probably in the minority here.

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


Re: Interface selection

2005-03-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Hello,
 
 How can I select on wich interface a socket will connect to?
 Say I have a pc with one network card and a 56K modem, how can I select
 on wich interface will the socket connect?

you need to specify the ip address that interface has been assigned to in
the bind-call.
-- 
Regards,

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


Re: SimpleRPCServer

2005-03-25 Thread Skip Montanaro

Esben What i don't know is how to the client ip. I would think I should
Esben override the _marshalled_dispatch method but I can't quite grasp
Esben it all.

First, from my reading of SimpleXMLRPCServer, I don't think _dispatch()
belongs at that level.  It belongs in the request handler class or in a
separate dispatcher class, depending on what version of Python you're using.
Second, SimpleXMLRPCServer is a SocketServer subclass.  You should be able
to provide a verify_request method (see the SocketServer docs) and a handler
class with a set_local method:

class RPCServer(SimpleXMLRPCServer):
 def verify_request(self, handler, address):
 handler.set_local(address_is_local(address))

A _dispatch method in the handler will then be able to check an attribute to
know if the request was made from the local machine or not.

Skip

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


Re: Interface selection

2005-03-25 Thread ias0nas
Actually its not a server. I dont do any binding call, just a connect.

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread John Roth
Antoon Pardon [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
Op 2005-03-25, Tim Tyler schreef [EMAIL PROTECTED]:
What do you guys think about Python's grouping of code via indentation?
Is it good - perhaps because it saves space and eliminates keypresses?
I think it was a mistake, but I'm probably in the minority here.
Um, why?
I think it isn't quite what's needed, based on the observation that it makes
shifting from expression to statement context difficult enough that useful 
features
like blocks don't have a decent syntax.

On the other hand, it saves me an awful lot of hassle; it's one less thing
to have to get into my head.
John Roth
--
Antoon Pardon 
--
http://mail.python.org/mailman/listinfo/python-list


Re: DBAPI Paramstyle

2005-03-25 Thread Bob Parnes
On Thu, 24 Mar 2005 15:03:13 +0100, Fredrik Lundh [EMAIL PROTECTED] \
wrote:
 Bob Parnes wrote:
 
 I must be missing something, so perhaps someone can explain
 the benefit of a paramstyle over the usual Python formatting
 style and maybe suggest a test to show it. Thanks.
 
 set the parameter to 0; DROP DATABASE template1; and see what
 happens.
 
 or set it to os.urandom(1000) and run your test a couple of times to see
 what happens.
 

Thanks for the suggestion. My system does not appear to contain an
os.urandom() method. It has a /dev/urandom device, but I don't know how to
use it for this purpose, except perhaps to select the first byte that it
produces.

I have a mediocre talent at programming, which is why I chose python.
For me it was a good choice. I note this so that I hope you understand why
I say that I don't know what you are driving at. My understanding is that a 
paramstyle is more efficient than the traditional python approach for repeated 
use of a query. If so, then I do not see how the choice of a parameter is
relevant. If it is more efficient only in a specific abstract case, then
one would have to look for other reasons to use it in a practical application.

Bob Parnes

-- 
Bob Parnes
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Kent Johnson
Tim Tyler wrote:
What do you guys think about Python's grouping of code via indentation?
Is it good - perhaps because it saves space and eliminates keypresses?
Or is it bad - perhaps because it makes program flow dependent on 
invisible, and unpronouncable characters - and results in more
manual alignment issues by preventing code formatters from managing
indentation?
http://www.python.org/doc/faq/general.html#why-does-python-use-indentation-for-grouping-of-statements
  from __future__ import braces
  File stdin, line 1
SyntaxError: not a chance
Love it or leave it...
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-25 Thread Lucas Raab
Leif B. Kristensen wrote:
R.Meijer wrote:

Jot jot at nad.com writes:

If she's really gifted i hope she dumps that obsolete monolithic
kernel as soon as she realizes that such beautiful language as python
shouldn't be used on top of ugly, badly designed software.
Did somebody say off-topic?

I'd say it's a Troll -1. Anyway, that'd be my moderator response over
at Slashdot. As had been said so many times; GNU/Hurd is still a
pipe-dream. Those who think that the Linux kernel is based on faulty
concepts should really get their act together and produce their own
microkernel. Personally, I don't care about the kernel architecture as
long as I've got a system that works right here, now.
 

Anyway, I myself am 14 years old and I can make simple python scripts
already by learning it off the official tutorial that comes with it.
My tip: let her take her time with a normal adult tutorial, and give
her small assignments every few chapters just so she gets it.

If I may ask, do you think that the How to think like a Computer
Scientist is a good starter? I'm 52 years old and learned my basics
with Swan's Mastering Turbo Pascal 5.5 way back when, but I'm
sincerely wondering what your generation think are hi-class tutorials.
I've got a thirteen-year old daughter to whom I have recently taught the
HTML basics, but she doesn't readily take to actual programming. If
you've got any idea what I should push to her to get her fascinated
about _real_ programming, I'd be obliged. Or maybe her head isn't
screwed together that way, what do I know.
I found How to Think Like a Computer Scientist a very good book. It 
was very well written and didn't push too many things onto you at once.

--
--
Lucas Raab
lvraab located at earthlink.net
dotpyFE located at gmail.com
AIM:Phoenix11890
MSN:dotpyfe @ gmail.com
IRC:lvraab
ICQ:324767918
Yahoo:  Phoenix11890
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interface selection

2005-03-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Actually its not a server. I dont do any binding call, just a connect.

Then where is your problem? The two interfaces have been assigned distinct
IPs, so connect to the appropriate one.

-- 
Regards,

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, John Roth schreef [EMAIL PROTECTED]:

 Antoon Pardon [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 Op 2005-03-25, Tim Tyler schreef [EMAIL PROTECTED]:
 What do you guys think about Python's grouping of code via indentation?

 Is it good - perhaps because it saves space and eliminates keypresses?

 I think it was a mistake, but I'm probably in the minority here.

 Um, why?

1) It makes it hard to see how many levels are dedented at the end of
   a suite, and sometime makes it difficult to see where the end
   of a suite is. If e.g. you are looking at the code spread over
   two pieces of paper, it is sometimes hard to see whether the
   suite ends at the end of the first page or not.

2) It makes it hard to introduce some kind of new syntax constructs.
   Sometimes its isn't clear what would be the best indentation scheme
   for a syntantical structure, or some usefull syntantical won't fall
   in the indentation scheme that python provides. I think it a
   shame that these consideration would limit what constructs
   get into python or not.

3) Sometimes the structure of the algorithm is not the structure
   of the code as written, people who prefer that the indentation
   reflects the structure of the algorithm instead of the structure
   of the code, are forced to indent wrongly.

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread projecktzero
Tim Tyler wrote:
 What do you guys think about Python's grouping of code via
indentation?

 Is it good - perhaps because it saves space and eliminates
keypresses?

 Or is it bad - perhaps because it makes program flow dependent on
 invisible, and unpronouncable characters - and results in more
 manual alignment issues by preventing code formatters from managing
 indentation?

 Python is certainly pretty unorthodox in this area.

 How would you have dealt with the issue of how to group statements?
 --
 __
  |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to
reply.

You might read Eric Raymond's Why Python? article
[http://www.linuxjournal.com/article/3882]

I would agree with him in that it just seems natural.

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


[Tutor] Re: Reading text lines from a socket

2005-03-25 Thread Sandip Bhattacharya
[Reposting to the general list too]

Lloyd Kvam wrote:
 Sockets deal with packetized data.  The network protocols do not guarantee
 keeping the data in line oriented chunks - even if the data starts out
 that way.

 You need to deal with extracting lines from chunks.  So long as the
 connection is
 working properly, this is easy.  The challenge occurs when the remainder
 of a line
 never gets delivered.  The best strategy depends upon the details of
 what you are
 doing.

I understand that. In Python using sockets is like using sockets in C.

However, I was looking for a python equivalent of the perl idiom of
opening a socket and getting a file handle ... and then reading this
file handle as any other line oriented file using $socket-readline

I am trying to write a simple Netcraft style script which tries the HEAD
method on a webserver and reads the Server: header from the response. I
would not like to use urllib, because even a call to something like
urllib.info() reads in the complete webpage on an open().

Even if this particular problem could be done elegantly, I would be
interested to know the answer to my original question because the
feature of reading a line at a time from a socket will help me in a lot
of other places in the future.

- Sandip

--
Sandip Bhattacharya
sandip (at) puroga.com
Puroga Technologies Pvt. Ltd.
Work: http://www.puroga.comHome: http://www.sandipb.net

GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Re: Reading text lines from a socket

2005-03-25 Thread Lloyd Kvam
Well, I've never used it, but sockets do have the makefile method.  That
would seem to fit what you're trying to do.

Sandip Bhattacharya wrote:

 [Reposting to the general list too]

 Lloyd Kvam wrote:

 Sockets deal with packetized data.  The network protocols do not
 guarantee
 keeping the data in line oriented chunks - even if the data starts out
 that way.

 You need to deal with extracting lines from chunks.  So long as the
 connection is
 working properly, this is easy.  The challenge occurs when the
 remainder of a line
 never gets delivered.  The best strategy depends upon the details of
 what you are
 doing.


 I understand that. In Python using sockets is like using sockets in C.

 However, I was looking for a python equivalent of the perl idiom of
 opening a socket and getting a file handle ... and then reading this
 file handle as any other line oriented file using $socket-readline

 I am trying to write a simple Netcraft style script which tries the HEAD
 method on a webserver and reads the Server: header from the response. I
 would not like to use urllib, because even a call to something like
 urllib.info() reads in the complete webpage on an open().

 Even if this particular problem could be done elegantly, I would be
 interested to know the answer to my original question because the
 feature of reading a line at a time from a socket will help me in a lot
 of other places in the future.

 - Sandip


--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:  603-653-8139
fax:801-459-9582


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, Carl Banks schreef [EMAIL PROTECTED]:

 Tim Tyler wrote:
 What do you guys think about Python's grouping of code via
 indentation?

 Is it good - perhaps because it saves space and eliminates
 keypresses?

 It's good, but this is only a minor reason.

 The reason this is good is because it exactly reflects the way human
 beings mentally group code in their heads.  In Python, you can eyeball
 grouping with 100% accuracy (except for one flaw that's being phased
 out).

That is not true. You can with the innermost levels, but it isn't
always that clear with intermediate levels.

 Not so with other languages.  In other languages, you have two
 simultaneous ways of grouping code: the way that makes sense to humans
 (indentation), and the way (braces or begin/end).  This creates the
 possibility of mismatch, and it puts an extra burden on the programmer
 to make sure computer and human grouping stays synchronized.

Structure/Disciplined programming is a burden in general. I have
never found putting braces or what ever delimiter such a problem.
I don't see people argueing that putting the right number of parenthesis
and or brackets is an extra burden.


 Grouping by indentations also goes a long way to prevent sloppiness.
 No matter how sloppy your style is, you can't slop away the way the way
 program was nested in Python; thus a reader should be able to follow
 the flow of just about any code.

IMO the flow of a lot of code would be easier to follow if code
like if condition: break could be dedented, because such a
condition is really at the same level as the while

 I've ended up as the computer expert
 at my engineering firm, so I get (non-Python) code to debug from time
 to time, and I can attest that inconsistent style is the single worst
 thing that everyone does to make code unreadable.  Python-like
 indentation would instantly halve that problem.

Use a tool for that. If people want something in python that python
doesn't has, those people are refered to tools that provide it.
It it works in that direction, it should also work in the other
direction and people that would like some feature of python in
an other language should use a tool for that. You wnat consistent
style? Use a tool to put all your source in a consistent style.

 The drawbacks are insanely minor.  It makes one liners more difficult,
 and can result in transmission difficulties with some stupid programs
 that helpfully strip leading whitespace.  (There's another drawback in
 Python that isn't inherent to grouping by indentation, namely the
 possibility of mixing spaces and tabs.  This is the flaw that's being
 phased out.)


 Or is it bad - perhaps because it makes program flow dependent on
 invisible,

 It doesn't.  I suspect Pythonistas will heavily attest to that.  But,
 as I said, it does make it virtually impossible for sloppy code to
 mislead you about the flow.  Overall, if someone hands you a random
 piece of C code, and a random piece of Python code, you will be more
 likely to easily follow the flow of the Python.

Not with my own code. The difference is not great but my C programs
have a slight edge here.

 How would you have dealt with the issue of how to group statements?

 Having experienced Python, I can say pretty earnestly that, were I
 designing my own language, there is no other way I would do it.
 Grouping by indentation is a slam dunk for me.

Well to each his own.

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Carl Banks

Tim Tyler wrote:
 What do you guys think about Python's grouping of code via
indentation?

 Is it good - perhaps because it saves space and eliminates
keypresses?

It's good, but this is only a minor reason.

The reason this is good is because it exactly reflects the way human
beings mentally group code in their heads.  In Python, you can eyeball
grouping with 100% accuracy (except for one flaw that's being phased
out).  Not so with other languages.  In other languages, you have two
simultaneous ways of grouping code: the way that makes sense to humans
(indentation), and the way (braces or begin/end).  This creates the
possibility of mismatch, and it puts an extra burden on the programmer
to make sure computer and human grouping stays synchronized.

Grouping by indentations also goes a long way to prevent sloppiness.
No matter how sloppy your style is, you can't slop away the way the way
program was nested in Python; thus a reader should be able to follow
the flow of just about any code.  I've ended up as the computer expert
at my engineering firm, so I get (non-Python) code to debug from time
to time, and I can attest that inconsistent style is the single worst
thing that everyone does to make code unreadable.  Python-like
indentation would instantly halve that problem.

The drawbacks are insanely minor.  It makes one liners more difficult,
and can result in transmission difficulties with some stupid programs
that helpfully strip leading whitespace.  (There's another drawback in
Python that isn't inherent to grouping by indentation, namely the
possibility of mixing spaces and tabs.  This is the flaw that's being
phased out.)


 Or is it bad - perhaps because it makes program flow dependent on
 invisible,

It doesn't.  I suspect Pythonistas will heavily attest to that.  But,
as I said, it does make it virtually impossible for sloppy code to
mislead you about the flow.  Overall, if someone hands you a random
piece of C code, and a random piece of Python code, you will be more
likely to easily follow the flow of the Python.


 and unpronouncable characters - and results in more
 manual alignment issues by preventing code formatters from managing
 indentation?

This is true.  Most common complaint is changing the nesting level of a
block of code.  Good editors have ways to cope with this, just as good
editors have ways to cope with all these superfluous braces in other
languages.


 Python is certainly pretty unorthodox in this area.

 How would you have dealt with the issue of how to group statements?

Having experienced Python, I can say pretty earnestly that, were I
designing my own language, there is no other way I would do it.
Grouping by indentation is a slam dunk for me.


-- 
CARL BANKS

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


[perl-python] limericks

2005-03-25 Thread Xah Lee
Better:

there is a Python, pithy
mighty, lissome, and tabby
algorithms it puffs
conundrums it snuffs
and cherished by those savvy


there is a camel, kooky
ugly, petty, ungainly
hacking it supports
TIMTOWTDI it sports
and transports DWIM-wit's fancy

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Re: [newbie] smtplib.login()?

2005-03-25 Thread Gerhard Häring
PA wrote:
On Mar 25, 2005, at 11:04, PA wrote:
What am I doing wrong? Why is the user name being encoded twice?

Ok... turns out that this is/was a bug in the python smtplib as  
recently as Dec 6 2004:

Patch #1075928: AUTH PLAIN in smtplib.
smtplib can not log in to some server using command AUTH PLAIN, it  sends
``user\0user\0pass'' to the server, but ``\0user\0pass'' has better
compatibility.
I'll try to look into it.
-- Gerhard
--
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Diez B. Roggisch
 Structure/Disciplined programming is a burden in general. I have
 never found putting braces or what ever delimiter such a problem.
 I don't see people argueing that putting the right number of parenthesis
 and or brackets is an extra burden.

Oh, not the right number. But I have seen wars waging over the correct
indention style to use. Braces behind flow control statements, or beneath,
and if the latter, indented halfways or not? 

 Use a tool for that. If people want something in python that python
 doesn't has, those people are refered to tools that provide it.
 It it works in that direction, it should also work in the other
 direction and people that would like some feature of python in
 an other language should use a tool for that. You wnat consistent
 style? Use a tool to put all your source in a consistent style.

And what to do if two (or more) people can't decide on what convention to
use? And just in case you never worked with CVS: Having mutually commits of
sourcecode that has been subject to code formatting tools often creates a
hellhole of conflicts - which is a major PITA.

 Well to each his own.

Amen. Why don't you use ruby? It has braces. And code blocks. And its more
liberal towards overriding builtins, which might appeal to you.

-- 
Regards,

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Antoon Pardon
Op 2005-03-25, Diez B. Roggisch schreef [EMAIL PROTECTED]:
 Structure/Disciplined programming is a burden in general. I have
 never found putting braces or what ever delimiter such a problem.
 I don't see people argueing that putting the right number of parenthesis
 and or brackets is an extra burden.

 Oh, not the right number. But I have seen wars waging over the correct
 indention style to use. Braces behind flow control statements, or beneath,
 and if the latter, indented halfways or not? 

 Use a tool for that. If people want something in python that python
 doesn't has, those people are refered to tools that provide it.
 It it works in that direction, it should also work in the other
 direction and people that would like some feature of python in
 an other language should use a tool for that. You wnat consistent
 style? Use a tool to put all your source in a consistent style.

 And what to do if two (or more) people can't decide on what convention to
 use?

Normally one is the project leader. He decides.

 And just in case you never worked with CVS: Having mutually commits of
 sourcecode that has been subject to code formatting tools often creates a
 hellhole of conflicts - which is a major PITA.

 Well to each his own.

 Amen. Why don't you use ruby? It has braces. And code blocks. And its more
 liberal towards overriding builtins, which might appeal to you.

I have other problems with it. I have problems with all languages
currently available, so I use those which rub me wrong the least.
I think the indentation syntax of python was a mistake, but for
the most part it is a minor issue and it doesn't weight heavy enough
to go and use an other language, although I keeping looking at 
the other languages.

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Diez B. Roggisch
 Normally one is the project leader. He decides.

Whishful thinking.

Another problem I have with code that is _not_ layouted the way I'm used to
it is that the perception of what very code does gets more difficult to me.
You seem to have the same troubles, I take that from your desire to reflect
algorithmic structure different from syntactic. And I guess most people
havo, otherwise the whose layout-thing wouldn't stir up so bad feelings all
the time.

And as not all code I read is code I'm supposed to write (might it be OSS
that I dig into for debugging, or other 3rd party sources I can't control,
e.g. different departments with different project leaders) I found that
python's way of imposing a rather strict layout on _all_ coders out there
means I've less trouble digging into other peoples code. Which is useful -
and it seems that I'm not the only one with this feeling.

-- 
Regards,

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


Version Number Comparison Function

2005-03-25 Thread Keith
Is there a function for comparing version numbers?

E.g.

0.1.0  0.1.2
1.876b  1.876c
3.2.2  3.4

Keith

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


Re: Version Number Comparison Function

2005-03-25 Thread TZOTZIOY
On 25 Mar 2005 07:34:38 -0800, rumours say that Keith
[EMAIL PROTECTED] might have written:

Is there a function for comparing version numbers?

E.g.

0.1.0  0.1.2
1.876b  1.876c
3.2.2  3.4

Keith

Convert your version numbers into tuples:

(0, 1, 0)  (0, 1, 2)
(1, 876, 'b')  (1, 876, 'c')
(3, 2, 2)  (3, 4)

All of the above are True.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Version Number Comparison Function

2005-03-25 Thread Bill Mill
On 25 Mar 2005 07:34:38 -0800, Keith [EMAIL PROTECTED] wrote:
 Is there a function for comparing version numbers?
 
 E.g.
 
 0.1.0  0.1.2
 1.876b  1.876c
 3.2.2  3.4
 

Not by default AFAIK. How about something like (untested):

def test_version(v1, v2):
v1, v2 = v1.split('.'), v2.split('.')
for x, y in zip(v1, v2):
if x  y: return v1
if y  x: return v2

It assumes that v1 and v2 have the same amount of '.'s and that all of
the version numbers are of the same length (i.e. 1.1000 would be 
1.999). How general do you need to be?

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Version Number Comparison Function

2005-03-25 Thread Fredrik Lundh
Keith wrote:

 Is there a function for comparing version numbers?

 E.g.

 0.1.0  0.1.2
 1.876b  1.876c
 3.2.2  3.4

the following works for many common cases:

import re

def cmpver(a, b):
def fixup(i):
try:
return int(i)
except ValueError:
return i
a = map(fixup, re.findall(\d+|\w+, a))
b = map(fixup, re.findall(\d+|\w+, b))
return cmp(a, b) # -1 if ab, 0 if a=b, 1 if ab

 cmpver(0.1.0, 0.1.2)
-1
 cmpver(1.876b, 1.876c)
-1
 cmpver(3.2.2, 3.4)
-1

ymmv.

/F 



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


Suggesting a new feature - Inverse Generators

2005-03-25 Thread Jordan Rastrick
First, a disclaimer. I am a second year Maths and Computer Science
undergraduate, and this is my first time ever on Usenet (I guess I'm
part of the http generation). On top of that, I have been using Python
for a grand total of about a fortnight now. Hence, I apologise if what
follows is a stupid suggestion, or if its already been made somewhere
else, or if this is not the appropriate place to make it, etc. But I
did honestly do some background checking through the Python
documentation, www.python.org, FAQs, and so forth before making this
post. Basically what I'm trying to say here is, please don't flame this
post :)

Anyway, I have a suggestion to make for a rather radical new feature in
Python. Rather than just struggling to explain and justify it straight
out, I'll give the background of how I thought up the feature - and how
I worked through the ideas I came up with. The example may seem a bit
trivial to start, but bear with me, because I think theres at least
some possibility the suggestion has merit.

I am writing a project in Python atm, and one thing it needs to do is
parse a very simple text file to get a list of records. Its a
straightforward kind of thing that I (and I'm sure you) have done many
times before in many languages.

Each bit of interesting data in the file occurs over 3 or 4 lines of
text. On top of this there are lines of random uninteresting junk as
well.

I decided to write a generator to filter out the junk lines, strip
excess whitespace and the like (generators are one of my favourite
features in Python). So the main body of code looks like this:

def filterJunk(lines):
   for line in lines:
   # Do filtering  cleaning up stuff on line.
   # ...
   yield line

def getData(filename):
recordList = []
input = file(filename)
lines = line.readlines()
input.close()
for line in filterJunk(lines):
# ... create records and add to recordList

So far, so good. Next comes the business of actually creating the
records from the lines of interesting text.

You can probably see the problem I ran into - I need to look at 3 or 4
lines at a time to create the record. Theres no easy way out of this
requirement, because whether the record is contained in 3 or 4 lines is
conditional on the value of the second line. But the for loop isn't
going to allow me to do that.
So I rewrote the for loop above as:

while True:
  try:
# do stuff repeatedly with lines.next() to add to recordList[]
  except StopIteration:
 pass

This works. (And yes, there are also a multitude of other reasonably
simple ways to approach this problem, some of which I've used in this
past. And probably some fancy ways involving map and reduce as well.)

But it seems ugly to me somehow. And I'm suspicious of anything that
hints of ugliness (in Computer Science, anyway.) I suppose that
Python's getting me into the habit of assuming theres always an elegant
looking solution.

I tried, and failed, to think of some sort of Generator-based concept
(I really do love generators! So simple, but so useful!) that would
allow me to retain a for loop. I guess that, essentially, I feel this
task is really just iterating over the lines, and that iterating over
something in Python is a job for a for loop. Generators allow you to
use for loops all regular iteration. So I wanted to have something
vaugely Generator like, that would allow me to get back to using a
for loop.

It occured to me - what if I had some sort of inverse generator -  a
function with a resumable call mechanism that retained state, but that
would resume when accepting input rather than returning output. For
want of a better term, call it an Acceptor.

If you think of a Generator as a method acting as (an abstraction of) a
source of sequential data, then the Acceptor correspondingly is a sink.


I started playing round with the Acceptor idea, thinking about how it
might work. I imagined a simple mirroring of Generator syntax - using a
new keyword, accept, to take in a value, just as Generator's use yield
to return a value. Here's my first attempt at 'coding' my precious for
loop using an imaginary Acceptor:

def combineIntoRecord(): # This is an acceptor function
   optionalline = None # We may not get given a value for this line
   accept firstline
   accept secondline
   if condition(secondline):
  accept optionalline
   accept lastline
   r = createRecord(firstline, secondline, lastline, optionalline)
   return r

recordlist = []
for line in lines:
 recordlist.append(combineIntoRecord(line))

I've since thought about it somewhat, and its clear I got this first
try just plain wrong. Its got a number of hideous defects. First,
combineIntoRecord() is 'accepting' its values by taking a magical
argument, line, that does not appear in the argument list.

Second, in this particular syntax, do
combineIntoRecord(x)at line 50
and
combineIntoRecord(y)at line 200
want x and y to be 

Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Jordan Rastrick
Sorry about the mangled formatting... like i said, first time on Usenet

Suggestions, comments, replies, etc most welcome.

This definitely includes replies of the form: This is stupid,
because...
provided it isnt followed with youre a jerk who knows nothing.
Period.

Heres a follow up rant in the form of a QA, trying to answer what I
think are likely or interesting questions:



Q: Is this idea even remotely feasible to actually implement?

A: No Idea

Q: Are you volunteering to implement it?

A: Not really. I'd have no clue where to start. I probably don't even
have enough C experience to begin to understand the Python source. But
if some real Python dev (or devs)actually wants to implement this, and
is willing to humour an undergraduate by somehow utilising assistance
in form a very limited set of programming skills, well, then I'd be
highly flattered and more than happy to help :)

Q: The whole document is full of half-formed ideas, hundredth-formed
ideas,
mistakes(conceptual/typograhpcial/stylistic/grammatical/terminological/programming/...),
inconsistencies, random nonsense..

A: Firstly, thats not a question, its a statment.

Secondly, see the very first paragraph.

Thirdly, the whole document, from initial attempts to code the original
for loop (yes, it is a real program I'm trying to write here), to
thinking of Acceptors, refining the model to something vaguely
coherent, coming up with examples, and typing it all out, was produced
on the fly, in the space of 5 hours or so. I attempted to give it a
semblance of coherent structure at first, but soon gave up. Its
basically stream of conciousness production. The bit where the first,
nonsensical example is given, is literally where I first tried to
forumlate the idea in code, saw the massive holes, stopped, thought
about it for a few minutes, and came backed and typed out the much
improved second version. The whole thing is totally unedited.Oh, and I
had virtually no sleep last night.

A real answer, with respect to the issue of terminology: If I use
technical terms loosely, e.g., if I improperly use 'method' for
'function' or vice versa (a hang up from dealing with languages that
only have one e.g. Java, or the other, e.g. C) ,  please forgive me. I
hope what I'm trying to say is still clear enough.

And as for coding style, Python itself is inconsistent (or to be more
diplomatic, not obsessively concerned with the relatively minor issue
of) using underscore_seperated_words or mixedCaseInstead, etc. And
again, I cry the nefarious influence of Java

Q: Did you steal this from somewhere else?

A: No, its entirely something I thought of, by myself, in the last 5
hours. Thats not to say something like it (or more likely, better than
it) hasnt been thought of somewhere else by someone else. But if it
has, I havent seen it.

To give credit where due though: I was motivated by the various
examples, from sources like www.python.org, of how Generators can be
used to do things really elegantly. Also, I'm still tossing around
ideas in the back of my mind from a great talk given at my university
by Rob Pike, of Google, about a language he helped devise and implement
called sawzall (or something close). Its used to do processing with
Google's massive data sets and highly parallel computing architecture,
yet its incredibly simple to understand and very efficient. I guess it
was only tenuously related to the idea presented here. But it was
certainly very inspiring in a general computer-science-enthusiasm kind
of way.

Q: Why did you go to all this trouble thinking up this feature when you
could have solved the original problem in so many other, simpler ways?

A: I honestly can't give a decent justification :-) Whenever I've
needed to do things like:

line = readline from file
if (line is some sort of 'extra' data)
   do something with line
   line = readline from file # get the 'regular' data
...

in the past, in Pascal, Java and the like, it always irked me. Don't
ask why, it just did.

I thought I could get around it with generator in Python, but I
couldnt. In trying to think of a generator solution, I more or less
randomly thought of extending the generator concept somehow, and I
decided to see where it took me. I thought it took me to somewhere
interesting, and possibly worthy of further investigation.

Q: What about using some sort of 'sequential data sink' that doesn't
use 'pretending to be a function' syntax, e.g. a simple Class of some
sort?

A: Maybe. You can have Iterators without Generators. Maybe you can have
inverse Iterators without inverse Generators, I havent thought
about it.
I love the 'pretending to be a function' syntax, its part of what makes
Generators so elegant. So I tried to emulate it.

Q: What could be some of the benefits of introducing this feature? What
could it be used for?

A: Again, I don't really know. Past the examples I've given, I havent
really thought about possible 

Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Larry Bates
Python's way of grouping is VERY good.  Over the last
30+ years I've seen a lot of code (good and bad) in
many languages.  IMHO good code (independent of language)
always uses indentation, even when other block constructs
(like braces) is available. Python developers thought that
this was redundant.  Just make the indentation mean
something and lose the block construct characters.

Secondly,  Python nudges me into writing better
(easier to maintain and clearer to understand) code by
influencing me towards splitting my code into smaller
functions/classes.  If I find myself with more than 3-4
levels of indentation, I probably need to move some of the
lower level code into a function or a class anyway (I
actually ran into this this very morning). Some might
interpret this as a negative, I don't.  I find that a lot
of programmers put WAY too much code into single individual
modules (main programs, functions) for their own good.  It
is harder to read, harder to understand, and harder to
maintain.  I believe that Python tends to make these
programmers better by influencing them to write more
modular code.  The best method for deeply nested grouping
is usually the introduction of functions/classes that
divide the deeply nested grouping into more manageable
and debuggable pieces.

Larry Bates







Tim Tyler wrote:
 What do you guys think about Python's grouping of code via indentation?
 
 Is it good - perhaps because it saves space and eliminates keypresses?
 
 Or is it bad - perhaps because it makes program flow dependent on 
 invisible, and unpronouncable characters - and results in more
 manual alignment issues by preventing code formatters from managing
 indentation?
 
 Python is certainly pretty unorthodox in this area.
 
 How would you have dealt with the issue of how to group statements?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Andrew Koenig
Jordan Rastrick [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 def combineIntoRecord(): # This is an acceptor function
   optionalline = None # We may not get given a value for this line
   accept firstline
   accept secondline
   if condition(secondline):
  accept optionalline
   accept lastline
   r = createRecord(firstline, secondline, lastline, optionalline)
   return r

 recordlist = []
 for line in lines:
 recordlist.append(combineIntoRecord(line))

How about doing it this way?

class Acceptor:
def __init__(self, gen):
self.gen = gen
def next(self):
firstline = self.gen.next()
secondline = self.gen.next()
if condition(secondline):
optionalline = self.gen.next()
accept lastline
r = createRecord(firstline, secondline, lastline, optinalline)
return r

This is just a generator done longhand.  If anything in Acceptor.next raises 
StopIteration, so will Acceptor.next itself.  Which means that you can now 
write this:

for r in Acceptor(line):
recordlist.append(r)

or, for that matter,

recordlist = list(Acceptor(line))

Incidentally, I did not try to fix the bug in your code that if 
condition(secondline) is false, optionalline never gets set so the program 
will crash :-)


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


Re: Version Number Comparison Function

2005-03-25 Thread Keith
I can't assume there are the same number of '.'s or there are the same
number of digits per version.

I don't know how the tuple comparison works offhand.  But that seems
like it would work if you split it.

The suggestion with the re module seems generic enough and looks like
it will work as is.

Thanks.

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


(no subject)

2005-03-25 Thread python-list-bounces+archive=mail-archive . com
#! rnews 1995
Newsgroups: comp.lang.python
Path: 
news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp
From: Jeff Sandys [EMAIL PROTECTED]
Subject: Re: Python for a 10-14 years old?
X-Nntp-Posting-Host: e515855.nw.nos.boeing.com
Content-Type: text/plain; charset=us-ascii
Message-ID: [EMAIL PROTECTED]
Sender: [EMAIL PROTECTED] (Boeing NNTP News Access)
Content-Transfer-Encoding: 7bit
Organization: juno
X-Accept-Language: en
References: [EMAIL PROTECTED]
Mime-Version: 1.0
Date: Fri, 25 Mar 2005 16:09:50 GMT
X-Mailer: Mozilla 4.79 [en]C-CCK-MCD Boeing Kit  (Windows NT 5.0; U)
Xref: news.xs4all.nl comp.lang.python:369133
Lines: 35

How to Think Like a Computer Scientist is a great book for this 
age group.  It is easy to read, in nice easy to digest steps, with 
enough examples.  I will be using this book for a Middle School 
(7-8 grade, 12-14 year old) Python Programming Club.  The hard 
part is guiding students into rewarding projects that can be 
accomplished in a short time.

John Zelle's _Python Programming: An Introduction to Computer 
Science_ is also a very good, but it is aimed at high school and 
first year college students.

Another thing that might be useful is if she has a friend that is 
interested in learning programming.  They can pair program with one 
reading the book while the other drives the computer.  Learning is 
faster and more fun with pair programming.

Check out the Python Edu-SIG:
http://www.python.org/sigs/edu-sig/

[EMAIL PROTECTED] wrote:
 
 ... The only tutorial I have found so far is
 How to Think Like a Computer Scientist - Learning with Python which,
 while very good indeed, is geared towards adult newbie students.
 
 Is there something out there like Python for kids which would explain
 *basic* programming concepts in a way which is accessible and
 entertaining for kids aged 10-14 (that about where her brain is right
 now) and which would allow them to play around and have fun solving
 small problems?
 
 Many thanks in advance,
 
 TN
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Tim Hochberg
Jordan Rastrick wrote:
[CHOP]
Behold:
# An Acceptor/Generator!!!
def combineIntoRecords():
   optionalline = None # We may not get given a value for this line
   accept firstline
   accept secondline
   if condition(secondline):
  accept optionalline
   accept lastline
   yield createRecord(firstline, secondline, optionalline,
lastline)
That's a nice example, but why not:
def combineIntoRecords(iterable):
iterator = iter(iterable)
optionalline = None
firstline = iterator.next()
secondline = iterator.next()
if condition(secondline):
optionalline = iterator.next()
lastline = iterator.next()
yield createRecord(firstline, secondline, optionalline, lastline)
???
-tim
def getData(lines):
return list(combineIntoRecords(filterJunk(lines)))
So, alas, my beloved for loop was not saved after all.
Fortunately, the dreaded While loop has been vanquished. In fact all
loopiness has disappeared. Along with any other semblance of a main
method.
I think I like the finished result. I'll leave if for you to decide if
you like it too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Version Number Comparison Function

2005-03-25 Thread Dan Sommers
On 25 Mar 2005 07:34:38 -0800,
Keith [EMAIL PROTECTED] wrote:

 Is there a function for comparing version numbers?
 E.g.

 0.1.0  0.1.2
 1.876b  1.876c
 3.2.2  3.4

How about a simple string comparison?

Python 2.3.3 (#1, Mar  9 2004, 14:21:31) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin
Type help, copyright, credits or license for more information.
 '0.1.0'  '0.1.2'
True
 '1.876b'  '1.876c'
True
 '3.2.2'  '3.4'
True
 

Beyond that, there seems to be sufficient variation between version
number schemes, and something interesting often happens immediately
before the final version (e.g. 1.0rc4 becomes 1.0), that you may
have to know something more about where you particular version numbers
come from.

Regards,
Dan

-- 
Dan Sommers
http://www.tombstonezero.net/dan/
c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Ivan Van Laningham
Hi All--

Larry Bates wrote:
 
 Secondly,  Python nudges me into writing better
 (easier to maintain and clearer to understand) code by
 influencing me towards splitting my code into smaller
 functions/classes.  If I find myself with more than 3-4
 levels of indentation, I probably need to move some of the
 lower level code into a function or a class anyway (I
 actually ran into this this very morning). Some might
 interpret this as a negative, I don't.  I find that a lot
 of programmers put WAY too much code into single individual
 modules (main programs, functions) for their own good.

Agreed.  Any method where you have to scroll to figure out what matches
what is _too big_.  This principle holds true for any language.  Keeping
to that aesthetic forces you to modularize your code and often generates
far more flexible functions/methods than you would have any right to
expect otherwise.

As far as grouping by indentation goes, it's why I fell in love with
Python in the first place.  Braces and so on are just extraneous cruft
as far as I'm concerned.  It's the difference between Vietnamese verbs
and Latin verbs;-)

Metta,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Jordan Rastrick
Thanks for the very fast feedback :)

I specifically set optionalline = None to deal with that bug you
mentioned, with the implicit assumption createRecord knows how to deal
with a None argument. If that guard got destroyed in the copy paste
process, my bad.

As for you solution, yes, you could do it that way.

But I'm not so much interested in alternate solutions to the problem
itself, which is to be honest trivial. I'm intereseted in the
implications of the imaginary solution of the Acceptor function.

Just as you can have Iterators (an abstract class based solution to
iteration) without Generators, yet Generators are still of interest, so
you could solve this problem without Acceptors, yet Acceptors are
(potentially) of interest.

Basically, an Acceptor is linked to a Generator (or some other
sequence) in the way you have linked the class implementation to a
Generator. So this is a kind of implementation of an Acceptor using a
class. I like the Acceptor syntax, though. And I'm wondering  if maybe
there are more complex examples that are harder or impossible to do
your way...

I think I already put something (briefer) in the QA bit along these
lines

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


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Michael Spencer
Tim Hochberg wrote:
Jordan Rastrick wrote:
itertools.groupby enables you to do this, you just need to define a suitable 
grouping function, that stores its state:

For example, if short lines should be appended to the previous line:
from itertools import groupby
linesource = \
Here is a long line, long line, long line
and this is short
and this is short
Here is a long line, long line, long line
and this is short.splitlines()
def record(item, seq = [0]):
if len(item)  20:
seq[0] +=1
return seq[0]
  for groupnum, lines in groupby(linesource, record):
 ... print .join(lines)
 ...
 Here is a long line, long line, long lineand this is shortand this is short
 Here is a long line, long line, long lineand this is short
 
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing closed source modules

2005-03-25 Thread Dave Brueck
Fuzzyman wrote:
Dave Brueck wrote:
It's certainly something lot's of people are interested in.  I guess it
depends who your audience is. If ytour code isn't for *mass*
distribution - the chances of people putting a lot of effort into
breaking it are greatly reduced. I don't htink it's necessarily futile.
By futile I meant that, if the code ends up running on a user's machine, then 
a sufficiently motivated person could crack it wide open, regardless of 
implementation language - the only way to truly protect the code is to never let 
it out of your hands (i.e. it's accessible just via a web service).

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


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Jordan Rastrick
Yes, granted.

This is basically the same as Andrew's reply, except with Iterators in
place of generators, so I'll let my answer to that stand. In fact, its
my solution, but with iter.next() in place of accept :)

This is probably something like how I wanted to solve the problem when
I first was looking at it and wanting a generator based solution. I
ended up thinking of this whole Acceptor business as part of getting me
to this point.

I'll try to reduce my pages of ranting to a single question. In
posting, i was wondering if the syntactic sugar (Acceptors) that i
invented to implement the solution is of any general interest. So are
there maybe examples less straightforward than this one, where
Acceptors work better? Or can you always just turn the generator
inside out in the way you have done here?

If you can always do it your way, well, thats a powerful design
pattern, and it just goes to show my faith in Generators was justified
:) And that I wasnt thinking hard /clearly enough about how to use
them.

There are other issues, like Does the Acceptor syntax, although
perhaps functionally equivalent to other methods, ever make the code
more readable, easier to parse, etc? But they're a lot less important
i'd say.

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


Re: Anonymus functions revisited : tuple actions

2005-03-25 Thread Ron_Adam
On 24 Mar 2005 22:16:10 -0800, Kay Schluehr [EMAIL PROTECTED]
wrote:

It's all developed during this discussion. Sometimes I'm a bit
surprised were it goes.

I enjoy exploring ideas this way. Many times it leads to dead ends or
you just end up with a long way back to where you started, but
sometimes you get a surprise, and almost always a deeper understanding
of the subject. :)

To make my intention clear for another time, also for George who
mistrusts these exercises alltogether. I want to derive a syntax and
semantics for anonymus functions ( called tuple-actions ) that are
generalizations of rules that are already used implicitely within
Python e.g. tuple-unpacking. This is done by progressive interpretation
and extension. They are not there by means of an accident, what Guido
claims about the current lambda which he feels to be sticked onto the
language. 

Looking at the syntax of lambda, I think I agree with Guido.

result = lambda *args: expression  

It's works like a function, but is formatted like a for or if
statement.  It should have been something like this.

result = lambda{ *args: expression}

Another interesting possibility by exploring ideas and concepts.  :)

Using a dictionary instead of ()'s to pass the arguments and
expressions.  This would simplify parsing it, because it could be
handled as an an object instead of having to parse the args and
expression first. 


What if you could:

x = lambda{ x, y: x+y}  
Hmm comma creates a problem here. so...

x = lambda{ (x,y): x+Y }

This is more consistent with python syntax and makes more since. the
args are in a tuple as they would be in function.

x = lambda{ (x,y): x+y } is same as  x = function(x,y): return x+y


Could this work too?:

x, y, z = lambda{ (x,y): x+y, (x,z):x+z, (x,v):x+v }   

 Short hand for:

x,y,z = lambda{(x,y):x+y}, lambda{(x,z):x+z, lambda{(x,v):x+v}


For compatibility purposes, You would need to give it a different
name:

af, afn, ann, lamb, lam, lm, ?

Or just call it what it is.. function{(args):expression}

Then it would be easy to explain, teach, and remember.


Ron_Adam


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


Re: Version Number Comparison Function

2005-03-25 Thread Robert Kern
[Pardon the piggybacking. My news-server does not see the OP's message.]
Fredrik Lundh wrote:
Keith wrote:

Is there a function for comparing version numbers?
E.g.
0.1.0  0.1.2
1.876b  1.876c
3.2.2  3.4
distutils has a set of version classes with comparisons.
In [1]:from distutils import version
In [2]:version?
Type:   module
Base Class: type 'module'
String Form:module 'distutils.version' from 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/distutils/version.pyc'
Namespace:  Interactive
File: 
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/distutils/version.py
Docstring:
Provides classes to represent module version numbers (one class for
each style of version numbering).  There are currently two such classes
implemented: StrictVersion and LooseVersion.

Every version number class implements the following interface:
  * the 'parse' method takes a string and parses it to some internal
representation; if the string is an invalid version number,
'parse' raises a ValueError exception
  * the class constructor takes an optional string argument which,
if supplied, is passed to 'parse'
  * __str__ reconstructs the string that was passed to 'parse' (or
an equivalent string -- ie. one that will generate an equivalent
version number instance)
  * __repr__ generates Python code to recreate the version number 
instance
  * __cmp__ compares the current instance with either another instance
of the same class or a string (which will be parsed to an instance
of the same class, thus must follow the same rules)


--
Robert Kern
[EMAIL PROTECTED]
In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Version Number Comparison Function

2005-03-25 Thread Mark Rowe
On Mar 26, 2005, at 3:34 AM, Keith wrote:
Is there a function for comparing version numbers?
E.g.
0.1.0  0.1.2
1.876b  1.876c
3.2.2  3.4

FWIW,
 from distutils import version
 version_list = 3.4 3.2.2 1.867c 1.867b 0.1.2 0.1.0.split()
 version_list = map(version.LooseVersion, version_list)
 version_list.sort()
 print version_list
[LooseVersion ('0.1.0'), LooseVersion ('0.1.2'), LooseVersion 
('1.867b'), LooseVersion ('1.867c'), LooseVersion ('3.2.2'), 
LooseVersion ('3.4')]
 print '  '.join(map(str, version_list))
0.1.0  0.1.2  1.867b  1.867c  3.2.2  3.4


It should be noted that distutils.version provides a StrictVersion 
class that offers less flexible but more predictable ordering -- see 
the module docstrings for more details.

Regards,
Mark Rowe
http://bdash.net.nz/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Version Number Comparison Function

2005-03-25 Thread Keith
distutils is one of the places I looked:
http://www.python.org/doc/2.3.5/lib/module-distutils.html

But I didn't see the functions documented.  I am new to Python so I
didn't know where else to look.

Using distutils seems like it would be the most generic and supported
way to compare version numbers.

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


Re: Python docs [was: function with a state]

2005-03-25 Thread Ulrich Hobelmann
[EMAIL PROTECTED] wrote:
The Python doc, though relatively incompetent, but the author have
Really, how could those morons even dream of creating a language, 
and even writing docs to accompany it??

tried the best. This is in contrast to documentations in unix related
things (unix tools, perl, apache, and so on etc), where the writers
have absolutely no sense of clear writing, and in most cases don't give
a damn and delight in drivel thinking of it as literary.
Well, man-pages are at least coherent and precise.
It's not literature, it's technical documentation!
I think that this is an excellent description of your own writing.
:)
To be sure, he's a stupid troll, but I think you shouldn't insult 
him for being bad at English.  I bet you (or most Western people 
anyway) have trouble getting fluent in an Asian language.  Imagine 
the lingua franca were Chinese, non English...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 | 7.3 The for statement

2005-03-25 Thread Facundo Batista
On 24 Mar 2005 19:49:38 -0800, brainsucker [EMAIL PROTECTED] wrote:


 foo = 0
 for item1 in range(10) until foo == 2:
   for item2 in range(10) until foo == 2:
 foo = item1 + item2
 if foo == 2: print Let's see
 print foo

In this case, I'll use the following:

try:
for item1 in range(10):
for item2 in range(10):
if item1 + item2 == 2:
print Let's see
raise StopIteration
except StopIteration:
pass
print item1 + item2

And I tell you what. Actually I'm very lousy remembering things, and
if I want the loop to stop in a different number, I'll have to change
the code in TWO places. In mine, just one (and this in your codes get
worse with more for levels).

Another approach:

def bar():
for item1 in range(10):
for item2 in range(10):
if item1 + item2 == 2:
print Let's see
return item1 + item2
foo = bar()
print foo

.Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://pyar.decode.com.ar/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minidom output of XML escaped characters

2005-03-25 Thread Derek Basch
Thanks effbot. I haven't had much use for XML comments so far and I
guess other people haven't either because it seems they are hardly ever
mentioned.

http://groups-beta.google.com/groups?hl=enlr=c2coff=1q=xml+comment+pythonqt_s=Search+Groups

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Rocco Moretti
Antoon Pardon wrote:
I have problems with all languages
currently available, so I use those which rub me wrong the least.
... [I]t doesn't weight heavy enough
to go and use an other language, although I keeping looking at 
the other languages.
I think the operational definition of a zealot is someone who thinks 
what they have is absolutely perfect, and refuses to examine the 
alternatives.

Not a very inspiring slogan though:
Python - the least of 1,000+ evils.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Anonymus functions revisited : tuple actions

2005-03-25 Thread Reinhold Birkenfeld
Ron_Adam wrote:

 What if you could:
 
 x = lambda{ x, y: x+y}  
 Hmm comma creates a problem here. so...

 from __future__ import braces
SyntaxError: not a chance


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


Re: Anonymus functions revisited

2005-03-25 Thread Ron_Adam
On 25 Mar 2005 10:09:50 GMT, Duncan Booth
[EMAIL PROTECTED] wrote:


I've never found any need for an is_defined function. If in doubt I just 
make sure and initialise all variables to a suitable value before use. 
However, I'll assume you have a good use case.

I admit that that is the better practice.  George's example was the
conversion of data from one form to another where the data is mixed
with complete and incomplete items.  And Kay is looking at tuple
unpacking.

It's hard to beat try/except for these situations though. :)

I cleaned it up some more and figured out the proper use of
_getframe().  So no lambdas, and no passing of locals needed., and it
checks for globals and builtins before defining the default value so
as not to over write a readable value.

I'm not sure what the best behavior should be.  Maybe a routine to
tell where a name is, ie.. local, global, builtin, or a writable
global?  maybe isa() return the location or None.? I think that would
be better.

The best purpose for utilities like these is for debugging and getting
feedback about the environment.  So I'm thinking of putting them in a
module for that purpose.  I have a subroutine to list all the names
attached to an object. I think I can add that a bit now too.


#---Here's the code-

import sys

def isa(v):

Check if a varable exists in the current 
(parent to this function), global, or 
builtin name spaces.

use: bool = isa( str )
 returns True or False

plocals = sys._getframe(1).f_locals
if plocals.has_key(v) or globals().has_key(v) or \
   __builtins__.locals().has_key(v):
return True
return False


def ifno(v, obj=None):

Check if a varable does not exists, return a
default value, otherwise return the varable obj.

use: obj = ifno( str [,obj=None] )
 if str exist, returns str's object
 if str does not exist, returns specified object

plocals = sys._getframe(1).f_locals
if plocals.has_key(v):
return plocals[v]
if globals().has_key(v):
return globals()[v]
if __builtins__.locals().has_key(v):
return __builtins__.locals()[v]
return obj


def test():

Test isa() and ifno() functions:


# Totally useless routine. ;)
import random
for n in range(25):

# Delete a random x,y,z coordinate to
# simulate an unrealiabe data source. 
d = random.choice([1,2,3])
if d==1:
if isa('x'): del x
elif d==2:
if isa('y'): del y
else:
if isa('z'): del z

# Replace the missing Varible with a random number.
r = int(random.random()*100)
x, y, z = ifno('x',r), ifno('y',r), ifno('z',r)
print x, y, z


if __name__ == '__main__':
test()

#-


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


Re: Version Number Comparison Function

2005-03-25 Thread Steve M
I recently saw this:

http://www.egenix.com/files/python/mxTools.html

 mx.Tools.verscmp(a,b)
Compares two version strings and returns a cmp() function
compatible value (,==, 0). The function is useful for sorting lists
containing version strings.

The logic used is as follows: the strings are compared at each
level, empty levels defaulting to '0', numbers with attached strings
(e.g. '1a1') compare less than numbers without attachement (e.g. '1a1'
 '1).

Keith wrote:
 Is there a function for comparing version numbers?
 
 E.g.
 
 0.1.0  0.1.2
 1.876b  1.876c
 3.2.2  3.4
 
 Keith

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


mod_python, user missing

2005-03-25 Thread KasiKuula
apache conf
Directory /python-publisher/
SetHandler mod_python
PythonHandler mod_python.publisher
/Directory
and this is in /python-publisher/index.py
__auth_realm__ = 'VIP'
def __auth__(req, user, passwd):
if user == 'noppa' and passwd == 'potti':
return True
  else:
return False
def __access__(req, user):
if user == 'noppa':
return True
else:
return False
def index(req):
req.get_basic_auth_pw()
user = req.user
return 'user is %s' % (user)
So problem is, how I get user in index function? That gives allways None
--
 (8)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Diez B. Roggisch
 
 I'll try to reduce my pages of ranting to a single question. In
 posting, i was wondering if the syntactic sugar (Acceptors) that i
 invented to implement the solution is of any general interest. So are
 there maybe examples less straightforward than this one, where
 Acceptors work better? Or can you always just turn the generator
 inside out in the way you have done here?
 
 If you can always do it your way, well, thats a powerful design
 pattern, and it just goes to show my faith in Generators was justified
 :) And that I wasnt thinking hard /clearly enough about how to use
 them.
 
 There are other issues, like Does the Acceptor syntax, although
 perhaps functionally equivalent to other methods, ever make the code
 more readable, easier to parse, etc? But they're a lot less important
 i'd say.


To me your acceptors look like micro-threads or similar concepts that have
been popped up here every now and then - but so far it seems they didn't
end up beeing included. I can't say for what reasons though.

Just yesterday I looked into stackless python to grasp what it does, and
while it is not syntactically different to standard python, it seems to
make coding the way you intend to do possible.


-- 
Regards,

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


Suggest more finesse, please. I/O and sequences.

2005-03-25 Thread Qertoip
Would you like to suggest me any improvements for the following code?
I want to make my implementation as simple, as Python - native, as fine as
possible.

I've written simple code, which reads input text file and creates words'
ranking by number of appearence.

Code:
---
import sys

def moreCommonWord( x, y ):
if x[1] != y[1]:
return cmp( x[1], y[1] ) * -1
return cmp( x[0], y[0] )

wordsDic = {}
inFile = open( sys.argv[1] )
for word in inFile.read().split():
if wordsDic.has_key( word ):
wordsDic[word] = wordsDic[word] + 1
else:
wordsDic[word] = 1
inFile.close()

wordsLst = wordsDic.items()
wordsLst.sort( moreCommonWord )

outFile = open( sys.argv[2], 'w')
for pair in wordsLst:
outFile.write( str( pair[1] ).rjust( 7 ) +  :  + str( pair[0] ) + 
\n )
outFile.close()
---

In particular, I don't like reading whole file just to split it. 
It is easy to read by lines - may I read by words with that ease?

PS I've been learning Python since todays morning, so be understanding :

-- 
Greets,
Piotrek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Jordan Rastrick
Wow, if I'm going to get replies (with implemented solutions!) this
quickly, I'll post here more often :-)

This is the most different to my solution, and also the shortest, and
therefore the most interesting, reply so far. Its also the last one
I'll reply to before I go to bed. 

Its taken me a while to get a rough understanding of this code, but I
think I have some idea. Correct me if I'm wrong.

groupby groups based on value of line(record)

Record returns 1 for the first line, 1 of the second, 1 for the 3rd,
then 2 for the 4th because seq[0] gets incremented since len(line)  20

OK thats fair enough. But how does record retain state between calls?
How is that related to the fact your storing your value as a singleton
list, instead just an int?

It seems a little confusing to be honest, probably mainly due to my
unfamiliarity with groupby. Retaining state between method calls is
part of what interests me so much about the Generator/ Acceptor case.
Here youre retaining state between calls with none of the special
syntax used for example in Generators.

How? Is it a side effect of the way groupby uses record? If so, then
thats a littleoblique and unreadable for my liking.

Is the state the record returns passed back to it somehow? I take it
gets passed a value for seq at some point, seeing as how you've
bothered to define it as a default argument rather than just seq = [0]
on the first line.

That works, but at the cost of having to return and pass all of state
every call. I imagine other solutions (Generator/Acceptor based etc)
would be substanitally more efficient. And again more readable, to a
Python beginner such as myself at least.

Still, this is fascinating going to have to spend some time
experimenting with groupby as soon as I get a chance

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


Re: Python 2.4 | 7.3 The for statement

2005-03-25 Thread Ron_Adam

-- Your code
foo = 0
for item1 in range(10):
  for item2 in range(10):
foo = item1 + item2
if foo == 2:
  print Let's see
  break # let's go
  if (item1 + item2) == 2:
break # one more time
print foo

The outer loop never reaches 1, so we can get rid of it along with the
second if statement, the additions aren't needed either. 

So what you have left is this.

for foo in range(3):
pass
print Let's see  
print foo 

Which is the same as:

print let's see\n, foo


I know that isn't the point. Just couldn't resist. ;)

Ron_Adam


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


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Michael Spencer
Jordan Rastrick wrote:
Wow, if I'm going to get replies (with implemented solutions!) this
quickly, I'll post here more often :-)
That is indeed typical of this most attentive group :-)
Its taken me a while to get a rough understanding of this code, but I
think I have some idea. 
It is just an example jotted in 2 min - no doubt it could be made clearer.
Correct me if I'm wrong.
groupby groups based on value of line(record)
No, groupby, groups on the value of record(item), where item is given by 
iterating over linesource

You should check the itertools documentation:
http://docs.python.org/lib/itertools-functions.html
Record returns 1 for the first line, 1 of the second, 1 for the 3rd,
then 2 for the 4th because seq[0] gets incremented since len(line)  20
In this case, it doesn't matter what record returns, as long as it is equal for 
successive values of item that should be grouped
OK thats fair enough. But how does record retain state between calls?
How is that related to the fact your storing your value as a singleton
list, instead just an int?
You are asking about the fundamental behavior of Python: argument passing, 
mutable objects and scopes.
It seems a little confusing to be honest, probably mainly due to my
unfamiliarity with groupby. Retaining state between method calls is
part of what interests me so much about the Generator/ Acceptor case.
Here youre retaining state between calls with none of the special
syntax used for example in Generators.
How? Is it a side effect of the way groupby uses record? If so, then
thats a littleoblique and unreadable for my liking.
No, it's nothing special about groupby.  record simply stores its state in a 
mutable default parameter.  This isn't general good practice: at least you have 
to be careful with it.  You can see the behavior in the following example:
  def accumulate(value, accum = []):
 ... accum.append(value)
 ... return accum
 ...
  accumulate(1)
 [1]
  accumulate(2)
 [1, 2]
  accumulate(6)
 [1, 2, 6]
 

...
Still, this is fascinating going to have to spend some time
experimenting with groupby as soon as I get a chance
Experimenting is good.  So is the the documentation: 
http://docs.python.org/tut/tut.html

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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Terry Reedy

Antoon Pardon [EMAIL PROTECTED] wrote in message

 1) It makes it hard to see how many levels are dedented at the end of
   a suite, and sometime makes it difficult to see where the end
   of a suite is. If e.g. you are looking at the code spread over
   two pieces of paper, it is sometimes hard to see whether the
   suite ends at the end of the first page or not.

One can use appropriately indented comment lines instead of closing 
brackets for this purpose.

 2) It makes it hard to introduce some kind of new syntax constructs.

I consider this as much a plus as a minus ;-)

 3) Sometimes the structure of the algorithm is not the structure
   of the code as written, people who prefer that the indentation
   reflects the structure of the algorithm instead of the structure
   of the code, are forced to indent wrongly.

Do you have any simple examples in mind?

Terry J. Reedy



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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Terry Reedy

Tim Tyler [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 What do you guys think about Python's grouping of code via indentation?

A major plus.  I was fanatic about carefully indenting my C code.

 Is it good - perhaps because it saves space and eliminates keypresses?

It eliminates redundancy.

Terry J. Reedy



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


Re: Version Number Comparison Function

2005-03-25 Thread Bengt Richter
On Fri, 25 Mar 2005 17:02:31 +0100, Fredrik Lundh [EMAIL PROTECTED] wrote:

Keith wrote:

 Is there a function for comparing version numbers?

 E.g.

 0.1.0  0.1.2
 1.876b  1.876c
 3.2.2  3.4

the following works for many common cases:

import re

def cmpver(a, b):
def fixup(i):
try:
return int(i)
except ValueError:
return i
a = map(fixup, re.findall(\d+|\w+, a))
b = map(fixup, re.findall(\d+|\w+, b))
return cmp(a, b) # -1 if ab, 0 if a=b, 1 if ab

[OT] Visually, I like the nested def fixup, and I realize
that for cmpver execution overhead is not likely to be an issue,
but in general, what do you think of not being able
to write it that way if MAKE_FUNCTION overhead is unacceptable?

What if we had something like

@sticky('fixup') # evaluate binding only first time
def cmpver(a , b):
   def fixup ... ?

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


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Serge Orlov
Michael Spencer wrote:
  Still, this is fascinating going to have to spend some time
  experimenting with groupby as soon as I get a chance
 
 Experimenting is good.  So is the the documentation:
 http://docs.python.org/tut/tut.html

Reading documentation is a good idea, but I think your example would
be more clear for Jordan if you used function attributes:

def record(item):
 if len(item)  20:
 record.seq +=1
 return record.seq
record.seq = 0

  Serge.

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


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Terry Reedy
Terminology: To me and some (most?) others posting here and, I believe, 
both the docs and the common meaning of 'generator', a Python generator is 
the particular kind of iterator that produces multiple values on request 
and which is created by the generator function that you write.

Acceptors (consumers): The concept is known to both CS and Python 
developers.  According to Tim Peters, Python generators constitute 
'semi-coroutines'.  Any full coroutine mechanism (Stackless, for instance) 
will allow the reverse (not inverse, which would undo rather than 
complement).  For various reasons, the Python developers choose that data 
chains should be written as consumer code getting data from a generator, 
which might in turn get data from a generator.

In your example, opening and reading the lines of the data file could be 
done by filterjunk, not the main function, but I can see reasons both ways.

For your specific problem, you could, I believe, use an intermediate 
generator (which could also be combined with filterjunk) that combines 
lines into complete text records.  Something like (ignoring any fussy 
details left out):

def textrecord(file):
  trlines = []
  for line in filterjunk(file):
trlines.append(line)
if complete(trline): yield ''.join(trlines)
# where 'complete' is code to determine if have all lines in record or 
not

Terry J. Reedy



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


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread James Stroud
On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
 As far as grouping by indentation goes, it's why I fell in love with
 Python in the first place.  Braces and so on are just extraneous cruft
 as far as I'm concerned.  It's the difference between Vietnamese verbs
 and Latin verbs;-)

Say I buy into the indentation ideology. Python then has this inconsistency: :

Why do we need : at the end of our if and for loops? I spend approximately 6 
minutes/100 lines of code going back and finding all of the times I missed :. 
Is it for cheating?

if False: print :

Now, what happened to the whitespace idea here? This code seems very 
unpythonic. I think : is great for slices and lamda where things go on one 
line, but to require it to specify the start of a block of code seems a 
little perlish.

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Bengt Richter
On Fri, 25 Mar 2005 08:46:12 -0800, Michael Spencer [EMAIL PROTECTED] wrote:

Tim Hochberg wrote:
 Jordan Rastrick wrote:
 

itertools.groupby enables you to do this, you just need to define a suitable 
grouping function, that stores its state:

For example, if short lines should be appended to the previous line:

from itertools import groupby
linesource = \
Here is a long line, long line, long line
and this is short
and this is short
Here is a long line, long line, long line
and this is short.splitlines()

def record(item, seq = [0]):
 if len(item)  20:
 seq[0] +=1
 return seq[0]


   for groupnum, lines in groupby(linesource, record):
  ... print .join(lines)
  ...
  Here is a long line, long line, long lineand this is shortand this is short
  Here is a long line, long line, long lineand this is short
  
Nice, but I think record is a bit opaque semantically.
How about group_id or 
generate_incrementing_unique_id_for_each_group_to_group_by or such?

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


Re: Suggesting a new feature - Inverse Generators

2005-03-25 Thread Scott David Daniels
Michael Spencer wrote:
itertools.groupby enables you to do this, you just need to define a 
suitable grouping function, that stores its state:
Michael, this would make a great Python Cookbook Recipe.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Robert Kern
James Stroud wrote:
On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
As far as grouping by indentation goes, it's why I fell in love with
Python in the first place.  Braces and so on are just extraneous cruft
as far as I'm concerned.  It's the difference between Vietnamese verbs
and Latin verbs;-)

Say I buy into the indentation ideology. Python then has this inconsistency: :
Why do we need : at the end of our if and for loops? I spend approximately 6 
minutes/100 lines of code going back and finding all of the times I missed :. 
Is it for cheating?

if False: print :
Now, what happened to the whitespace idea here? This code seems very 
unpythonic. I think : is great for slices and lamda where things go on one 
line, but to require it to specify the start of a block of code seems a 
little perlish.
During the usability studies for the language ABC, which Guido worked on 
before developing Python and also used indentation for grouping, it was 
found that the colon improved readability.

I don't know what those studies said about the frequency of people 
forgetting to put in the colon. Anecdotally, I can say that I do it very 
rarely.

--
Robert Kern
[EMAIL PROTECTED]
In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-25 Thread Bill Mill
On Fri, 25 Mar 2005 11:38:37 -0800, Robert Kern [EMAIL PROTECTED] wrote:
 James Stroud wrote:
  On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
 
 As far as grouping by indentation goes, it's why I fell in love with
 Python in the first place.  Braces and so on are just extraneous cruft
 as far as I'm concerned.  It's the difference between Vietnamese verbs
 and Latin verbs;-)
 
 
  Say I buy into the indentation ideology. Python then has this 
  inconsistency: :
 
  Why do we need : at the end of our if and for loops? I spend approximately 6
  minutes/100 lines of code going back and finding all of the times I missed 
  :.
  Is it for cheating?
  
  if False: print :
 
  Now, what happened to the whitespace idea here? This code seems very
  unpythonic. I think : is great for slices and lamda where things go on one
  line, but to require it to specify the start of a block of code seems a
  little perlish.
 
 During the usability studies for the language ABC, which Guido worked on
 before developing Python and also used indentation for grouping, it was
 found that the colon improved readability.
 
 I don't know what those studies said about the frequency of people
 forgetting to put in the colon. Anecdotally, I can say that I do it very
 rarely.
 

I can't remember having ever done it, although I am sure I have. The
real question is, though, 6 minutes per 100 lines of code? There
probably aren't more than 30 lines out of those 100 that should end in
a colon. Assuming you forget half your colons, you're spending upwards
of 20 seconds per colon?

If you want, I'll write a script that checks for colons at the end of
lines before increased indentation, and asks you if you want to put
one there - I could save you 5.8 minutes per 100 lines of code. How's
that for a productivity boost?

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Example Code - Named Pipes (Python 2.4 + ctypes on Windows)

2005-03-25 Thread Paul L. Du Bois

Srijit Kumar Bhadra wrote:
 Hello,
 Here is an example of Multithreaded Pipe Server and Client using the
 excellent ctypes library (Windows).

Coincidentally, the other day I just used named pipes in for the first
time.  I recommend using the excellent win32api extension; I believe it
is included by deafult in the ActiveState distro.

The API calls look fairly similar, but you pass strings instead of
c_whatever_p(), they return tuples, and they throw exceptions instead
of returning HRESULT h s.t. FAILED(h).  The resulting code feels much
more Pythonic.  For example, my first test looked like this:

def testread(self):
Read all data currently in pipe.
while True:
try:
(nRead, nAvail, nMessage) =
win32pipe.PeekNamedPipe(self.hFile, 0)
if nAvail:
(hr, data) = win32file.ReadFile(self.hFile, nAvail)
return data
except pywintypes.error, e:
errno = e.args[0]
if errno == 109:  # other end disconnected
self.disconnect()
self.connect()
else:
raise

It's kind of cool that you can directly port C code to Python, but the
end result is IMO nigh-unreadable.

p

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


  1   2   >