Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Kay Schluehr

Robert Brewer wrote:
> Bengt Richter wrote:
> > The '::' unary suite operator should return an ordered dict
> > subtype representing the bindings
>
> Why ordered?

Because You can't otherwise guarantee to feed optional argument
parameters in a correct way.

Example:

x = property(*seq) where:
seq = (item[1] for item in ::
def get_x():
return self.__x
def set_x(value):
self.__x = value
del_x = None
doc   = "I'm the 'x' property." )

This statement would not work if the result of '::' ( considered as an
"ordered dict" ) would return simply a dict because the order of the
input parameters matters.

Ciao,
Kay

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


Re: pre-PEP: Simple Thunks

2005-04-16 Thread Ron_Adam
On Sat, 16 Apr 2005 17:25:00 -0700, Brian Sabbey
<[EMAIL PROTECTED]> wrote:

>> You can already do this, this way.
>>
> def f(thunk):
>> ... before()
>> ... thunk()
>> ... after()
>> ...
> def before():
>> ... print 'before'
>> ...
> def after():
>> ... print 'after'
>> ...
> def stuff():
>> ... print 'stuff'
>> ...
> def morestuff():
>> ... print 'morestuff'
>> ...
> f(stuff)
>> before
>> stuff
>> after
> f(morestuff)
>> before
>> morestuff
>> after
>
>>
>> This works with arguments also.
>
>Yes, much of what thunks do can also be done by passing a function 
>argument.  But thunks are different because they share the surrounding 
>function's namespace (which inner functions do not), and because they can 
>be defined in a more readable way.

Generally my reason for using a function is to group and separate code
from the current name space.  I don't see that as a drawback.

Are thunks a way to group and reuse expressions in the current scope?
If so, why even use arguments?  Wouldn't it be easier to just declare
what I need right before calling the group?  Maybe just informally
declare the calling procedure in a comment.

def thunkit:  # no argument list defines a local group.
# set thunk,x and y before calling.  
before()
result = thunk(x,y)
after()

def foo(x,y):
x, y = y, x
return x,y

thunk = foo
x,y = 1,2
do thunkit
print result

-> (2,1)

Since everything is in local name space, you  really don't need to
pass arguments or return values.  

The 'do' keyword says to evaluate the group.  Sort of like eval() or
exec would, but in a much more controlled way.  And the group as a
whole can be passed around by not using the 'do'.  But then it starts
to look and act like a class with limits on it.  But maybe a good
replacement for lambas?

I sort of wonder if this is one of those things that looks like it
could be useful at first, but it turns out that using functions and
class's in the proper way, is also the best way. (?)

>You're right that, in this case, it would be better to just write 
>"f(stuff, 27, 28)".  That example was just an attempt at describing the 
>syntax and semantics rather than to provide any sort of motivation.  If 
>the thunk contained anything more than a call to 'stuff', though, it would 
>not be as easy as passing 'stuff' to 'f'.  For example,
>
>do f(27, 28):
>   print stuff()
>
>would require one to define and pass a callback function to 'f'.  To me, 
>'do' should be used in any situation in which a callback *could* be used, 
>but rarely is because doing so would be awkward.  Probably the simplest 
>real-world example is opening and closing a file.  Rarely will you see 
>code like this:
>
>def with_file(callback, filename):
>   f = open(filename)
>   callback(f)
>   f.close()
>
>def print_file(file):
>   print file.read()
>
>with_file(print_file, 'file.txt')
>
>For obvious reasons, it usually appears like this:
>
>f = open('file.txt')
>print f.read()
>f.close()
>
>Normally, though, one wants to do a lot more than just print the file. 
>There may be many lines between 'open' and 'close'.  In this case, it is 
>easy to introduce a bug, such as returning before calling 'close', or 
>re-binding 'f' to a different file (the former bug is avoidable by using 
>'try'/'finally', but the latter is not).  It would be nice to be able to 
>avoid these types of bugs by abstracting open/close.  Thunks allow you to 
>make this abstraction in a way that is more concise and more readable than 
>the callback example given above:

How would abstracting open/close help reduce bugs?  

I'm really used to using function calls, so anything that does things
differently tend to be less readable to me. But this is my own
preference.  What is most readable to people tends to be what they use
most. IMHO

>do f in with_file('file.txt'):
>   print f.read()
>
>Thunks are also more useful than callbacks in many cases since they allow 
>variables to be rebound:
>
>t = "no file read yet"
>do f in with_file('file.txt'):
>   t = f.read()
>
>Using a callback to do the above example is, in my opinion, more 
>difficult:
>
>def with_file(callback, filename):
>   f = open(filename)
>   t = callback(f)
>   f.close()
>   return t
>
>def my_read(f):
>   return f.read()
>
>t = with_file(my_read, 'file.txt')

Wouldn't your with_file thunk def look pretty much the same as the
callback?

I wouldn't use either of these examples.  To me the open/read/close
example you gave as the normal case would work fine, with some basic
error checking of course. Since Python's return statement can handle
multiple values, it's no problem to put everything in a single
function and return both the status with an error code if any, and the
result.  I would keep the open, read/write, and close statements in
the same function and not split them up.

>> When I see 'do', it reminds me of 'do lo

Decorator Syntax For Recursive Properties

2005-04-16 Thread Jeffrey Froman
Consider the following class:

class Node(object):
def __init__(self, name, parent=None):
self.name = name
self.parent = parent

def _ancestors(self, ants=None):
if ants is None:
ants = []
else:
ants.insert(0, self.name)
if self.parent is None:
return ants
return self.parent._ancestors(ants)
ancestors = property(_ancestors)

The ancestor property generates a list ancestor nodes by having each parent
examine its own name recursively. The recursion is managed by calling the
method underlying the parent property, rather than calling the property
directly.

Is it possible to rewrite this property using decorator syntax? Does the
@property decorator create some underlying method that I can call directly?

Alternately, perhaps there is a way to rewrite the recursion so that such a
call is unnecessary? Note that the property should not add its own name if
it is the originating node (the node trying to find _its_ ancestors). So
something like this didn't work for me:

@property
def ancestors(self):
if self.parent is None:
return [self.name]
return [self.name] + self.parent.ancestors

In other words, since there is no longer a list passing from child to parent
during the recursion, is there a graceful way to examine the state of the
ancestor list so far?


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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Oren Tirosh
Take a look at Nick Coglan's "with" proposal:

http://groups.google.co.uk/groups?selm=mailman.403.1105274631.22381.python-list%40python.org

It addresses many of the same issues (e.g. easy definition of
properties). It is more general, though: while your proposal only
applies to keyword arguments in a function call this one can be used
to name any part of a complex expression and define it in a suite.

I think that a good hybrid solution would be to combine the "with"
block with optional use of the ellipsis to mean "all names defined in
the with block".

See also the thread resulting from Andrey Tatarinov's original
proposal (using the keyword "where"):

http://groups.google.co.uk/groups?selm=3480qqF46jprlU1%40individual.net


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


RE: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Robert Brewer
Bengt Richter wrote:
> The '::' unary suite operator should return an ordered dict 
> subtype representing the bindings

Why ordered?


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Kay Schluehr
Bengt Richter wrote:
> On Sun, 17 Apr 2005 01:10:47 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:
> [...]
> >
> >The "::" expression I'm proposing generalizes capturing suite
bindings into an ordered sequence of (key,value)
> >tuples, like an ordered vars().items() limited to the bindings
produced in the suite following "::"
> >Thus
> >items = ::
> >x = 1
> >y = [1,2]
> >def foo():pass

I like this idea of "folding definitions into dicts" very much and
think that it is on the ground of suite-basing. It breaks down the
barrier between expressions and statements in Python without
annihilating it. I think it is also wise to restrict '::' to certain
accumulations. I don't like the idea of storing and dropping whole code
fragments in an irresponsible manner as Brian did for trapping the
compiler in his generator-to-function example of the thunks pre-PEP.

I think that '::' and 'where' are true and explicit representations of
the content of this proposal and be less redundant than the "as
" syntax with it's various specifiers. Introducing '::'
would make the "folding definitions into dict" operation visible that
takes place in the machinery of the VM. Very Pythonic IMHO :-)

+1 from me for '::' and 'where'.

Regards,
Kay

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


Re: Compute pi to base 12 using Python?

2005-04-16 Thread Tim Roberts
Dick Moores <[EMAIL PROTECTED]> wrote:

>M.E.Farmer wrote at 23:18 4/14/2005:
>>Nice collection of unix tools, Cygwin not needed.
>>http://unxutils.sourceforge.net/
>
>Thank you!
>
>But a question. I've download both UnxUtils.zip and UnxUpdates.zip. I'm 
>planning to put the contents of UnxUtils.zip in a directory and then move 
>the contents of UnxUpdates.zip, which has many of the same filenames, to 
>the same directory. Should I just let Windows replace the old files with 
>the updated ones?

Yes.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compute pi to base 12 using Python?

2005-04-16 Thread Tim Roberts
Dick Moores <[EMAIL PROTECTED]> wrote:
>>
>># Reading/writing Python source often gives me the impression of
>># reading/writing a poem!
>># Layout, indentation, rythm, I like the look and feel!
>>
>># What does this tiny program do? It is not a sonnet, even not a
>># pi-sonnet, but it surely produces Pi!
>
>It sure does. When I ran it my jaw dropped. I had 7,947 CORRECT digits in 
>2 minutes 0 seconds (by my stopwatch)!

How do you know?  I think the 7,912th digit is wrong.

;)
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: whitespace , comment stripper, and EOL converter

2005-04-16 Thread M.E.Farmer
Thanks Jean,
I have thought about adding docstrings several times, but I was stumped
at how to determine a docstring from a regular tripleqoted string ;)
I have been thinking hard about the problem and I think I have an idea.
If the line has nothing before the start of the string it must be a
docstring.
Sounds simple enough but in Python there are 12 or so 'types' of
strings .
Here is my crack at it feel free to improve it ;)
I reversed  the logic on the comments and docstrings so I could add a
special mode to docstring stripping ...pep8 mode .
Pep8 mode only strips double triple quotes from your source code
leaving the offending single triple quotes behind. Probably just stupid
but someone might find it usefull.
 ##
# Python source stripper
##

import os
import sys
import token
import keyword
import StringIO
import tokenize
import traceback
__credits__ = '''
Jürgen Hermann
M.E.Farmer
Jean Brouwers
'''
__version__ = '.8'
__author__ = 'M.E.Farmer'
__date__ =  'Apr 16, 2005,' \
'Jan 15 2005,' \
'Oct 24 2004' \


##

class Stripper:
"""Python source stripper
"""
def __init__(self, raw):
self.raw = raw

def format(self, out=sys.stdout, comments=0, docstrings=0,
spaces=1, untabify=1, eol='unix'):
""" strip comments,
strip docstrings,
strip extra whitespace and lines,
convert tabs to spaces,
convert EOL's in Python code.
"""
# Store line offsets in self.lines
self.lines = [0, 0]
pos = 0
# Strips the first blank line if 1
self.lasttoken = 1
self.temp = StringIO.StringIO()
self.spaces = spaces
self.comments = comments
self.docstrings = docstrings

if untabify:
   self.raw = self.raw.expandtabs()
self.raw = self.raw.rstrip()+' '
self.out = out

# Have you ever had a multiple line ending script?
# They can be nasty so lets get them all the same.
self.raw = self.raw.replace('\r\n', '\n')
self.raw = self.raw.replace('\r', '\n')
self.lineend = '\n'

# Gather lines
while 1:
pos = self.raw.find(self.lineend, pos) + 1
if not pos: break
self.lines.append(pos)

self.lines.append(len(self.raw))
self.pos = 0

# Wrap text in a filelike object
text = StringIO.StringIO(self.raw)

# Parse the source.
## Tokenize calls the __call__
## method for each token till done.
try:
tokenize.tokenize(text.readline, self)
except tokenize.TokenError, ex:
traceback.print_exc()

# Ok now we write it to a file
# but we also need to clean the whitespace
# between the lines and at the ends.
self.temp.seek(0)

# All this should be written into the
# __call__ method just haven't yet...

# Mac CR
if eol == 'mac':
   self.lineend = '\r'
# Windows CR LF
elif eol == 'win':
   self.lineend = '\r\n'
# Unix LF
else:
   self.lineend = '\n'

for line in self.temp.readlines():
if spaces == -1:
self.out.write(line.rstrip()+self.lineend)
else:
if not line.isspace():
self.lasttoken=0
self.out.write(line.rstrip()+self.lineend)
else:
self.lasttoken+=1
if self.lasttoken<=self.spaces and self.spaces:
self.out.write(self.lineend)

def __call__(self, toktype, toktext,
 (srow,scol), (erow,ecol), line):
""" Token handler.
"""
# calculate new positions
oldpos = self.pos
newpos = self.lines[srow] + scol
self.pos = newpos + len(toktext)

# kill comments
if self.comments:
if toktype == tokenize.COMMENT:
return

# kill doc strings
if self.docstrings:
# Assume if there is nothing on the
# left side it must be a docstring
if toktype == tokenize.STRING and \
line.lstrip(' rRuU')[0] in ["'",'"']:
t = toktext.lstrip('rRuU')
if (t.startswith('"""') and
(self.docstrings == 'pep8' or
 self.docstrings =='8')):
 return
elif t.startswith('"""') or t.startswith("'''"):
 return

# handle newlines
if toktype in [token.NEWLINE, tokenize.NL]:
self.temp.write(self.lineend)
return

# send the original whitespace
if newpos > ol

Re: Python's use in RAD

2005-04-16 Thread Luis M. Gonzalez
Check this out: http://pythoncard.sourceforge.net/

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


Re: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 141)

2005-04-16 Thread
!!
-- 
http://mail.python.org/mailman/listinfo/python-list


pysvn install on freebsd

2005-04-16 Thread Timothy Smith
has anyone used or installed this on fbsd
the install for it is totally redundant. i get this error for it
make -f freebsd.mak clean all test
cd ../Source && make -f pysvn_freebsd_py.mak clean
make: cannot open pysvn_freebsd_py.mak.
*** Error code 2
Stop in /usr/home/timothy/pysvn-1.1.2/Extension/Builder.
--
http://mail.python.org/mailman/listinfo/python-list


Re: new to mac OS10

2005-04-16 Thread Robert Kern
Maurice LING wrote:
Hi Thomas,
It seems that you've cleanly killed the Apple-installed Python, which 
isn't too bad a thing after all. What I can suggest you do is this... 
Copy the entire /System/Library/Frameworks/Python.framework directory 
from someone and drop it into your system (same place of course). I will 
not suggest installing Python 2.4.1 until the Apple-installed Python is 
sorted out. My reasons being,

1. I have no idea what Mac OSX uses Python for. Although symlink may get 
you through most of the time but I cannot be sure that none of OSX's 
stuffs are hardcoded to use the Python in 
/System/Library/Frameworks/Python.framework.
I believe Apple only uses it for their fax utilities. There's also the 
CoreGraphics wrapper (which the fax stuff uses), but that's pretty 
useless as it is.

2. Installing another Python may or may not be a precise remedy. It may 
just worsen things and I won't want to bet on that.
The 2.4.1 build by Bob Ippolito is designed to work alongside the 
system-installed Python. It certainly won't replace it, but it shouldn't 
worsen anything.

3. Apple-installed Python's command line tools are symlinked from 
/usr/bin to /System/Library/Frameworks/Python.framework but the OSX 
installer for Python 2.4.1 places the commandline tools in 
/usr/local/bin and symlinked to /Library/Frameworks/Python.framework. So 
it seems to me that Python 2.4.1 (installed using OSX installer for 
Python 2.4.1) is not a precise replacement of Apple-installed Python...
Bingo. It's not intended to be one.
--
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: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Bengt Richter
On Sun, 17 Apr 2005 01:10:47 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:
[...]
>
>The "::" expression I'm proposing generalizes capturing suite bindings into an 
>ordered sequence of (key,value)
>tuples, like an ordered vars().items() limited to the bindings produced in the 
>suite following "::"
>Thus
>items = ::
>x = 1
>y = [1,2]
>def foo():pass
>
>print items => (('x', 1), ('y', [1, 2]), ('foo',  0x02EE8D14>))
>
Update, sorry. Galloping evolution here ;-)

The '::' unary suite operator should return an ordered dict subtype 
representing the bindings, so

 print items => {'x':1, 'y':[1, 2], 'foo':}

instead. This allows cleaner suite-based keyword calling, since no 
dict(::) is necessary,

so
 def foo(**kw): print kw

followed by

 foo(**::
 x = 1
 y = [1,2]
 def foo():pass)

will print the same. Since :: is an expression, it can go anywhere an 
expression can go.
I like orthogonality ;-)

Methods allow (with order preserved from binding in suite)

(:: x=1; y=2).keys()   # => ['x', 'y']
and
(:: x=1; y=2).values() # => [1, 2]
and
(:: x=1; y=2).items()  # => [('x', 1), ('y', 2)]

note that :: is ;-greedy in one-line suites, so
   :: x=1; y=2
is not
   (:: x=1); y=2

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
On Sat, 16 Apr 2005 14:01:56 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote:

>Reinhold Birkenfeld wrote:
>> Brian Sabbey wrote:
>>> Here is a pre-PEP for what I call "suite-based keyword arguments". The
>>> mechanism described here is intended to act as a complement to thunks.
>>> Please let me know what you think.
>>>
>>> Suite-Based Keyword Arguments
>>> -
>>>
>>> Passing complicated arguments to functions is currently awkward in Python.
>>> For example, the typical way to define a class property winds up polluting
>>> the class's namespace with the property's get/set methods.  By allowing
>>> keyword arguments to be defined in a suite following a function call,
>>> complicated arguments can be passed in a cleaner, easier way.
>>>
>>> Examples
>>> 
>>>
>>> Using suite-based keyword arguments, the code
>>>
>>> f(x = 1)
>>>
>>> is equivalent to
>>>
>>> f():
>>> x = 1
>>
>> Pretty cool, but it interferes with current suites.
>>
>> How would you write
>>
>> if f(x=1):
>>print "yes"
>>
>> using suite-based keyword args?
>>
>> Reinhold
>>
>
   if f(x=1) where: x=23:
   print "yes"

"where:" expression trailer intoduces a suite whose net bindings are used to 
evaluate the names
in the expression it trails, which means the calling parameters, if the 
expression is a call.
Syntacticaly where: should be equivalent to '' other than its name 
binding effect (which
is only for the call -- i.e.,
x = 123
foo(x) where: x=1  # => foo(1)
print x # => 123

>You wouldn't be able to use suite keywords in that situation.  Also, one 
>would not be able to use suite keywords when there is more than one 
>function call on the same line:
>
>y = f()*g():
>   x = 1# ??  not allowed

Stretching for it, using my latest and greatest ;-)

y = f(**::
   x = 1
   y = 'y for f'
)*g(**::
   x = 'x for g'
   y = 'y for g'
   def foo(): return 'foo for g'
)

Note that there is no problem adding other parameters, because :: is just
a unary expression returning dict subtype instance, e.g.,

y = f(11,22,**::
   x = 1
   y = 'y for f'
)*g(*args_from_somewhere, **::
   x = 'x for g'
   y = 'y for g'
   def foo(): return 'foo for g'
)


This assumes that the unary :: expression returns an ordered dict subtype
instance containing the bindings created in the suite following the unary suite 
operator ::
E.g,
d = ::
x = 1
y = 2
print d # => {'x':1, 'y':2}

(Ignore version of previous posts where :: returned d.items() in place of d 
here)
>
>There is only so much suites can do.  Cases in which you want to do both 
>are probably far enough between that it seems acceptable to me to require 
>two suites:
>
>t = f():
>  x = 1
>if t:
>  y = 1

It's a little clunky, but

if self.f(self, z, *a) where:
z=123
a = getarglist(): # ':' terminates transparent where:
y = 1  # indentation as if where: were == ''

>
>In general, I think that anything more than just a function call with an 
>optional assignment should be disallowed:
>
>y = [f()]:  #  ? probably shouldn't be allowed
>   x = 1

y = [f(**:: x=1)] # sort form with single-line  for ::
or
y = [f(**::
 x = 1
)]

isolates the suite better, in case it has logic and fancy stuff
Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML parsing per record

2005-04-16 Thread William Park
Willem Ligtenberg <[EMAIL PROTECTED]> wrote:
> I want to parse a very large (2.4 gig) XML file (bioinformatics
> ofcourse :)) But I have no clue how to do that. Most things I see read
> the entire xml file at once. That isn't going to work here ofcourse.
> 
> So I would like to parse a XML file one record at a time and then be
> able to store the information in another object.  How should I do
> that?
> 
> Thanks in advance,
> 
> Willem Ligtenberg A total newbie to python by the way.

You may want to try Expat (www.libexpat.org) or Python wrapper to it.
You can feed small piece at a time, say by lines or whatever.  Of
course, it all depends on what kind of parsing you have in mind. :-)

Care to post more details?

-- 
William Park <[EMAIL PROTECTED]>, Toronto, Canada
Slackware Linux -- because it works.

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
On Sat, 16 Apr 2005 13:58:38 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote:

[...]
>
>Yes, my description of the syntax was ambiguous.  To clarify, I intended 
>the syntax to be backwardly compatible.  That is, one would not be able to 
>use a suite to define keywords if there already exists a suite for other 
>reasons.  So, one would not be able to use a suite to pass keywords to 'f' 
>in this situation:
>
>if f():
>  x = 1
>
>This code should behave exactly as it does now.
>
>I agree that the ellipsis idea probably makes the code more readable, and 
>it may be a good idea to have them for that reason.  However, ellipses are 
>not necessary as a way to disambiguate the syntax; all statements 
>containing suites currently begin with a keyword, and keyword suites would 
>not.
>
Using my expression where: trailer, the above if could be spelled

if f(x) where: x=1: # where: acts like '' other than its semantics.
   do_something()

I was debating whether to use a where: that applied to a whole previous 
statement and its suite,
indenting as if the where were a following statment, e.g.,

if f(x):
do_something()
where:
x = 1

But I thought that could get too far away, and not cover many use cases that 
could be done
other ways. The thing that where does though is create a transient namespace 
for the suite
bindings, so they don't clobber the calling namespace the way just prefixing a 
setup would

x = 1 # clobber x
if f(x):
do_something()

Shoot, I just has another idea about the :: expression -- instead of 
returning a tuple,
it could return an order-maintaining subtype of dict with methods for items(), 
keys() and values()
and that would make better spellings for many examples in Kay's post ;-/

Also suite-based keyword calling would just become

f(10, 4, **::  # note ease of including other parameters if part of the 
signature
 x = 1
 y = 2 )

and you could do
print (::
x = 1
y = 2
).keys()
=> ['x', 'y']

or call foo
foo(self, whatever, *(::
x = 1
y = 2).values())

Oh well, that's the way ideas evolve ;-)

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


Re: new to mac OS10

2005-04-16 Thread Maurice LING
Hi Thomas,
It seems that you've cleanly killed the Apple-installed Python, which 
isn't too bad a thing after all. What I can suggest you do is this... 
Copy the entire /System/Library/Frameworks/Python.framework directory 
from someone and drop it into your system (same place of course). I will 
not suggest installing Python 2.4.1 until the Apple-installed Python is 
sorted out. My reasons being,

1. I have no idea what Mac OSX uses Python for. Although symlink may get 
you through most of the time but I cannot be sure that none of OSX's 
stuffs are hardcoded to use the Python in 
/System/Library/Frameworks/Python.framework.

2. Installing another Python may or may not be a precise remedy. It may 
just worsen things and I won't want to bet on that.

3. Apple-installed Python's command line tools are symlinked from 
/usr/bin to /System/Library/Frameworks/Python.framework but the OSX 
installer for Python 2.4.1 places the commandline tools in 
/usr/local/bin and symlinked to /Library/Frameworks/Python.framework. So 
it seems to me that Python 2.4.1 (installed using OSX installer for 
Python 2.4.1) is not a precise replacement of Apple-installed Python...

For me, my setup is this
ls -all /usr/bin/python*
lrwxr-xr-x  1 root  wheel   14  4 Apr 08:40 /usr/bin/python -> 
/sw/bin/python
lrwxr-xr-x  1 root  wheel   72  1 Apr  1976 /usr/bin/python2.3 -> 
../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python
lrwxr-xr-x  1 root  wheel   10  1 Apr  1976 /usr/bin/pythonw -> pythonw2.3
-rwxr-xr-x  1 root  wheel  122  9 Jun  2003 /usr/bin/pythonw2.3

/usr/bin/pythonw2.3 and /usr/bin/python2.3 points to the same thing, 
/System/Library/Frameworks/Python.framework/Versions/2.3/bin/python. And 
I have Fink's Python in /sw/bin/python.

So now, for me, if I need to use the Apple-installed Python, my command 
line is "pythonw" while "python" gives me Fink's Python as shown below:

~ mauriceling$ pythonw
Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python23.zip', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-darwin', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/lib-scriptpackages', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-dynload', 
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages']
>>>

~ mauriceling$ python
Python 2.3.5 (#1, Apr  6 2005, 13:01:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/sw/lib/python23.zip', '/sw/lib/python2.3', 
'/sw/lib/python2.3/plat-darwin', '/sw/lib/python2.3/plat-mac', 
'/sw/lib/python2.3/plat-mac/lib-scriptpackages', 
'/sw/lib/python2.3/lib-tk', '/sw/lib/python2.3/lib-dynload', 
'/sw/lib/python2.3/site-packages', 
'/sw/lib/python2.3/site-packages/Numeric', 
'/sw/lib/python2.3/site-packages/libsbml', 
'/sw/lib/python2.3/site-packages/gtk-2.0']
>>>

There is no problem with having multiple versions and copies of Pythons 
in your system. The problems are:

1. get all the symlinks correct
2. know when to use what and how to use
3. means that you may have to install the same 3rd party library x-times 
for x-numbers of Pythons you might have... quite a pain...

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


Re: pre-PEP: Simple Thunks

2005-04-16 Thread Brian Sabbey
Bengt Richter wrote:
Good background on thunks can be found in ref. [1].
UIAM most of that pre-dates decorators. What is the relation of thunks
to decorators and/or how might they interact?
Hmm, I think you answered this below better than I could ;).
def f(thunk):
   before()
   thunk()
   after()
do f():
   stuff()
The above code has the same effect as:
before()
stuff()
after()
Meaning "do" forces the body of f to be exec'd in do's local space? What if 
there
are assignments in f? I don't think you mean that would get executed in do's 
local space,
that's what the thunk call is presumably supposed to do...
Yes, I see now that there is an ambiguity in this example that I did not 
resolve.  I meant that the suite of the 'do' statement gets wrapped up as 
an anonymous function.  This function gets passed to 'f' and can be used 
by 'f' in the same way as any other function.  Bindings created in 'f' are 
not visible from the 'do' statement's suite, and vice-versa.  That would 
be quite trickier than I intended.

Other arguments to 'f' get placed after the thunk:
def f(thunk, a, b):
# a == 27, b == 28
before()
thunk()
after()
do f(27, 28):
stuff()
I'm not sure how you intend this to work. Above you implied (ISTM ;-)
that the entire body of f would effectively be executed locally. But is that
true? What if after after() in f, there were a last statment hi='from last 
statement of f'
Would hi be bound at this point in the flow (i.e., after d f(27, 28): stuff() )?
I didn't mean to imply that.  The body of 'f' isn't executed any 
differently if it were called as one normally calls a function.  All of 
its bindings are separate from the bindings in the 'do' statement's scope.

I'm thinking you didn't really mean that. IOW, by magic at the time of calling 
thunk from the
ordinary function f, thunk would be discovered to be what I call an executable 
suite, whose
body is the suite of your do statement.
yes
In that case, f iself should not be a callable suite, since its body is _not_ 
supposed to be called locally,
and other than the fact that before and after got called, it was not quite 
exact to say it was _equivalent_ to
before()
stuff() # the do suite
after()
yes, I said "same effect as" instead of "equivalent" so that too much 
wouldn't be read from that example.  I see now that I should have been 
more clear.

In that case, my version would just not have a do, instead defining the do suite
as a temp executable suite, e.g., if instead
we make an asignment in the suite, to make it clear it's not just a calling 
thing, e.g.,
do f(27, 28):
 x = stuff()
then my version with explict name callable suite would be
def f(thunk, a, b):
 # a == 27, b == 28
 before()
 thunk()
 after()
set_x():
x = stuff() # to make it plain it's not just a calling thing
f(set_x, 27, 28)
# x is now visible here as local binding
but a suitable decorator and an anonymous callable suite (thunk defined my way 
;-) would make this
@f(27, 28)
(): x = stuff()
Hmm, but this would require decorators to behave differently than they do 
now.  Currently, decorators do not automatically insert the decorated 
function into the argument list.  They require you to define 'f' as:

def f(a, b):
def inner(thunk):
before()
thunk()
after()
return inner
Having to write this type of code every time I want an thunk-accepting 
function that takes other arguments would be pretty annoying to me.

Thunks can also accept arguments:
def f(thunk):
   thunk(6,7)
do x,y in f():
   # x==6, y==7
   stuff(x,y)
IMO
   @f
   (x, y): stuff(x, y)   # like def foo(x, y): stuff(x, y)
is clearer, once you get used to the missing def foo format
OK.  I prefer a new keyword because it seems confusing to me to re-use 
decorators for this purpose.  But I see your point that decorators can be 
used this way if one allows anonymous functions as you describe, and if 
one allows decorators to handle the case in which the function being 
decorated is anonymous.

The return value can be captured
This is just a fallout of f's being an ordinary function right?
IOW, f doesn't really know thunk is not an ordinary callable too?
I imagine that is for the CALL_FUNCTION byte code implementation to discover?
yes

def f(thunk):
   thunk()
   return 8
do t=f():
   # t not bound yet
   stuff()
print t
==> 8
That can't be done very well with a decorator, but you could pass an
explicit named callable suite, e.g.,
thunk(): stuff()
t = f(thunk)
But not having to do it that way was most of the purpose of thunks.
Thunks blend into their environment
ISTM this needs earlier emphasis ;-)
def f(thunk):
   thunk(6,7)
a = 20
do x,y in f():
   a = 54
print a,x,y
==> 54,6,7
IMO that's more readable as
   def f(thunk):
   thunk(6, 7)
   @f
   (x, y): # think def foo(x, y): with "def foo" missing to make it a 
thunk
   a = 54
   print a,x,y
IMO we need some real use cases, or we'll never be ab

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
On Sat, 16 Apr 2005 14:02:32 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote:

>Bengt Richter wrote:
>> On Fri, 15 Apr 2005 19:32:02 -0700, James Stroud <[EMAIL PROTECTED]> wrote:
 Examples
 

 Using suite-based keyword arguments, the code

 f(x = 1)

 is equivalent to

 f():
 x = 1
>>
>>   f(**def():
>> x = 1
>> return vars())
>
>Yes, it seems it would just be sugar for full lambdas.  Although, in this 
>example and the others, wouldn't you have to actually call the anonymous 
>function?
D'oh, yes, but you got the idea ;-)
>
>f(**(def():
>   x = 1
>   return vars())())
>
>Otherwise it seems like you are trying to pass a function, not the 
>keywords the function returns.
>
>One could, of course, also do the same with a named function:
>
>def no_longer_anonymous():
>   x = 1
>   return vars()
>
>f(**no_longer_anonymous())

Yes, but that does away with the trailing suite definition of the bindings from 
the pov of f ;-)

BTW, I hope you will read my latest post replying to Kay Schluehr, where I 
propose some different
spellings ;-)

f():
x = 1

would be spelled

f(**kw) where:
kw = dict(::
x = 1)

or could also be

f(x=x) where:
x = 1

"::" is a unary suite operator that returns an ordered vars().items() 
representing the net bindings made
in the suite (i.e. del  will remove a binding just as for vars()). 
:: is a first class expression.

items = ::
x = 1
y = 2
print items => (('x', 1), ('y', 2))

"where:" is an expression trailer introducing a suite like :: except that the 
bindings are used to evaluate
the names in the expression that the "where:" trails, not to produce an items() 
tuple.

See the other post replying to Kay for more, superseding some things in my 
reply to you ;-)

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


Re: RE Engine error with sub()

2005-04-16 Thread Maurice LING
Solved it. Instead of modifying Replacer class, I've made another class 
which initiates a list of Replacer objects from a list of substitution 
rule files. And then iterates through the list of Replacer objects and 
calls upon their own substitute() method. It seems to work.

Thanks for all your advices.
Cheers
Maurice
Maurice LING wrote:
Hi all,
I think I might have a workaround to this problem but have no idea how 
to work it through. I hope that someone can kindly help me out because I 
do not quite understand the mechanics of the _make_regex() method in the 
original codes...

My idea is, instead of having one UserDict, have a list of UserDicts. So 
 a large unprocessable replacement rule set is split into multiple 
smaller files, with each file read into a UserDict and it is made into a 
 RE matcher. Then iterative matching using a list of REs.

In short, the current precedure is
1 dictionary, 1 RE, 1 RE matcher... to match inputs
My workaround is to change it to
list of dictionaries, list of REs, list of RE matcher... iterative 
matching of inputs.

Can someone kindly help me out here?
Thanks in advance.
Cheers,
Maurice
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Bengt Richter
On 16 Apr 2005 09:07:09 -0700, "Kay Schluehr" <[EMAIL PROTECTED]> wrote:

>The idea is interesting but not unambigously realizable. Maybe one
>should introduce some extra syntax for disambiguation and thereby
>generalize the proposal.
This is intriguing. I am reminded of trailing "where x is something" phrase, 
but with
an implied x.
>
>as :
>   # list of definitions and assignments
ISTM this list, other than for func, always could be considered to
generate an ordered sequence of (key, value) pairs that need to be plugged into
the preceding context. Where to plug it in is implicit, but it could be given
explicit target name(s) in an expression, e.g.,
  where: 

and  would be a series of assignments like for suite-based 
keywords, except that
the key names would be used in resolving the names in the expression preceding 
the where:, e.g.,
foo(x, y) where:
x = 1
y = 2

would make the foo call using the where bindings by name, here effectively 
calling foo(1, 2) 
But sometimes we want all the bindings in a suite in a chunk, as with 
suite-based keyword bindings.

I'm proposing below a unary suite operator spelled '::' which will return a 
single tuple of 2-tuples
representing the ordered bindings produced by the statement suite following the 
'::' Thus ::
is a general expression that can be used anywhere an expression can be used. 
(I'll explain indentation rules).

The "::" expression I'm proposing generalizes capturing suite bindings into an 
ordered sequence of (key,value)
tuples, like an ordered vars().items() limited to the bindings produced in the 
suite following "::"
Thus
items = ::
x = 1
y = [1,2]
def foo():pass

print items => (('x', 1), ('y', [1, 2]), ('foo', ))

Now we can use a :: expression in a where: spec, e.g.

d = dict(items) where:
items = ('added','value') + ::  # note that :: is a unary suite 
operator producing a tuple of tuples
x = 1
y = [1,2]
def foo():pass

where: actually introduces a suite of scoped assignments much like ::  e.g.,
d = {key:value} where: key='x'; value='123' # where is ;-greedy on the same 
line
print d => {'x':123}

or a multi-parameter call
foo(x, y=23, *args, **kw) where:
x = 333; y = 555
args = [44, 55, 66]
kw = dict(::
   z = 'zee'
   class C(object): pass
   c = C()
   del C )

resulting in foo being called like foo(333, 555, 44, 55, 66, z='zee', c=C()) # 
except C was transiently defined


You can also use a :: expression directly, skipping the where: reference 
resolution mechanism, e.g.,

d = dict(::
x = 1
y = [1,2]
def foo():pass)  # closing bracket not opened in :: suite ends the 
suite like a sufficient dedent would

It can also participate as a normal expression anywhere a tuple of tuples could 
go, e.g.

print list(t[0] for t in ::
x = 1
y = [1,2]
def foo():pass)
=> ['x', 'y', 'foo']

Now we can rewrite some examples. Thanks for the inspiration to 
generalize/orthogonalize ;-)

>
>Proposed specifiers are dict, tuple, *, ** and func.
>
>
>-  as dict:
>
>   conversion into a dictionary
>
>   Example:
>
>   d = as dict:
>   doc = "I'm the 'x' property."
>   def fget(self):
>   return self.__x
d = dict(items) where:
items = ::
doc = "I'm the 'x' property."
def fget(self):
return self.__x

Or more concisely

d = dict(::
doc = "I'm the 'x' property."
def fget(self):
return self.__x )

>
>   We would get d = {"doc":"I'm the 'x' property.", "fget":fget}
>
>
>-  as **:
>
>   conversion into keyword-arguments. This comes close in spirit to the
>   original proposal
BTW, this would happen to cover dict alternatively by way of your format
d = dict():
   as **: key=value #etc
>
>   Example:
>
>   x = property():
>   as **:
>   doc = "I'm the 'x' property."
>   def fget(self):
>   return self.__x
>
x = property(**kw) where:
kw = dict(::
doc = "I'm the 'x' property."
def fget(self):
return self.__x)
or
x = property(fget=fget, doc=doc) where:
doc = "I'm the 'x' property."
def fget(self):
return self.__x

>-  as tuple:
>
>   conversion into a tuple. Preserving order.
>
>   Example:
>
>   t = as tuple:
>   doc = "I'm the 'x' property."
>   def fget(self):
>   return self.__x
>   >>> t[1]
>   
"as tuple:" is special sugar for
t = tuple(*v) where:
v = (t[1] for t in ::
doc = "I'm the 'x' property."
def fget(self):
return self.__x )

>
>
>-  as *:
>
>   conversion into an argument tuple. Preserving order.
That's the same as passing values to tuple above
>
>   Example:
>
>   x = property():
>  

Re: pre-PEP: Simple Thunks

2005-04-16 Thread Brian Sabbey
[EMAIL PROTECTED] wrote:
	Keep in mind that most of the problems come from the "space is 
significant" thing, which is IMHO a very good idea, but prevents us from 
putting code in expressions, like :

func( a,b, def callback( x ):
print x
)
	or does it ? maybe this syntax could be made to work ?
Hmm.  I'd like to think that suite-based keywords do make this example 
work.  One just has to let go of the idea that all arguments to a function 
appear inside parentheses.


Comments on the thunks.
	First of all I view code blocks as essential to a language. They are 
very useful for a lot of common programming tasks (like defining callbacks in 
an elegant way) :

button = create_button( "Save changes" ):
do
self.save()
	However it seems your thunks can't take parameters, which to me is a 
big drawback. In ruby a thunk can take parameters. Simple examples :

	field = edit_field( "initial value", onsubmit={ |value| if 
self.validate(value) then do something else alert( "the value is invalid" ) } 
)
	[1,3,4].each { |x| puts x }
Thunks can take parameters:
do value in field = edit_field("initial value"):
if self.validate(value):
something
else:
alert("the value is invalid")
But callbacks are better defined with suite-based keywords:
field = edit_field("initial value"):
def onsubmit(value):
if self.validate(value):
something
else:
alert("the value is invalid")
	This has the advantage that the interface to the thunk (ie. its 
parameters) are right there before your eyes instead of being buried in the 
thunk invocation code inside the edit_field.
In the cases in which one is defining a callback, I agree that it would be 
preferable to have the thunk parameters not buried next to 'do'. 
However, I do not consider thunks a replacement for callbacks.  They are a 
replacement for code in which callbacks could be used, but normally aren't 
because using them would be awkward.  Your 'withfile' example below is a 
good one.  Most people wouldn't bother defining a 'withfile' function, 
they would just call 'open' and 'close' individually.

	So I think it's essential that thunks take parameters and return a 
value (to use them effectively as callbacks).
	What shall distinguish them from a simple alteration to def(): which 
returns the function as a value, and an optional name ? really I don't know, 
but it could be the way they handle closures and share local variables with 
the defining scope. Or it could be that there is no need for two kinds of 
function/blocks and so we can reuse the keyword def() :
Right, defining a function with 'def' is different than defining a thunk 
because thunks share the namespace of the surrounding function, functions 
do not:

x = 1
def f():
x = 2   # <- creates a new x
g(f)
print x # ==> 1
do g():
x = 2
print x # ==> 2 ( assuming 'g' calls the thunk at least once)
	If you wish to modify def(), you could do, without creating any 
keyword :

# standard form
f = def func( params ):
code
# unnamed code block taking params
func = def (params):
code
	Note that the two above are equivalent with regard to the variable 
"func", ie. func contains the defined function. Actually I find def 
funcname() to be bloat, as funcname = def() has the same functionality, but 
is a lot more universal.

# unnamed block taking no params
f = def:
code
I'm confused.  These examples seem to do something different than what a 
'do' statement would do.  They create a function with a new namespace and 
they do not call any "thunk-accepting" function.

***
Comments on the suite-based keywords.
Did you notice that this was basically a generalized HEREDOC syntax ?
I'd say that explicit is better than implicit, hence...
Your syntax is :
do f(a,b):
a block
passes block as the last parameter of f.
I don't like it because it hides stuff.
Yes, it hides stuff.  It doesn't seem to me any worse than what is done 
with 'self' when calling a method though.  Once I got used to 'self' 
appearing automatically as the first parameter to a method, it wasn't a 
big deal for me.

I'd write :
f(a,b,@>,@>):
"""a very
large multi-line
string"""
def (x):
print x
	Here the @> is a symbol (use whatever you like) to indicate 
"placeholder for something which is on the next line".
	Indentation indicates that the following lines are indeed argument 
for the function. The : at the end of the function call is there for 
coherence with the rest of the syntax.
	Notice that, this way, there is no need for a "do" keyword, as the 
code block created by an anonymous def() is no different that the other 
parameter, in this case a multilin

Re: pre-PEP: Simple Thunks

2005-04-16 Thread Brian Sabbey
On Sat, 16 Apr 2005, Ron_Adam wrote:
Thunks are, as far as this PEP is concerned, anonymous functions that
blend into their environment. They can be used in ways similar to code
blocks in Ruby or Smalltalk. One specific use of thunks is as a way to
abstract acquire/release code. Another use is as a complement to
generators.
I'm not familiar with Ruby or Smalltalk.  Could you explain this
without referring to them?
Hopefully my example below is more understandable.  I realize now that I 
should have provided more motivational examples.

def f(thunk):
   before()
   thunk()
   after()
do f():
   stuff()
The above code has the same effect as:
before()
stuff()
after()
You can already do this, this way.
def f(thunk):
... before()
... thunk()
... after()
...
def before():
... print 'before'
...
def after():
... print 'after'
...
def stuff():
... print 'stuff'
...
def morestuff():
... print 'morestuff'
...
f(stuff)
before
stuff
after
f(morestuff)
before
morestuff
after

This works with arguments also.
Yes, much of what thunks do can also be done by passing a function 
argument.  But thunks are different because they share the surrounding 
function's namespace (which inner functions do not), and because they can 
be defined in a more readable way.

Other arguments to 'f' get placed after the thunk:
def f(thunk, a, b):
# a == 27, b == 28
before()
thunk()
after()
do f(27, 28):
stuff()
Can you explain what 'do' does better?
Why is the 'do' form better than just the straight function call?
f(stuff, 27, 28)
The main difference I see is the call to stuff is implied in the
thunk, something I dislike in decorators.  In decorators, it works
that way do to the way the functions get evaluated.  Why is it needed
here?
You're right that, in this case, it would be better to just write 
"f(stuff, 27, 28)".  That example was just an attempt at describing the 
syntax and semantics rather than to provide any sort of motivation.  If 
the thunk contained anything more than a call to 'stuff', though, it would 
not be as easy as passing 'stuff' to 'f'.  For example,

do f(27, 28):
print stuff()
would require one to define and pass a callback function to 'f'.  To me, 
'do' should be used in any situation in which a callback *could* be used, 
but rarely is because doing so would be awkward.  Probably the simplest 
real-world example is opening and closing a file.  Rarely will you see 
code like this:

def with_file(callback, filename):
f = open(filename)
callback(f)
f.close()
def print_file(file):
print file.read()
with_file(print_file, 'file.txt')
For obvious reasons, it usually appears like this:
f = open('file.txt')
print f.read()
f.close()
Normally, though, one wants to do a lot more than just print the file. 
There may be many lines between 'open' and 'close'.  In this case, it is 
easy to introduce a bug, such as returning before calling 'close', or 
re-binding 'f' to a different file (the former bug is avoidable by using 
'try'/'finally', but the latter is not).  It would be nice to be able to 
avoid these types of bugs by abstracting open/close.  Thunks allow you to 
make this abstraction in a way that is more concise and more readable than 
the callback example given above:

do f in with_file('file.txt'):
print f.read()
Thunks are also more useful than callbacks in many cases since they allow 
variables to be rebound:

t = "no file read yet"
do f in with_file('file.txt'):
t = f.read()
Using a callback to do the above example is, in my opinion, more 
difficult:

def with_file(callback, filename):
f = open(filename)
t = callback(f)
f.close()
return t
def my_read(f):
return f.read()
t = with_file(my_read, 'file.txt')
When I see 'do', it reminds me of 'do loops'. That is 'Do' involves
some sort of flow control.  I gather you mean it as do items in a
list, but with the capability to substitute the named function.  Is
this correct?
I used 'do' because that's what ruby uses for something similar.  It can 
be used in a flow control-like way, or as an item-in-a-list way.  For 
example, you could replace 'if' with your own version (not that you would 
want to):

def my_if(thunk, val):
if val:
thunk()
do my_if(a): # same as "if a:"
assert a
(replacing "else" wouldn't be possible without allowing multiple thunks.)
Or you could create your own 'for' (again, NTYWWT):
def my_for(thunk, vals):
for i in vals:
thunk(i)
do i in my_for(range(10)):
print i
-Brian
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Simple Thunks

2005-04-16 Thread Brian Sabbey
Leif K-Brooks wrote:
Brian Sabbey wrote:
Thunk statements contain a new keyword, 'do', as in the example below. The 
body of the thunk is the suite in the 'do' statement; it gets passed to the 
function appearing next to 'do'. The thunk gets inserted as the first 
argument to the function, reminiscent of the way 'self' is inserted as the 
first argument to methods.
It would probably make more sense to pass the thunk as the last argument, not 
as the first. That would make it easier to create functions with optional 
thunks, as in:

def print_nums(start, end, thunk=None):
   for num in xrange(start, end+1):
   if thunk is not None:
   num = thunk(num)
   print num
print_nums(1, 3) # prints 1, 2, 3
do num print_nums(1, 3): # prints 2, 4, 6
   continue num * 2
That seems like a good idea to me.
I suppose it also makes sense to have the thunk last because it appears 
after all the other arguments in the function call.

Because thunks blend into their environment, a thunk cannot be used after 
its surrounding 'do' statement has finished
Why? Ordinary functions don't have that restriction:
def foo():
... x = 1
... def bar():
... return x
... return bar
...
foo()()
1
Thunks, as I implemented them, don't create a closure.  I believe that 
creating a closure will require a performance penalty.  Since one use of 
thunks is in loops, it seems that their performance may often be 
important.

I believe that saving the thunk and calling it a later time is a somewhat 
hackish way to use thunks.  Explicitly defining a function (perhaps with a 
suite-based keyword :) ) seems to me to be a more readable way to go.

But, yes, it is an arbitrary restriction.  If it turns out that 
performance isn't really affected by creating a closure, or that 
performance doesn't matter as much as I think it does, then this 
restriction could be lifted.

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


Re:

2005-04-16 Thread Jaime Wyant
You need to look at the re module.
 
>>> import re
>>> dir(re)
>>> re.split('A|a', 'A big Fat CAt')
['', ' big F', 't C', 't']

Then google around for a regular expression tutorial...

jw


On 4/16/05, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> All,
> 
> I have been going through the manuals and not having much luck with the
> following code.  This is basically an issue of giving 'split' multiple
> patterns to split a string.  If it had an ignore case switch, the problem
> would be solved.  Instead, I have to code the following, which works fine
> for a single byte string.  What can I do when I want to look for strings?
> 
> >>> test = 'A big Fat CAt'
> >>> A = test.split('A')
> >>> print A
> ['', ' big Fat C', 't']
> >>> a = []
> >>> for x in xrange(len(A)):
> ... tmp = A[x].split('a')
> ... for y in xrange(len(tmp)):
> ... a.append(tmp[y])
> ...
> >>>
> >>> a
> ['', ' big F', 't C', 't']
> 
> It is odd about the help files, after I figure out how to do something, the
> help makes sense.  Before hand is another story...  Are there any others out
> there that share this misery?
> 
> thanks,
> Michael
> ___
> The information contained in this message and any attachment may be
> proprietary, confidential, and privileged or subject to the work
> product doctrine and thus protected from disclosure.  If the reader
> of this message is not the intended recipient, or an employee or
> agent responsible for delivering this message to the intended
> recipient, you are hereby notified that any dissemination,
> distribution or copying of this communication is strictly prohibited.
> If you have received this communication in error, please notify me
> immediately by replying to this message and deleting it and all
> copies and backups thereof.  Thank you.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: whitespace , comment stripper, and EOL converter

2005-04-16 Thread qwweeeit
Hi,

Importing a text file from another o.s. is not a problem : I convert
it immediately using the powerful shell functions of Linux (and Unix).

I thank you for the explanation about classes, but I am rather dumb
and
by now I resolved all my problems without them...
Speaking of problems..., I have yet an error in parsing for literal
strings,
when there is more than one literal string by source line.

Perhaps it's time to use classes...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing colors in python

2005-04-16 Thread Claudio Grondi
The readline module (used e.g. in IPython)
http://sourceforge.net/project/showfiles.php?group_id=82407
provides the Console.py
script and in my own version of it, the (extended)
Console() class supports any ANSI escape
sequences of the form ESC[#m and ESC[#,#m ,
making it possible to set any by console supported
text and background colors.
http://people.freenet.de/AiTI-IT/Python/Console.py

Replace the Console.py of the readline
module with my extended version and run
it as main script to see the coloured output
looking into the code to see how it comes.

Claudio
http://www.python.org/moin/ClaudioGrondi


"GujuBoy" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> i have a ansi.py file that i use in LINUX to change the text color to
> STDOUT when i use the "print" function...but when i move this ansi.py
> file over the windows...it does not work
>
> is there a version of ansi.py i can use for windows/linux
>
> please help
>


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


Re: A little request about spam

2005-04-16 Thread Mike Meyer
Ivan Van Laningham <[EMAIL PROTECTED]> writes:
> Of course I wouldn't base decisions _only_ on whether or not [PYTHON]
> appears in the subject.  But I ordinarily do base decisions on the whole
> subject line, and I think that's perfectly reasonable.  There's nothing
> else to go on without opening the message, and for HTML-based mail
> there's no surer way to let spammers know they've found a live email
> addres than to open it.  You know that.

No, I don't. My mail reader has a separate "decode" step. I can open
HTML email, and see the HTML. Actually, I usually see the ascii
version of the HTML followed by the HTML. If I want to see the HTML, I
have to tell the reader to "decode" the mail. Then it renders the HTML.

Further, I have the HTML renderer set to *not* fetch inline objects
unless/until I click on them. So even rendering the HTML won't tell
spammers anything.

In short - your mail reader needs an upgrade.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's use in RAD

2005-04-16 Thread Jarek Zgoda
Ross Cowie napisał(a):
I am currenly a second year university student and was wondering if you 
could help me ut. As part of a project i have decided to write about 
python, i am not having very much luck with regards to finding 
infrmation on pythons use in Rapid Application Development, and was 
wondering of you could highlight some of the features that make it 
suitable for RAD. Like the use of dinamic binding.
I develop applications in python on AS/400 really fast -- that is, 
rapidly ("five to eight" times faster comparing to Java, even more when 
comparing to RPG). Dynamic & strong typing, comprehensive standard 
library and clean syntax makes Python ideal for RAD event on such 
obscure platforms as i5 (formerly known as iSeries, formerly known as 
AS/400).

For me, at least.
--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Steven Bethard
Shane Hathaway wrote:
I like this PEP a lot, but your concern is valid.  Maybe Brian could
modify the PEP slightly to disambiguate.  How about using an ellipsis in
the argument list to signify suite-based keywords?  Examples:
f(...):
x = 1
class C(object):
   x = property(...):
  doc = "I'm the 'x' property."
  def fget(self):
 return self.__x
  def fset(self, value):
 self.__x = value
  def fdel(self):
 del self.__x
d = dict(...):
a = 1
b = 2
I also like the ellipsis idea much better than the original proposal. 
While I figured out what the original syntax meant after half a minute 
of staring at it (unlike the thunk proposal which I still can't decode), 
I couldn't help but feel that I'd like a visual cue that arguments had 
been omitted.  Seeing
f():
gives me only ':' as a tiny clue that arguments have been omitted.  And 
':' is used in all Python suites, so it doesn't have a good intuition 
associated with it.  Using ellipsis or something similar to indicate 
that keyword arguments have been omitted would make this much easier for 
me to read.

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Kay Schluehr
Nicolas Fleury wrote:

> Shane Hathaway wrote:
> > I like this PEP a lot, but your concern is valid.  Maybe Brian
could
> > modify the PEP slightly to disambiguate.  How about using an
ellipsis in
> > the argument list to signify suite-based keywords?  Examples:
> >
> > f(...):
> > x = 1
> >
> > class C(object):
> >x = property(...):
> >   doc = "I'm the 'x' property."
> >   def fget(self):
> >  return self.__x
> >   def fset(self, value):
> >  self.__x = value
> >   def fdel(self):
> >  del self.__x
> >
> > d = dict(...):
> > a = 1
> > b = 2
> >
> > Using an ellipsis in a statement that would begin a different kind
of
> > block is illegal and generates a syntax error.  Note that this
usage
> > seems to fit well with the definition of "ellipsis".
> >
> > http://dictionary.reference.com/search?q=ellipsis
> >
> > Shane
>
> I like the ellipsis syntax a lot, it greatly helps the proposal IMHO.
>
> Regards,
> Nicolas

I think the usage of the block is still limited in Shawns answer. Kents
objection can be evaded but Reinhold Birkenfelds remains valid.

The statement

f(...):
  x = 1

is still not an expression like f(x=1) is. I think one has to mark
somehow the scope of the suite-based keywords.

In the examples below we can identifiy the expression belonging to f
without ambiguities and restrictions.

f(y=0,..)
   .. x = 1

if f(y=2,..) == 1:
   .. x = 5
  def g(a):
  a**2-1
   return 8

Note that the colon after f has vanished as expected for a call.

Ciao,
Kay

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


Re: pythonic use of properties?

2005-04-16 Thread Michael Spencer
Marcus Goldfish wrote:
So what do you consider when making this decision
Python style tends away from validating what doesn't need to be validated.  The 
argument seems to be that the additional validating code comes at the price of 
legibility, and perhaps flexibility.

It's common in Python to use public attributes - even though an irresponsible 
user could set an object to a harmful or meaningless state.

Instead, the Python mantra is that it is 'better to ask forgiveness than 
permission', i.e., to handle exceptions gracefully rather than trying to avoid them.

One form of validation that is particularly discouraged in Python is 
type-checking.
That said, of course there are cases where data must be validated.  For data 
stored in one type, and used in many contexts - I would validate where stored. 
If the reverse, then validate at the point it is used.  In the likely case of 
'somewhere in between these extremes', personal taste and project conventions.


and do these factors differ between python and C#/Java?
I have rarely used C#, and never Java.
C#'s strongly typed method signatures imply a contract to act properly on 
objects passed to the method.  Given this, it seems sensible to me to include 
data validation in the source object.

Python's lack of type-checking of callable arguments invites the use of 'duck 
types'.  On the margin, I think, this argues for putting data validation at the 
point where the data is used, rather than when it is stored.

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Brian Sabbey
Bengt Richter wrote:
On Fri, 15 Apr 2005 19:32:02 -0700, James Stroud <[EMAIL PROTECTED]> wrote:
I_vote_yes(James):
  I_understand_what_it_does = True
  Makes_code_formatting_way_more_managable_in_tough_cases = True
  Makes_code_way_more_readable = True
  To_cool = True
On Friday 15 April 2005 04:45 pm, Brian Sabbey wrote:
Here is a pre-PEP for what I call "suite-based keyword arguments". The
mechanism described here is intended to act as a complement to thunks.
Please let me know what you think.
Kind of cool. If we had full lambdas aka as anonymous defs (def foo(...) with 
foo left out ;-)
would this be concise sugar for the equivalents shown below your examples?
(The rule for parsing the suite of an anonymous def is that the left column of 
the first non-space
character of the first suite statement following the def(): becomes the suite 
indent reference,
and a dedent to the left of that ends the def(): or a closing bracket not 
opened in the def(): suite
also ends it. Otherwise it is standard suite indentation)
Suite-Based Keyword Arguments
-
Passing complicated arguments to functions is currently awkward in Python.
For example, the typical way to define a class property winds up polluting
the class's namespace with the property's get/set methods.  By allowing
keyword arguments to be defined in a suite following a function call,
complicated arguments can be passed in a cleaner, easier way.
Examples

Using suite-based keyword arguments, the code
f(x = 1)
is equivalent to
f():
x = 1
  f(**def():
x = 1
return vars())
Yes, it seems it would just be sugar for full lambdas.  Although, in this 
example and the others, wouldn't you have to actually call the anonymous 
function?

f(**(def():
x = 1
return vars())())
Otherwise it seems like you are trying to pass a function, not the 
keywords the function returns.

One could, of course, also do the same with a named function:
def no_longer_anonymous():
x = 1
return vars()
f(**no_longer_anonymous())
-Brian
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Brian Sabbey
Reinhold Birkenfeld wrote:
Brian Sabbey wrote:
Here is a pre-PEP for what I call "suite-based keyword arguments". The
mechanism described here is intended to act as a complement to thunks.
Please let me know what you think.
Suite-Based Keyword Arguments
-
Passing complicated arguments to functions is currently awkward in Python.
For example, the typical way to define a class property winds up polluting
the class's namespace with the property's get/set methods.  By allowing
keyword arguments to be defined in a suite following a function call,
complicated arguments can be passed in a cleaner, easier way.
Examples

Using suite-based keyword arguments, the code
f(x = 1)
is equivalent to
f():
x = 1
Pretty cool, but it interferes with current suites.
How would you write
if f(x=1):
   print "yes"
using suite-based keyword args?
Reinhold
You wouldn't be able to use suite keywords in that situation.  Also, one 
would not be able to use suite keywords when there is more than one 
function call on the same line:

y = f()*g():
x = 1# ??  not allowed
There is only so much suites can do.  Cases in which you want to do both 
are probably far enough between that it seems acceptable to me to require 
two suites:

t = f():
 x = 1
if t:
 y = 1
In general, I think that anything more than just a function call with an 
optional assignment should be disallowed:

y = [f()]:  #  ? probably shouldn't be allowed
x = 1
-Brian
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Brian Sabbey
Shane Hathaway wrote:
Kent Johnson wrote:
Brian Sabbey wrote:
Using suite-based keyword arguments, the code
f(x = 1)
is equivalent to
f():
   x = 1

ISTM the syntax is ambiguous. How do you interpret
if f():
  x = 1
?
Is a suite alllowed only when a block could not be introduced in the
current syntax?
I like this PEP a lot, but your concern is valid.  Maybe Brian could
modify the PEP slightly to disambiguate.  How about using an ellipsis in
the argument list to signify suite-based keywords?  Examples:
f(...):
   x = 1
class C(object):
  x = property(...):
 doc = "I'm the 'x' property."
 def fget(self):
return self.__x
 def fset(self, value):
self.__x = value
 def fdel(self):
del self.__x
d = dict(...):
   a = 1
   b = 2
Using an ellipsis in a statement that would begin a different kind of
block is illegal and generates a syntax error.  Note that this usage
seems to fit well with the definition of "ellipsis".
http://dictionary.reference.com/search?q=ellipsis
Shane
Yes, my description of the syntax was ambiguous.  To clarify, I intended 
the syntax to be backwardly compatible.  That is, one would not be able to 
use a suite to define keywords if there already exists a suite for other 
reasons.  So, one would not be able to use a suite to pass keywords to 'f' 
in this situation:

if f():
 x = 1
This code should behave exactly as it does now.
I agree that the ellipsis idea probably makes the code more readable, and 
it may be a good idea to have them for that reason.  However, ellipses are 
not necessary as a way to disambiguate the syntax; all statements 
containing suites currently begin with a keyword, and keyword suites would 
not.

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


Re: pydoc preference for triple double over triple single quotes -- anyreason?

2005-04-16 Thread Kent Johnson
Brian van den Broek wrote:
Hi all,
I'm posting partly so my problem and solution might be more easily found 
by google, and partly out of mere curiosity.

I've just spent a frustrating bit of time figuring out why pydoc didn't 
extract a description from my module docstrings. Even though I had a 
well formed docstring (one line, followed by a blank line, followed by 
the rest of the docstring), when I ran Module docs, my modules showed up 
as having "no description". ("Module docs" referring to the shortcut 
installed on Windows that launches the pydoc server.)
?? It works for me with triple-single quoted strings...from a quick look it appears that pydoc uses 
inspect which looks at the __doc__ attribute; do your modules have __doc__ attributes?

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


Software Development Jobs

2005-04-16 Thread Solido Design Automation Jobs
Software Developer
--

Responsibilities:
You will be a key member of a project team to develop and deliver core
modules of a breakthrough product in a venture capital backed start-up
company in the electronic design automation (EDA) industry. You will
be responsible for defining, designing and implementing complex
software. You will be participating in the decision-making for product
features and the software life-cycle. You will be expected to take a
greater leadership role as the company grows.

Qualification Musts:
-BSCS, BSEE or Masters in Computer Science/Electrical Engineering 
-Software development experience on Linux, HP, or Sun 
-Experience in object oriented (OO) software design and implementation
-Excellent problem solving skills 
-Strong leadership and written/verbal communication skills; team
player

Qualification Pluses:
-Languages: Python, C/C++, Matlab, Cadence SKILL 
-Experience setting up and working within a development methodology
and environment for commercial Linux/HP/Sun software
-Experience in agile software development methodologies 
-Software testing methodology and tools, and quality assurance (QA) 
-Understanding of microelectronic circuits 
-Experience with SPICE-like simulator interfaces 
-Experience with Cadence, Mentor and/or Synopsys / Avanti analog EDA
tools
-GUI development experience 

Job Location:
Saskatoon, Saskatchewan, Canada.

Deadline:
ASAP

To apply:
Email resume to [EMAIL PROTECTED] , subject: PNG Software
Developer Application
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python 2.3.2 for PalmOS available

2005-04-16 Thread Erik Max Francis
Klaus Alexander Seistrup wrote:
However, MLPY doesn't seem to work on my Tungsten T3 (PalmOS 5.2.1).
The .prc installs without any problems, and I can start the Python
interpreter, but nothing happens if I ring in a Python expression and
press return -- the prompt just "hangs" and never returns.
It worked on my Treo 650, although you quickly ran out of space in the 
input text area (if you typed too many characters it would beep and 
prevent you from typing anymore).

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  It comes from inside, and that's what I consider to be soul music.
  -- Sade Adu
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python 2.3.2 for PalmOS available

2005-04-16 Thread bryce . moore
Lucio,

Just tried to install it on my sony clie PEG-S360.  When I try to run
it I get:
Fatal Alert
pythonrun.c, Line: 1483,
Py_Initialize: can't init ints

Aside from my clie being significantly under-powered, I don't know what
else could be wrong.

What version of the Palm OS does this support?

Good luck with this.  I could use a more up-to-date python than Pippy
(http://pippy.sourceforge.net/) offers.

I didn't know where else to post / email this.

bryce

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


Re: pre-PEP: Simple Thunks

2005-04-16 Thread Ron_Adam
On Fri, 15 Apr 2005 16:44:58 -0700, Brian Sabbey
<[EMAIL PROTECTED]> wrote:

>
>Simple Thunks
>-
>
>Thunks are, as far as this PEP is concerned, anonymous functions that 
>blend into their environment. They can be used in ways similar to code 
>blocks in Ruby or Smalltalk. One specific use of thunks is as a way to 
>abstract acquire/release code. Another use is as a complement to 
>generators.

I'm not familiar with Ruby or Smalltalk.  Could you explain this
without referring to them?


>A Set of Examples
>=
>
>Thunk statements contain a new keyword, 'do', as in the example below. The 
>body of the thunk is the suite in the 'do' statement; it gets passed to 
>the function appearing next to 'do'. The thunk gets inserted as the first 
>argument to the function, reminiscent of the way 'self' is inserted as the 
>first argument to methods.
>
>def f(thunk):
>before()
>thunk()
>after()
>
>do f():
>stuff()
>
>The above code has the same effect as:
>
>before()
>stuff()
>after()

You can already do this, this way.

>>> def f(thunk):
... before()
... thunk()
... after()
...
>>> def before():
... print 'before'
...
>>> def after():
... print 'after'
...
>>> def stuff():
... print 'stuff'
...
>>> def morestuff():
... print 'morestuff'
...
>>> f(stuff)
before
stuff
after
>>> f(morestuff)
before
morestuff
after
>>>

This works with arguments also.


>Other arguments to 'f' get placed after the thunk:
>
>def f(thunk, a, b):
> # a == 27, b == 28
> before()
> thunk()
> after()
>
>do f(27, 28):
> stuff()

Can you explain what 'do' does better?

Why is the 'do' form better than just the straight function call?

f(stuff, 27, 28)

The main difference I see is the call to stuff is implied in the
thunk, something I dislike in decorators.  In decorators, it works
that way do to the way the functions get evaluated.  Why is it needed
here?

When I see 'do', it reminds me of 'do loops'. That is 'Do' involves
some sort of flow control.  I gather you mean it as do items in a
list, but with the capability to substitute the named function.  Is
this correct?

Cheers,
Ron

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


Re: pydoc preference for triple double over triple single quotes -- any reason?

2005-04-16 Thread Thomas Rast
Brian van den Broek <[EMAIL PROTECTED]> writes:

> It turns out that I was using '''triple single quotes''' and pydoc
> only pulls a description out from module docstrings that are formatted
> in """triple double quotes""". I've poked about with google, and
> cannot find any explanation of why pydoc should treat the two cases
> differently. Anyone have an idea?

Maybe because some editors, e.g. Emacs, do not (cannot) properly
handle triple quotes in syntax analysis and highlighting.  Instead,
the quotes are treated as ordinary quotes, which breaks

  '''This doesn't work'''

but not

  """This'll work"""

due to the apostrophe.  pydoc then probably decided to follow PEP 257
which says

  For consistency, always use """triple double quotes""" around
  docstrings.
  [http://www.python.org/peps/pep-0257.html]

- Thomas

-- 
If you want to reply by mail, substitute my first and last name for
'foo' and 'bar', respectively, and remove '.invalid'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Nicolas Fleury
Shane Hathaway wrote:
I like this PEP a lot, but your concern is valid.  Maybe Brian could
modify the PEP slightly to disambiguate.  How about using an ellipsis in
the argument list to signify suite-based keywords?  Examples:
f(...):
x = 1
class C(object):
   x = property(...):
  doc = "I'm the 'x' property."
  def fget(self):
 return self.__x
  def fset(self, value):
 self.__x = value
  def fdel(self):
 del self.__x
d = dict(...):
a = 1
b = 2
Using an ellipsis in a statement that would begin a different kind of
block is illegal and generates a syntax error.  Note that this usage
seems to fit well with the definition of "ellipsis".
http://dictionary.reference.com/search?q=ellipsis
Shane
I like the ellipsis syntax a lot, it greatly helps the proposal IMHO.
Regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: whitespace , comment stripper, and EOL converter

2005-04-16 Thread MrJean1

Great tool, indeed!  But doc strings stay in the source text.

If you do need to remove doc strings as well, add the following into
the __call__ method.

...  # kill doc strings
...  if not self.docstrings:
...  if toktype == tokenize.STRING and len(toktext) >= 6:
...  t = toktext.lstrip('rRuU')
...  if ((t.startswith("'''") and t.endswith("'''")) or
...  (t.startswith('"""') and t.endswith('"""'))):
...  return

as shown in the original post below.  Also, set self.docstrings in the
format method, similar to self.comments as shown below in lines
starting with '...'.


/Jean Brouwers



M.E.Farmer wrote:
> qwweeeit wrote:
> > Thanks! If you answer to my posts one more time I could  consider
you
> as
> > my tutor...
> >
> > It was strange to have found a bug...! In any case I will not go
> deeper
> > into the matter, because for me it's enough your explanatiom.
> > I corrected the problem by hand removing the tokens spanning
multiple
> lines
> > (there were only 8 cases...).
> >
> > Instead I haven't understood your hint about comments...
> > I succeded  in realizing a python script which removes comments.
> >
> > Here it. is (in all its cumbersome and criptic appearence!...):
> >
> > # removeCommentsTok.py
> > import tokenize
> > Input = "pippo1"
> > Output = "pippo2"
> > f = open(Input)
> > fOut=open(Output,"w")
> >
> > nLastLine=0
> > for i in tokenize.generate_tokens(f.readline):
> > .   if i[0]==52 and nLastLine != (i[2])[0]:
> > .   .   fOut.write((i[4].replace(i[1],'')).rstrip()+'\n')
> > .   .   nLastLine=(i[2])[0]
> > .   elif i[0]==4 and nLastLine != (i[2])[0]:
> > .   .   fOut.write((i[4]))
> > .   .   nLastLine=(i[2])[0]
> > f.close()
> > fOut.close()
> >
> > Some explanations for the guys like me...:
> > - 52 and 4 are the arbitrary codes for comments and NEWLINE
> respectively
> > - the comment removing is obtained by clearing the comment (i[1])
in
> the
> >   input line (i[4])
> > - I also right trimmed the line to get rid off the remaining
blanks.
> Tokenizer sends multiline strings and comments as a single token.
>
>
##
> # python comment and whitespace stripper :)
>
##
>
> import keyword, os, sys, traceback
> import StringIO
> import token, tokenize
> __credits__ = 'just another tool that I needed'
> __version__ = '.7'
> __author__ = 'M.E.Farmer'
> __date__ =  'Jan 15 2005, Oct 24 2004'
>
>
##
>
> class Stripper:
> """python comment and whitespace stripper :)
> """
> def __init__(self, raw):
> self.raw = raw
>
...   def format(self, out=sys.stdout, comments=0, docstrings=0,
spaces=1,
> untabify=1, eol='unix'):
> ''' strip comments, strip extra whitespace,
> convert EOL's from Python code.
> '''
> # Store line offsets in self.lines
> self.lines = [0, 0]
> pos = 0
> # Strips the first blank line if 1
> self.lasttoken = 1
> self.temp = StringIO.StringIO()
> self.spaces = spaces
> self.comments = comments
...   self.docstrings = docstrings
>
> if untabify:
>self.raw = self.raw.expandtabs()
> self.raw = self.raw.rstrip()+' '
> self.out = out
>
> self.raw = self.raw.replace('\r\n', '\n')
> self.raw = self.raw.replace('\r', '\n')
> self.lineend = '\n'
>
> # Gather lines
> while 1:
> pos = self.raw.find(self.lineend, pos) + 1
> if not pos: break
> self.lines.append(pos)
>
> self.lines.append(len(self.raw))
> # Wrap text in a filelike object
> self.pos = 0
>
> text = StringIO.StringIO(self.raw)
>
> # Parse the source.
> ## Tokenize calls the __call__
> ## function for each token till done.
> try:
> tokenize.tokenize(text.readline, self)
> except tokenize.TokenError, ex:
> traceback.print_exc()
>
> # Ok now we write it to a file
> # but we also need to clean the whitespace
> # between the lines and at the ends.
> self.temp.seek(0)
>
> # Mac CR
> if eol == 'mac':
>self.lineend = '\r'
> # Windows CR LF
> elif eol == 'win':
>self.lineend = '\r\n'
> # Unix LF
> else:
>self.lineend = '\n'
>
> for line in self.temp.readlines():
> if spaces == -1:
> self.out.write(line.rstrip()+self.lineend)
> else:
> if not line.isspace():
> self.lasttoken=0
> self.out.write(line.rstrip()+self.lineend)
> else:
> self.lasttoken+=1
> if self.lasttok

pydoc preference for triple double over triple single quotes -- any reason?

2005-04-16 Thread Brian van den Broek
Hi all,
I'm posting partly so my problem and solution might be more easily 
found by google, and partly out of mere curiosity.

I've just spent a frustrating bit of time figuring out why pydoc 
didn't extract a description from my module docstrings. Even though I 
had a well formed docstring (one line, followed by a blank line, 
followed by the rest of the docstring), when I ran Module docs, my 
modules showed up as having "no description". ("Module docs" referring 
to the shortcut installed on Windows that launches the pydoc server.)

It turns out that I was using '''triple single quotes''' and pydoc 
only pulls a description out from module docstrings that are formatted 
in """triple double quotes""". I've poked about with google, and 
cannot find any explanation of why pydoc should treat the two cases 
differently. Anyone have an idea?

I do see that both  -- Style 
Guide for Python Code and  
-- Docstring Conventions suggest triple double, so I guess it is my 
fault. But still, those PEP's have the tone of suggestions, and since 
the two quoting schemes are semantically equivalent . . .

I do prefer the look of triple-single, but oh well. My attempts to 
google for an answer didn't come up with anything, so perhaps this 
post will help someone else, if nothing else :-)

Best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: IPython - problem with using US international keyboard input scheme on W2K

2005-04-16 Thread Thomas Heller
"Gary Bishop" <[EMAIL PROTECTED]> writes:

> Fernando Perez <[EMAIL PROTECTED]> wrote:
>> Claudio Grondi wrote:
>
>> > Considering what I found in the ipython mailing archives
>> > and the fact, that after the fix with displaying colors on
>> > bright backgrounds Gary had no time yet to get in touch
>> > with me about the code I have sent him, I suppose, that
>> > there will be no new releases addressing this problem
>> > soon, right?
>
> Folks, the code is OPEN SOURCE! It is right there at
> SourceForge. Anyone, anywhere, at any time is free to hack it,
> redistribute it, or ignore it.
>
> It works FINE FOR ME as it is. Furthermore, I know NOTHING about
> localization. Someone who NEEDS LOCALIZATION should FIX IT in a
> general way.
>
> Make your own version. Create a SourceForge project for it and you can
> be the developer. I wouldn't even care if you removed my name from it.
>
> I've received a patch or two for specific keyboards but I have no way
> to test them and no time or inclination to fool with it.
>
> The bottom line is, I write code for my own use. If others benefit
> that is great. If it doesn't do what you want, make your own
> version. If you want to distribute a new version, go for it.

Maybe it would make sense then to maintain the readline code in the ctypes
CVS repository, since it requires ctypes anyway?

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


Re: whitespace , comment stripper, and EOL converter

2005-04-16 Thread M.E.Farmer
Glad you are making progress ;)

>I give you a brief example of the xref output (taken from your >code,
>also if the line numbers don't match, because I modified >your code,
>not beeing interested in eof's other than Linux).

What happens when you try to analyze a script from a diffrent os ? It
usually looks like a skewed mess, that is why I have added EOL
conversion so it is painless for you to convert to your eol of choice.
The code I posted consist of a class and a Main function.
The class has three methods.
 __init__ is called by Python when you create an instance of the class
Stripper.  All __init__ does here is just set a class variable self.raw
.
format is called explicitly with a few arguments to start the
tokenizer.
__call__ is special it is not easy to grasp how this even works.. at
first.
In Python when you treat an instance like a function, Python invokes
the __call__method of that instance if present and if it is callable().
example:
 try:
tokenize.tokenize(text.readline, self)
except tokenize.TokenError, ex:
traceback.print_exc()
The snippet above is from the Stripper class.
Notice that tokenize.tokenize is being feed a reference to self ( if
this code is running self is an instance of Stripper ).
tokenize.tokenize is really a hidden loop.
Each token generated is sent to self as five parts toktype, toktext,
(startrow,startcol), (endrow,endcol), and line. Self is callable and
has a __call__  method so tokenize sends really sends the five part
info to __call__ for every token.
If this was obvious then ignore it ;)

M.E.Farmer

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


Re: new to mac OS10

2005-04-16 Thread Kevin Walzer
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
It's *not* a good idea to delete Apple's system Python. You will
probably need to reinstall the OS.
In addition to the mailing list that someone else posted (which is a
great resource!), here's a good site to check out:
http://pythonmac.org/
The site maintainer, Bob Ippolito, is one of the main developers of
Python on the Mac and maintains a lot of packages. This site also
includes lots of links to information.
Hope that helps,
Kevin
Thomas Nelson wrote:
| The main thing I would like is to be able to use tkinter with python on
| my mac.  will the command-line-style source allow this?  Does it come
| with IDLE?  How is the fink version different from the source i can
| download at python.org?  Here's the result of the requested commands on
| my Terminal.  It would appear that these links are broken, as
| Python.framework no longer exists.  Sorry to be so much trouble,
|
| THN
|
|
|
| Welcome to Darwin!
| ~ $ ls -all /usr/bin/python*
| lrwxr-xr-x  1 root  wheel9 20 Jun  2004 /usr/bin/python -> python2.3
| lrwxr-xr-x  1 root  wheel   72 20 Jun  2004 /usr/bin/python2.3 ->
| ../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python
| lrwxr-xr-x  1 root  wheel   10 20 Jun  2004 /usr/bin/pythonw -> pythonw2.3
| -rwxr-xr-x  1 root  wheel  122  8 Jun  2003 /usr/bin/pythonw2.3
| ~ $ ls /System/Library/Framework/Python.framework
| ls: /System/Library/Framework/Python.framework: No such file or directory
| ~ $ cd /System/Library/Framework/Python.framwork
| -bash: cd: /System/Library/Framework/Python.framwork: No such file or
| directory
| ~ $
|
|
| Jorl Shefner wrote:
|
|> If you simply want the latest python to run from the command line, then
|> compiling the source code works fine on the mac.  I just installed
|> 2.4.1 on Os 10.3.8 last week without any problems.
|>
|> http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz
|>
|> "./configure"
|> "make"
|> "make install"
|>
|> J.S.
|>
- --
Cheers,
Kevin Walzer, PhD
WordTech Software--Open Source Applications and Packages for OS X
http://www.wordtech-software.com
http://www.smallbizmac.com
http://www.kevin-walzer.com
mailto:[EMAIL PROTECTED]
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.4 (Darwin)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
iD8DBQFCYVSkJmdQs+6YVcoRAj2IAJ4/Pv0yJhs4flLOk1JgEHcUbNrJPwCeMeS9
ue7gNcVE8Kluw7LplS1bFGs=
=uqOO
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: XML parsing per record

2005-04-16 Thread Fredrik Lundh
Kent Johnson wrote:
So I would like to parse a XML file one record at a time and then be able
to store the information in another object.
You might be interested in this recipe using ElementTree:
http://online.effbot.org/2004_12_01_archive.htm#element-generator
if you have ElementTree 1.2.5 or later, the "iterparse" function provides a
more efficient implementation of that pattern:
   http://effbot.org/zone/element-iterparse.htm
the cElementTree implemention of "iterparse" is a lot faster than SAX; see
the second table under
   http://effbot.org/zone/celementtree.htm#benchmarks
for some figures.

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


Re: unicode "em space" in regex

2005-04-16 Thread "Martin v. LÃwis"
Xah Lee wrote:
> how to represent the unicode "em space" in regex?

You will have to pass a Unicode literal as the regular expression,
e.g.

 fracture=re.split(u'\u2003*\\|\u2003*',myline,re.U)

Notice that, in raw Unicode literals, you can still use \u to
escape characters, e.g.

 fracture=re.split(ur'\u2003*\|\u2003*',myline,re.U)

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


Re: Dr Dobbs "with" keyword

2005-04-16 Thread Giovanni Bajo
Neil Hodgson wrote:

>In the March 2005 issue of Dr Dobbs Journal there is an article
> "Resource Management in Python" by Oliver Schoenborn. One paragraph
> (first new paragraph, page 56) starts "Starting with Python 2.4, a new
> type of expression lets you use the keyword /with/". It continues,
> mentioning PEP 310 (Reliable Acquisition/Release Pairs) which is at
> "Draft" status and unlikely to be accepted with the keyword "with" as
> Guido wants to use that for another purpose.

Whatever keyword is chosen, I hope PEP 310 eventually hit Python, I have been
awaiting it for a long time. I would also like to have a builtin resource()
like this:

def resource(enter_call, exit_call):
   class Res(object):
  __enter__ = lambda self: enter_call()
  __exit__ = lambda self: exit_call()
   return Res()

with resource(self.mutex.lock, self.mutex.unlock):
pass

Either that, or "with" could call adapt() implicitly so I can register my
conversion functions.
-- 
Giovanni Bajo


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


Re:

2005-04-16 Thread tiissa
[EMAIL PROTECTED] wrote:
I have been going through the manuals and not having much luck with the
following code.  This is basically an issue of giving 'split' multiple
patterns to split a string.  If it had an ignore case switch, the problem
would be solved.  Instead, I have to code the following, which works fine
for a single byte string.  What can I do when I want to look for strings?
As far as I know there is no such switch.
If you can't convert your string in, say, lowercase, before splitting, 
you may have to use the re module:

In [1]: test = 'A big Fat CAt'
In [2]: import re
In [3]: A=re.compile('a', re.IGNORECASE)
In [4]: A.split(test)
Out[4]: ['', ' big F', 't C', 't']

test = 'A big Fat CAt'
A = test.split('A')
print A
['', ' big Fat C', 't']
a = []
for x in xrange(len(A)):
... tmp = A[x].split('a')
... for y in xrange(len(tmp)):
... a.append(tmp[y])
...
a
['', ' big F', 't C', 't']
As a side note, reduce is great in such situations:
In [5]: reduce(list.__add__,[t.split('a') for t in test.split('A')],[])
Out[5]: ['', ' big F', 't C', 't']
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Kay Schluehr
The idea is interesting but not unambigously realizable. Maybe one
should introduce some extra syntax for disambiguation and thereby
generalize the proposal.

as :
   # list of definitions and assignments

Proposed specifiers are dict, tuple, *, ** and func.


-  as dict:

   conversion into a dictionary

   Example:

   d = as dict:
   doc = "I'm the 'x' property."
   def fget(self):
   return self.__x

   We would get d = {"doc":"I'm the 'x' property.", "fget":fget}


-  as **:

   conversion into keyword-arguments. This comes close in spirit to the
   original proposal

   Example:

   x = property():
   as **:
   doc = "I'm the 'x' property."
   def fget(self):
   return self.__x

-  as tuple:

   conversion into a tuple. Preserving order.

   Example:

   t = as tuple:
   doc = "I'm the 'x' property."
   def fget(self):
   return self.__x
   >>> t[1]
   


-  as *:

   conversion into an argument tuple. Preserving order.

   Example:

   x = property():
   as *:
   def get_x():
   return self.__x
   def set_x(value):
   self.__x = value
   del_x = None
   doc   = "I'm the 'x' property."



-  as func(*args,**kw):

   Anoymus functions. Replacement for lambda. Support for
   arbirtray statements?

   Examples:

   p = as func(x,y): x+y
   p(1,2)

   i,j = 3,4
   if (as func(x,y): x+y) (i,j) > 10:
  print True


Ciao,
Kay

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


Re:

2005-04-16 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
All,
I have been going through the manuals and not having much luck with the
following code.  This is basically an issue of giving 'split' multiple
patterns to split a string.  If it had an ignore case switch, the problem
would be solved.  Instead, I have to code the following, which works fine
for a single byte string.  What can I do when I want to look for strings?
Use re.split() instead of str.split(). It uses any regex as the split 
string:
 >>> import re
 >>> test = 'A big Fat CAt'
 >>> re.split('[aA]', test)
['', ' big F', 't C', 't']
Kent
test = 'A big Fat CAt'
A = test.split('A')
print A
['', ' big Fat C', 't']
a = []
for x in xrange(len(A)):
... tmp = A[x].split('a')
... for y in xrange(len(tmp)):
... a.append(tmp[y])
...
a
['', ' big F', 't C', 't']
--
http://mail.python.org/mailman/listinfo/python-list


Re: XML parsing per record

2005-04-16 Thread Kent Johnson
Willem Ligtenberg wrote:
I want to parse a very large (2.4 gig) XML file (bioinformatics ofcourse :))
But I have no clue how to do that. Most things I see read the entire xml
file at once. That isn't going to work here ofcourse.
So I would like to parse a XML file one record at a time and then be able
to store the information in another object.
How should I do that?
You might be interested in this recipe using ElementTree:
http://online.effbot.org/2004_12_01_archive.htm#element-generator
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Simple Thunks

2005-04-16 Thread Bengt Richter
On Fri, 15 Apr 2005 16:44:58 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote:

>Here is a first draft of a PEP for thunks.  Please let me know what you 
>think. If there is a positive response, I will create a real PEP.
>
>I made a patch that implements thunks as described here. It is available 
>at:
> http://staff.washington.edu/sabbey/py_do
>
>Good background on thunks can be found in ref. [1].

UIAM most of that pre-dates decorators. What is the relation of thunks
to decorators and/or how might they interact?

>
>Simple Thunks
>-
>
>Thunks are, as far as this PEP is concerned, anonymous functions that 
>blend into their environment. They can be used in ways similar to code 
>blocks in Ruby or Smalltalk. One specific use of thunks is as a way to 
>abstract acquire/release code. Another use is as a complement to 
>generators.

"blend into their environment" is not very precise ;-)
If you are talking about the code executing in the local namespace
as if part of a suite instead of apparently defined in a separate function,
I think I would prefer a different syntax ;-)

>
>A Set of Examples
>=
>
>Thunk statements contain a new keyword, 'do', as in the example below. The 
>body of the thunk is the suite in the 'do' statement; it gets passed to 
>the function appearing next to 'do'. The thunk gets inserted as the first 
>argument to the function, reminiscent of the way 'self' is inserted as the 
>first argument to methods.
>
>def f(thunk):
>before()
>thunk()
>after()
>
>do f():
>stuff()
>
>The above code has the same effect as:
>
>before()
>stuff()
>after()
Meaning "do" forces the body of f to be exec'd in do's local space? What if 
there
are assignments in f? I don't think you mean that would get executed in do's 
local space,
that's what the thunk call is presumably supposed to do...

But let's get on to better examples, because this is probably confusing some, 
and I think there
are better ways to spell most use cases than we're seeing here so far ;-)

I want to explore using the thunk-accepting function as a decorator, and 
defining an anonymous
callable suite for it to "decorate" instead of using the do x,y in deco: or do 
f(27, 28): format.

To define an anonymous callable suite (aka thunk), I suggest the syntax for
do x,y in deco:
suite
should be
@deco
(x, y):# like def foo(x, y):  without the def and foo
suite

BTW, just dropping the def makes for a named thunk (aka callable suite), e.g.
foo(x, y):
suite
which you could call like
foo(10, 4)
with the local-where-suite-was-define effect of
x = 10
y = 4
suite

BTW, a callable local suite also makes case switching by calling through 
locals()[xsuitename]()
able to rebind local variables. Also, since a name is visible in an enclosing 
scope, it could
conceivably provide a mechanism for rebinding there. E.g.,

def outer():
xsuite(arg):
   x = arg
def inner():
   xsuite(5)
x = 2
print x # => 2
inner()
print x # => 5

But it would be tricky if outer returned inner as a closure.
Or if it returned xsuite, for that matter. Probably simplest to limit
callable suites to the scope where they're defined.

>
>Other arguments to 'f' get placed after the thunk:
>
>def f(thunk, a, b):
> # a == 27, b == 28
> before()
> thunk()
> after()
>
>do f(27, 28):
> stuff()
I'm not sure how you intend this to work. Above you implied (ISTM ;-)
that the entire body of f would effectively be executed locally. But is that
true? What if after after() in f, there were a last statment hi='from last 
statement of f'
Would hi be bound at this point in the flow (i.e., after d f(27, 28): stuff() )?

I'm thinking you didn't really mean that. IOW, by magic at the time of calling 
thunk from the
ordinary function f, thunk would be discovered to be what I call an executable 
suite, whose
body is the suite of your do statement.

In that case, f iself should not be a callable suite, since its body is _not_ 
supposed to be called locally,
and other than the fact that before and after got called, it was not quite 
exact to say it was _equivalent_ to

before()
stuff() # the do suite
after()

In that case, my version would just not have a do, instead defining the do suite
as a temp executable suite, e.g., if instead


we make an asignment in the suite, to make it clear it's not just a calling 
thing, e.g.,

 do f(27, 28):
  x = stuff()

then my version with explict name callable suite would be

 def f(thunk, a, b):
  # a == 27, b == 28
  before()
  thunk()
  after()

 set_x():
 x = stuff() # to make it plain it's not just a calling thing

 f(set_x, 27, 28)
 # x is now visible here as local binding

but a suitable decorator and an anonymous callable suite (thunk defined my way 
;-) would make this

 @f(27, 28)
 (): x = stuff()


>
>Thunks can also accept arguments:
>
>def f(thunk):
>   

Re: pre-PEP: Simple Thunks

2005-04-16 Thread Kay Schluehr
Brian Sabbey wrote:

> def get_items(thunk):# <-- "thunk-accepting function"
>  f = acquire()
>  try:
>  for i in f:
>  thunk(i)  # A-OK
>  finally:
>  f.release()
>
> do i in get_items():
> print i

Seems like You want to solve the addressed generator problem by
manipulating the syntax: "make generators look more function like",
because father compiler won't complain ;-) Sorry, but IMO this is
hackery and has nothing to do with good language design and I consider
this as extremely harmfull. Instead of making things explicit it does
it the other way round and tries to make Python code more obscure.
Moreover I can't notice the superiority of thunks in Your other
examples over more common techniques like decorators for pre- and
postconditions and the GOF command pattern. I thinks the place for such
ideas are Michael Hudsons famous bytecodehacks.

-1 for from me for thunks in Python.

Ciao,
Kay

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


Re: XML parsing per record

2005-04-16 Thread Ivan Voras
Irmen de Jong wrote:
XML is not known for its efficiency
 Surely you are blaspheming, sir! XML's the greatest thing 
since peanut butter! 

I'm just *waiting* for the day someone finds its use on the rolls of 
toilet paper... oh the glorious day...

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


Re: trouble to print array contents using slice operator

2005-04-16 Thread Diez B. Roggisch
praba kar wrote:

> Dear all,
> 
>In Php array_slice function base
> we can print array contents as per our desire
> eg)
> 
> $a = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
> $arr = array_slice($a,10,10);
> 
> this function will print 11,12,13,14,15
> 
> But I try to print the same thing in python
> using slice operator
> 
> eg) print a[10:10]
> 
> This statement print [] empty array.
> 
> How I need to get my desired output like php
> array_slice function?

Slicing indices in python are [start:stop], not [start:lengh]. So use

print a[10:10+10]




-- 
Regards,

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


Re: whitespace , comment stripper, and EOL converter

2005-04-16 Thread qwweeeit
Hi,

At last I succeded in implementing a cross reference tool!
(with your help and that of other gurus...).
Now I can face the problem (for me...) of understanding your 
code (I have not grasped the classes and objects...).

I give you a brief example of the xref output (taken from your code,
also if the line numbers don't match, because I modified your code,
not beeing interested in eof's other than Linux).

and 076 if self.lasttoken<=self.spaces and
self.spaces:
append  046 self.lines.append(pos)
append  048 self.lines.append(len(self.raw))
argv116 if sys.argv[1]:
argv117 filein = open(sys.argv[1]).read()
__author__  010 __author__ = s_
break   045 if not pos: break
__call__080 def __call__(self, toktype, toktext, (srow,scol),
..
   (erow,ecol), line):
class   015 class Stripper:
COMMENT 092 if toktype == tokenize.COMMENT:
comments021 def format(self, out=sys.stdout, comments=0,
spaces=1,untabify=1):
comments033 self.comments = comments
comments090 if not self.comments:
comments118 Stripper(filein).format(out=sys.stdout,
comments=0,.  
untabify=1)
__credits__ 008 __credits__ = s_
__date__011 __date__ =  s_
DEDENT  105 if toktype in [token.INDENT, token.DEDENT]:
def 018 def __init__(self, raw):
def 021 def format(self, out=sys.stdout, comments=0, 
.  spaces=1,untabify=1):
def 080 def __call__(self, toktype, toktext, (srow,scol),
(erow,ecol), line):
def 114 def Main():
ecol080 def __call__(self, toktype, toktext, (srow,scol),
.   (erow,ecol), line):
erow080 def __call__(self, toktype, toktext, (srow,scol), 
. (erow,ecol), line):
ex  059 except tokenize.TokenError, ex:
except  059 except tokenize.TokenError, ex:
expandtabs  036self.raw = self.raw.expandtabs()
filein  117 filein = open(sys.argv[1]).read()
filein  118 Stripper(filein).format(out=sys.stdout,
comments=0,
   
untabify=1)
find044 pos = self.raw.find(self.lineend, pos) + 1
format  021 def format(self, out=sys.stdout, comments=0, 
   spaces=1,untabify=1):
format  118 Stripper(filein).format(out=sys.stdout,
comments=0,
   untabify=1)
import  005 import keyword, os, sys, traceback
import  006 import StringIO
import  007 import token, tokenize
import  115 import sys
INDENT  105 if toktype in [token.INDENT, token.DEDENT]:
__init__018 def __init__(self, raw):
isspace 071 if not line.isspace():
keyword 005 import keyword, os, sys, traceback
lasttoken   030 self.lasttoken = 1
lasttoken   072 self.lasttoken=0
lasttoken   075 self.lasttoken+=1
lasttoken   076 if self.lasttoken<=self.spaces and
   self.spaces:
...

To obtain this output, you must remove comments and empty lines, move
strings in a db file, leaving as place holder s_ for normal strings
and m_ for triple strings.
See an example:

m_   """python comment and whitespace stripper :)"""  #016
m_   ''' strip comments, strip extra whitespace, convert EOL's from
Python
  code.'''#023 
m_   ''' Token handler.'''#082

s_ 'just another tool that I needed'|008 __credits__ = 'just another
tool
   that I needed'
s_ '.7'   |009 __version__ = '.7'
s_ 'M.E.Farmer'   |010 __author__ = 'M.E.Farmer'
s_ 'Jan 15 2005, Oct 24 2004'   |011 __date__ =  'Jan 15 2005, Oct 24
2004'
s_ ' '|037 self.raw = self.raw.rstrip()+'
'
s_ '\n'   |040 self.lineend = '\n'
s_ '__main__' |122 if __name__ == '__main__':

I think that this tool is very useful.

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


RE: trouble to print array contents using slice operator

2005-04-16 Thread Michael . Coll-Barth
print a[10:15] 
or 
print a[10:]



-Original Message-
From:
[EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
n.org]On Behalf Of praba kar
Sent: Saturday, April 16, 2005 10:28 AM
To: python-list@python.org
Subject: trouble to print array contents using slice operator


Dear all,

   In Php array_slice function base
we can print array contents as per our desire
eg)

$a = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$arr = array_slice($a,10,10);

this function will print 11,12,13,14,15

But I try to print the same thing in python
using slice operator 

eg) print a[10:10] 

This statement print [] empty array.  

How I need to get my desired output like php
array_slice function?

with regards
Prabahar



 


Yahoo! India Matrimony: Find your life partner online
Go to: http://yahoo.shaadi.com/india-matrimony
-- 
http://mail.python.org/mailman/listinfo/python-list
___
The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.

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


RE:

2005-04-16 Thread Michael . Coll-Barth
All,

I have been going through the manuals and not having much luck with the
following code.  This is basically an issue of giving 'split' multiple
patterns to split a string.  If it had an ignore case switch, the problem
would be solved.  Instead, I have to code the following, which works fine
for a single byte string.  What can I do when I want to look for strings?

>>> test = 'A big Fat CAt'
>>> A = test.split('A')
>>> print A
['', ' big Fat C', 't']
>>> a = []
>>> for x in xrange(len(A)):
... tmp = A[x].split('a')
... for y in xrange(len(tmp)):
... a.append(tmp[y])
...
>>>
>>> a
['', ' big F', 't C', 't']



It is odd about the help files, after I figure out how to do something, the
help makes sense.  Before hand is another story...  Are there any others out
there that share this misery? 

thanks,
Michael
___
The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.

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


trouble to print array contents using slice operator

2005-04-16 Thread praba kar
Dear all,

   In Php array_slice function base
we can print array contents as per our desire
eg)

$a = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$arr = array_slice($a,10,10);

this function will print 11,12,13,14,15

But I try to print the same thing in python
using slice operator 

eg) print a[10:10] 

This statement print [] empty array.  

How I need to get my desired output like php
array_slice function?

with regards
Prabahar



 


Yahoo! India Matrimony: Find your life partner online
Go to: http://yahoo.shaadi.com/india-matrimony
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python modules in home dir

2005-04-16 Thread Uche Ogbuji
On Sat, 2005-04-09 at 14:09 -0700, dzieciou wrote:

> I'm new-comer in Python.
> I want to install few Python modules (4Suite, RDFLib, Twisted and Racoon)
> in my home directory, since Python installation is already installed in the
> system
> and I'm NOT its admin.
> I cannot install pyvm (portable binary python machine) - have no such big
> quota.
> Any idea how can I solve it?

To install 4Suite in the home dir, use an incantation such as:

./setup.py config --prefix=$HOME/lib
./setup.py install

Note: I expect you also installed Python in your home dir?


-- 
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Use CSS to display XML, part 2 - 
http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html
Writing and Reading XML with XIST - 
http://www.xml.com/pub/a/2005/03/16/py-xml.html
Use XSLT to prepare XML for import into OpenOffice Calc - 
http://www.ibm.com/developerworks/xml/library/x-oocalc/
Schema standardization for top-down semantic transparency - 
http://www-128.ibm.com/developerworks/xml/library/x-think31.html

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


Re: sort of a beginner question about globals

2005-04-16 Thread fred.dixon
just read the ne stuuf. i went to DIP right after work anf found in
nice intro to unittest. not to bad (i thinK) now that I can see it work)

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


Re: XML parsing per record

2005-04-16 Thread Irmen de Jong
Willem Ligtenberg wrote:
I want to parse a very large (2.4 gig) XML file (bioinformatics ofcourse :))
But I have no clue how to do that. Most things I see read the entire xml
file at once. That isn't going to work here ofcourse.
So I would like to parse a XML file one record at a time and then be able
to store the information in another object.
How should I do that?
Thanks in advance,
Willem Ligtenberg
A total newbie to python by the way.

Read about SAX parsers.
This may be of help:
http://www.devarticles.com/c/a/XML/Parsing-XML-with-SAX-and-Python/
Out of curiousity, why is the data stored in a XML file?
XML is not known for its efficiency
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


XML parsing per record

2005-04-16 Thread Willem Ligtenberg
I want to parse a very large (2.4 gig) XML file (bioinformatics ofcourse :))
But I have no clue how to do that. Most things I see read the entire xml
file at once. That isn't going to work here ofcourse.

So I would like to parse a XML file one record at a time and then be able
to store the information in another object.
How should I do that?

Thanks in advance,

Willem Ligtenberg
A total newbie to python by the way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode "em space" in regex

2005-04-16 Thread Klaus Alexander Seistrup
Xah Lee :

> how to represent the unicode "em space" in regex?
>
> e.g. i want do something like this:
>
> fracture=re.split(r'\342371*\|\342371*',myline,re.U)

I'm not sure what you're trying to do, but would it help you to use
it's name:

>>> EM_SPACE = u'\N{EM SPACE}'
>>> fracture = myline.split(EM_SPACE)

?

Cheers,

-- 
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python 2.3.2 for PalmOS available

2005-04-16 Thread Peter Hansen
Klaus Alexander Seistrup wrote:
[EMAIL PROTECTED] wrote:
Some months ago i did a port of the Python2.3.2 interpreter to
PalmOS.
Wow, this is just what I've been waiting for.  Meanwhile I've tried
to make do with Rexx for PalmOS, hehehe...
I've been making do (rather successfully so far) with
Plua 2 (basically Lua 5.0), which I think feels a
little closer to Python than does Rexx (but which
doesn't come, out of the box, with quite as much
power).
The main benefit is that it *does* support the Palm
OS stuff, mainly making a UI form, an event loop,
and interfacing with databases.
It would be wonderful if Python was equally well
supported (yes, I know, somebody has to do the work)
but I also suspect there's no hope of it running on
my old 2MB Palm V the way Plua currently does! :-)
Well, it would finally be a reason to upgrade though...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python 2.3.2 for PalmOS available

2005-04-16 Thread Klaus Alexander Seistrup
[EMAIL PROTECTED] wrote:

> Some months ago i did a port of the Python2.3.2 interpreter to
> PalmOS.

Wow, this is just what I've been waiting for.  Meanwhile I've tried
to make do with Rexx for PalmOS, hehehe...

However, MLPY doesn't seem to work on my Tungsten T3 (PalmOS 5.2.1).
The .prc installs without any problems, and I can start the Python
interpreter, but nothing happens if I ring in a Python expression and
press return -- the prompt just "hangs" and never returns.

Any ideas?

-- 
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MS SQL Server/ODBC package for Python

2005-04-16 Thread Francois Lepoutre
Peter,
May my I apologize for knocking against your information, as well.
> For what it is worth, my experience is as follows:  Using a PIII
> 550MHz, 256MB RAM, running WinNT 4.0 and Python 2.3.4 and connecting
> to a Sybase Adaptive Server Anywhere 8.0 database, mx.ODBC took
> approximately 8 wall-clock seconds to connect
As a long time user of the ASA range of products, I was surprised
by your connection time to ASA 8. I'm not a regular user of mxODBC
but i have tested it with success here. With no pending time upon
connection whatever the middleware.
The script below ran fast on my machine (an oldish pentium 400)
with ASA 8.0.2 (the engine is local).
When re-cycling ASA connection (a good practice) the script took
0.21 sec. to run and  3.4 sec. when re-building the connection
on every hit (which you should avoid).
For 100 connections, not one! Which confirms my feeling that
something got in the way when you ran your test.
mxODBC is fast and safe (on both linux and win32).
I won't comment on ado since i'm not a user. But the fact that
ASA+mxODBC runs multi-platform may be an additional advantage.
Regards
Francis
from mx import ODBC
import time
mytime=time.time()
print "1 connection and 750 cursors started, used and closed at once..."
dbHandle=ODBC.Windows.Connect("descriptive demo fr","dupont","",0)
for i in range(100):
cHandle=dbHandle.cursor()
cHandle.execute("select 1")
cHandle.fetchall()
cHandle.close()
print time.time() - mytime
print "750 connection fully started, used and closed at once..."
for i in range(100):
dbHandle=ODBC.Windows.Connect("descriptive demo fr","dupont","",0)
cHandle=dbHandle.cursor()
cHandle.execute("select 1")
cHandle.fetchall()
cHandle.close()
dbHandle.close()
print time.time() - mytime
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python appropriate for web applications?

2005-04-16 Thread Unknown User
Thank you very much.
On Fri, 15 Apr 2005 06:47:14 -0300, Peter Maas <[EMAIL PROTECTED]> wrote:
Unknown User schrieb:
I am a Python programmer and I'm thinking about learning PHP, which is
similar to C++
wrong
(quite  different from Python).
true
I want to start writing web applications. Do  you  think if I learn
 > PHP I'll develop faster?
Nobody but you can anawer this question. You'll have to try.
Does PHP have more features?
PHP has a rich library which probably outperforms any Python alternative
in terms of features. But this doesn't necessarily mean that you will
develop faster in PHP. The problem with Python is that you have to make
a choice among many solutions (roughly ordered by inreasing complexity):
- plain cgi
- Quixote
- modpython
- CherryPy
- Spice
- Webware
- Twisted
- ZOPE
...
Have a look at http://www.python.org/topics/web/
How about the speed  of execution?
There is no simple answer. Both languages use C functions which are
executed at CPU speed. But with interpreted code Python seems to be
approximately 3-4 times faster than PHP (http://dada.perl.it/shootout/).
What are the pros and cons?
http://www.allsites.com/Top.Computers.Programming.Languages.Comparison_and_Review.html

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
--
http://mail.python.org/mailman/listinfo/python-list


unicode "em space" in regex

2005-04-16 Thread Xah Lee
how to represent the unicode "em space" in regex?

e.g. i want do something like this:

fracture=re.split(r'\342371*\|\342371*',myline,re.U)

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

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


Re: pythonic use of properties?

2005-04-16 Thread Diez B. Roggisch
> 
> Even though "tens", "ones" and "number" all appear as attributes, only
> "number" has its input validated.  Since the class is designed to only
> hold numbers 0 - 99, one can 'break' it by setting self.tens=11, for
> example.  Should tens and ones be made into full-fledged properties
> and validated?  Should number have no validation?  Is it more pythonic
> to encapsulate tightly, or rely on "responsible use."

You could make them double-underscored attributes. That creates some
name-mangling that prevents accidential access. But as there is no real
private concept in python (and java and C++ protection can be easily
overcome), it is considered pythonic to rely on responsible use.  If a
design for abuse-protection is the ultimate goal, the common suggestion is
to use IPC mechanisms to prevent in-process sharing of data and code -
that's the only real way to go, regardless of the used language.

-- 
Regards,

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


Re: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 140)

2005-04-16 Thread Craig
Lord... forgive the Holy Roller, spammers for they know not what they do

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread peufeu

How would you write
if f(x=1):
print "yes"
using suite-based keyword args?
	Good point.
	Then we should remove the extra ':' at the end of the function invocation  
:

if f(x=@>):
value of x
print "yes"
if f(@**>):
x: value of x
print "yes"
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Simple Thunks

2005-04-16 Thread peufeu
	I think your proposal is very interesting, I've been missing code blocks  
in Python more and more as time goes by.
	I'll answer to both the 'thunks" proposal and the "suite-based keywords"  
proposal here.

	I find the Ruby syntax rather dirty though, because it has a lot of  
implicit stuff, treats code blocks as different from normal arguments,  
allows passing only one code block, needs a proc keyword, has yield  
execute an implicit block... all this, coming from a Python "explicit is  
better than implicit" background (which makes a lot of sense) is simply  
ugly.
	I like your syntax but have a few comments.
	I'll give you an unordered list of ideas, up to you to do what you like  
with them.

	Keep in mind that most of the problems come from the "space is  
significant" thing, which is IMHO a very good idea, but prevents us from  
putting code in expressions, like :

func( a,b, def callback( x ):
print x
)
or does it ? maybe this syntax could be made to work ?

Comments on the thunks.
	First of all I view code blocks as essential to a language. They are very  
useful for a lot of common programming tasks (like defining callbacks in  
an elegant way) :

button = create_button( "Save changes" ):
do
self.save()
	However it seems your thunks can't take parameters, which to me is a big  
drawback. In ruby a thunk can take parameters. Simple examples :

	field = edit_field( "initial value", onsubmit={ |value| if  
self.validate(value) then do something else alert( "the value is invalid"  
) } )
	[1,3,4].each { |x| puts x }

	This has the advantage that the interface to the thunk (ie. its  
parameters) are right there before your eyes instead of being buried in  
the thunk invocation code inside the edit_field.

a more complex random example :
	fields['password1'] = edit_field( "Enter Password" )
	fields['password2'] = edit_field( "Enter it again", onsubmit = {|value,  
other_values| if value != other_values['password_1'] then alert('the two  
passwords must be the same !") }

	So I think it's essential that thunks take parameters and return a value  
(to use them effectively as callbacks).
	What shall distinguish them from a simple alteration to def(): which  
returns the function as a value, and an optional name ? really I don't  
know, but it could be the way they handle closures and share local  
variables with the defining scope. Or it could be that there is no need  
for two kinds of function/blocks and so we can reuse the keyword def() :

If you wish to modify def(), you could do, without creating any keyword 
:
# standard form
f = def func( params ):
code
# unnamed code block taking params
func = def (params):
code
	Note that the two above are equivalent with regard to the variable  
"func", ie. func contains the defined function. Actually I find def  
funcname() to be bloat, as funcname = def() has the same functionality,  
but is a lot more universal.

# unnamed block taking no params
f = def:
code
***
Comments on the suite-based keywords.
Did you notice that this was basically a generalized HEREDOC syntax ?
I'd say that explicit is better than implicit, hence...
Your syntax is :
do f(a,b):
a block
passes block as the last parameter of f.
I don't like it because it hides stuff.
I'd write :
f(a,b,@>,@>):
"""a very
large multi-line
string"""
def (x):
print x
	Here the @> is a symbol (use whatever you like) to indicate "placeholder  
for something which is on the next line".
	Indentation indicates that the following lines are indeed argument for  
the function. The : at the end of the function call is there for coherence  
with the rest of the syntax.
	Notice that, this way, there is no need for a "do" keyword, as the code  
block created by an anonymous def() is no different that the other  
parameter, in this case a multiline string.

This has many advantages.
It will make big statements more readable :
	instead of :
	f( a,b, [some very big expression made up of nested class constructors  
like a form defintion ], c, d )

write :
f( a, b, @>, c, d ):
[the very big expression goes here]
	So, independently of code blocks, this already improves the readability  
of big statements.
	You could also use named parameters (various proposals):

f( a,b, c=@>, d=@> ):
value of c
value of d
or :
f( a,b, @*> ):
value of c
value of d
f( a,b, @**> ):
c: value of c
d: value of d
	Notice how this mimics f( a,b, * ) and f(a,b, ** ) for multiple  
arguments, and multiple named arguments. Do you like it ? I do. Especially  
the named version whe

Re: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 140)

2005-04-16 Thread [EMAIL PROTECTED]
I don't know why you post this article and contradict pope and
Christian.
Is this the right forum to talk something like this ?

I guess this is only python language forum not Religion forum 


---
pujo

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


Re: RE Engine error with sub()

2005-04-16 Thread Maurice LING
Hi all,
I think I might have a workaround to this problem but have no idea how 
to work it through. I hope that someone can kindly help me out because I 
do not quite understand the mechanics of the _make_regex() method in the 
original codes...

My idea is, instead of having one UserDict, have a list of UserDicts. So 
 a large unprocessable replacement rule set is split into multiple 
smaller files, with each file read into a UserDict and it is made into a 
 RE matcher. Then iterative matching using a list of REs.

In short, the current precedure is
1 dictionary, 1 RE, 1 RE matcher... to match inputs
My workaround is to change it to
list of dictionaries, list of REs, list of RE matcher... iterative 
matching of inputs.

Can someone kindly help me out here?
Thanks in advance.
Cheers,
Maurice
Maurice LING wrote:
Hi,
I have the following codes:
from __future__ import nested_scopes
import re
from UserDict import UserDict
class Replacer(UserDict):
"""
An all-in-one multiple string substitution class. This class was 
contributed by Xavier
Defrang to the ASPN Python Cookbook 
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330)
and [EMAIL PROTECTED]

Copyright: The methods _make_regex(), __call__() and substitute() 
were the work of Xavier Defrang,
__init__() was the work of [EMAIL PROTECTED], all others were 
the work of Maurice Ling"""

def __init__(self, dict = None, file = None):
"""Constructor. It calls for the compilation of regular 
expressions from either
a dictionary object or a replacement rule file.

@param dict: dictionary object containing replacement rules with 
the string to be
replaced as keys.
@param file: file name of replacement rule file
"""
self.re = None
self.regex = None
if file == None:
UserDict.__init__(self, dict)
self._make_regex()
else:
UserDict.__init__(self, self.readDictionaryFile(file))
self._make_regex()

def cleanDictionaryFile(self, file):
"""
Method to clean up the replacement rule dictionary file and 
write the cleaned
file as the same name as the original file."""
import os
dict = self.readDictionaryFile(file)
f = open(file, 'w')
for key in dict.keys(): f.write(str(key) + '=' + str(dict[key]) 
+ os.linesep)
f.close()

def readDictionaryFile(self, file):
"""
Method to parse a replacement rule file (file) into a dictionary 
for regular
expression processing. Each rule in the rule file is in the form:
=
"""
import string
import os
f = open(file, 'r')
data = f.readlines()
f.close()
dict = {}
for rule in data:
rule = rule.split('=')
if rule[1][-1] == os.linesep: rule[1] = rule[1][:-1]
dict[str(rule[0])] = str(rule[1])
print '%s replacement rule(s) read from %s' % 
(str(len(dict.keys())), str(file))
return dict

def _make_regex(self):
""" Build a regular expression object based on the keys of the 
current dictionary """
self.re = "(%s)" % "|".join(map(re.escape, self.keys()))
self.regex = re.compile(self.re)

def __call__(self, mo):
""" This handler will be invoked for each regex match """
# Count substitutions
self.count += 1 # Look-up string
return self[mo.string[mo.start():mo.end()]]
def substitute(self, text):
""" Translate text, returns the modified text. """
# Reset substitution counter
self.count = 0
# Process text
#return self._make_regex().sub(self, text)
return self.regex.sub(self, text)
def rmBracketDuplicate(self, text):
"""Removes the bracketed text in occurrences of ' 
()'"""
regex = re.compile(r'(\w+)\s*(\(\1\))')
return regex.sub(r'\1', text)

def substituteMultiple(self, text):
"""Similar to substitute() method except that this method loops 
round the same text
multiple times until no more substitutions can be made or when 
it had looped
10 times. This is to pre-ampt for cases of recursive 
abbreviations."""
count = 1 # to get into the loop
run = 0 # counter for number of runs thru the text
while count > 0 and run < 10:
count = 0
text = self.rmBracketDuplicate(self.substitute(text))
count = count + self.count
run = run + 1
print "Pass %d: Changed %d things(s)" % (run, count)
return text


Normally I will use the following to instantiate my module:
replace = Replacer('', 'rule.mdf')
rule.mdf is in the format of "=\n"

Then using replace.substituteMultiple('') to carry out multiple 
replacements.

It all works well for rule count up to 800+ but when my replacement 
rules swells up to 1800+, it gives me a

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Reinhold Birkenfeld
Brian Sabbey wrote:
> Here is a pre-PEP for what I call "suite-based keyword arguments". The 
> mechanism described here is intended to act as a complement to thunks. 
> Please let me know what you think.
> 
> Suite-Based Keyword Arguments
> -
> 
> Passing complicated arguments to functions is currently awkward in Python. 
> For example, the typical way to define a class property winds up polluting 
> the class's namespace with the property's get/set methods.  By allowing 
> keyword arguments to be defined in a suite following a function call, 
> complicated arguments can be passed in a cleaner, easier way.
> 
> Examples
> 
> 
> Using suite-based keyword arguments, the code
> 
> f(x = 1)
> 
> is equivalent to
> 
> f():
> x = 1

Pretty cool, but it interferes with current suites.

How would you write

if f(x=1):
print "yes"

using suite-based keyword args?

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


distutils question: different projects under same namespace

2005-04-16 Thread Qiangning Hong
To avoid namespace confliction with other Python packages, I want all
my projects to be put into a specific namespace, e.g. 'hongqn' package,
so that I can use "from hongqn.proj1 import module1", "from
hongqn.proj2.subpack1 import module2", etc.

These projects are developed and maintained and distributed seperately,
so I should not make a whole 'hongqn' package with one setup.py.  I
must write setup.py scripts for each project.  I meet a problem here.

For instance, I am writing setup.py script for proj1. I use the
following parameters when calling distutils.core.setup:

setup(
...
package_dir = {'hongqn.proj1': 'proj1'},
packages = ['hongqn.proj1'],
...
)

"python setup.py install" will create /usr/lib/python2.3/hongqn/proj1
directory and copy proj1/*.py there.  But this is UNUSABLE!  There is
NO __init__.py file under /usr/lib/python2.3/hongqn/ so that import
hongqn.proj1 will fail!

I am considering manually create this __init__.py by hacking the
install_lib command.  But before making my hands dirty,  I want to know
if there is an "official" solution exists or others have already
success stories on this matter.

As a note, I wish the solution can handle setup.py bdist and
bdist_wininst well.

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


Re: ANN: Python 2.3.2 for PalmOS available

2005-04-16 Thread Wolfgang Keller
> If there is any interest on this, please let me know so we can work on
> getting this as a real port.

"Interest" is just a "slight" understatement... :-)

Best regards

Wolfgang Keller

-- 
P.S.: My From-address is correct
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem when subclass instance changes base class instance variable

2005-04-16 Thread Peter Otten
Gerry Sutton wrote:

> I have noticed a strange behavior when using a constant identifier to
> initialize an instance list variable in a base class and then trying to
> modifying the list in subclasses by using either the list.extend method or
> even by having the subclass create a whole new list in the variable.
> 
> The following example illustrates the situation.

> Lbase = ['Initial Base Data']

> class BaseClass:
> def __init__(self):
> self.data = Lbase #<  this fails??

self.data and Lbase are now bound to the same variable. Consequently changes
to that variable through self.data affect Lbase and vice versa. This is
standard Python behaviour. If you want to use Lbase as a kind of initial
value, modify BaseClass to make a (shallow) copy:

class BaseClass:
def __init__(self):
self.data = list(Lbase)

Now every BaseClass instance gets its separate copy. If you have nested
mutables, e. g. a list of lists, look into the copy module for deepcopy().

Peter

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


need help in PySparse

2005-04-16 Thread monocalibro
Hello all!
I need ready-for-use installable version of PySparse (for FiPy), because I
can't compile it with MingW. Or, may be, somebody knows step-by-step
instruction to complie this package under Win32 using Mingw?
Best regards


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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
On Fri, 15 Apr 2005 16:45:55 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote:

>Here is a pre-PEP for what I call "suite-based keyword arguments". The 
>mechanism described here is intended to act as a complement to thunks. 
>Please let me know what you think.
>
Sorry, I replied to to you via James Stroud's reply (q.v.) ;-)
BTW, I like this suite-based keword definition for calls better
than the thunk stuff ;-)

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
On Fri, 15 Apr 2005 19:32:02 -0700, James Stroud <[EMAIL PROTECTED]> wrote:

>I_vote_yes(James):
>   I_understand_what_it_does = True
>   Makes_code_formatting_way_more_managable_in_tough_cases = True
>   Makes_code_way_more_readable = True
>   To_cool = True
>
>On Friday 15 April 2005 04:45 pm, Brian Sabbey wrote:
>> Here is a pre-PEP for what I call "suite-based keyword arguments". The
>> mechanism described here is intended to act as a complement to thunks.
>> Please let me know what you think.
>>
Kind of cool. If we had full lambdas aka as anonymous defs (def foo(...) with 
foo left out ;-)
would this be concise sugar for the equivalents shown below your examples?

(The rule for parsing the suite of an anonymous def is that the left column of 
the first non-space
character of the first suite statement following the def(): becomes the suite 
indent reference,
and a dedent to the left of that ends the def(): or a closing bracket not 
opened in the def(): suite
also ends it. Otherwise it is standard suite indentation)

>> Suite-Based Keyword Arguments
>> -
>>
>> Passing complicated arguments to functions is currently awkward in Python.
>> For example, the typical way to define a class property winds up polluting
>> the class's namespace with the property's get/set methods.  By allowing
>> keyword arguments to be defined in a suite following a function call,
>> complicated arguments can be passed in a cleaner, easier way.
>>
>> Examples
>> 
>>
>> Using suite-based keyword arguments, the code
>>
>> f(x = 1)
>>
>> is equivalent to
>>
>> f():
>> x = 1

   f(**def():
 x = 1
 return vars())
   
>>
>> In general, a suite following a function call creates a new scope.  The
>> bindings created in this scope get passed to the function as keyword
>> arguments.
>>
>> Suite-based keyword arguments can be mixed with regular arguments:
>>
>> f(1, 2, y = 4):
>>  x = 1

   f(1, 2, y = 4,
**def():
x =1
return vars())
>>
>> Motivation
>> ==
>>
>> One motivation for suite-based keywords is to allow cleaner definitions of
>> properties.  Currently, properties are typically define as in this
>> example:
>>
>> class C(object):
>> def getx(self):
>>return self.__x
>> def setx(self, value):
>>self.__x = value
>> def delx(self):
>>del self.__x
>> x = property(getx, setx, delx, "I'm the 'x' property.")
>>
>> The 'getx', 'setx', and 'delx' methods get defined in the namespace of the
>> class even though one wants only to pass them to 'property'.  Ideally, one
>> would want these methods to be defined in their own namespace.  Also, it
>> would be helpful when reading the code if the layout of the code gave
>> visual indication that their only purpose is to be used in a property.
>>
>> Using suite-based keyword arguments, and without any changes to the
>> 'property' type, this code can be written as:
>>
>> class C(object):
>> x = property():
>>doc = "I'm the 'x' property."
>>def fget(self):
>>   return self.__x
>>def fset(self, value):
>>   self.__x = value
>>def fdel(self):
>>   del self.__x
   clas C(object):
   x = property(
  **def():
doc = "I'm the 'x' property."
def fget(self):
   return self.__x
def fset(self, value):
   self.__x = value
def fdel(self):
   del self.__x
return vars())
  
>>
>> Here, 'fget', 'fset' and 'fdel' do not wind up as methods of the class,
>> and it is visually clear that they are methods only for the 'x' property.
>> Also, this code is less bug-prone since the name of each method need
>> appear only once.
>>
>> Passing callbacks in other situations is made similarly easier and
>> cleaner:
>>
>> setHandlers():
>>  def success():
>>  print 'success'
>>  def failure():
>>  print 'an error has occured'
>>  def apocalypse():
>>  print 'a serious error has occured'
   setHandlers(**def():
def success():
print 'success'
def failure():
print 'an error has occured'
def apocalypse():
print 'a serious error has occured'
return vars())
>>
>> a = [1,3,2]
>> a.sort():
>>  def cmpfunc(x,y):
>>  return cmp(x,y)
   a.sort(**def():
def cmpfunc(x,y)
return vars())
>>
>> Situations that do not require callbacks can also be better organized
>> using suite-based keywords.  For example, here is code as it would
>> currently be written in Python:
>>
>> if a:
>>  x = 1
>> else:
>>  x = 2
>> f(x=x)
>>
>> When reading this code, one reaches the 'if' statment without knowing what
>> its purpose is-- layout of the code does not indicate that the 'if'
>> statement is calculating an argument to 'f'.  Also, it requires a binding
>> that serves no purpose other than to hold an argumen

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Shane Hathaway
Kent Johnson wrote:
> Brian Sabbey wrote:
>> Using suite-based keyword arguments, the code
>>
>> f(x = 1)
>>
>> is equivalent to
>>
>> f():
>>x = 1
> 
> 
> ISTM the syntax is ambiguous. How do you interpret
> if f():
>   x = 1
> ?
> 
> Is a suite alllowed only when a block could not be introduced in the
> current syntax?

I like this PEP a lot, but your concern is valid.  Maybe Brian could
modify the PEP slightly to disambiguate.  How about using an ellipsis in
the argument list to signify suite-based keywords?  Examples:

f(...):
x = 1

class C(object):
   x = property(...):
  doc = "I'm the 'x' property."
  def fget(self):
 return self.__x
  def fset(self, value):
 self.__x = value
  def fdel(self):
 del self.__x

d = dict(...):
a = 1
b = 2

Using an ellipsis in a statement that would begin a different kind of
block is illegal and generates a syntax error.  Note that this usage
seems to fit well with the definition of "ellipsis".

http://dictionary.reference.com/search?q=ellipsis

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