ANN: 4Suite 1.0b1

2005-04-16 Thread Uche Ogbuji
Today we release 4Suite 1.0 beta 1, now available from Sourceforge and
ftp.4suite.org.

Highlights of changes
--

* Minor to huge performance increases throughout the core libraries:
  * Ft.Lib.Set implemented in C, resulting in faster evaluation of XPath
expressions using '/', '//', and '|')
  * 40x speedup in startup time for Domlette parsing
  * Additional optimization of XPath expressions involving '/', '//',
'child::' and others
  * .docindex removed from Domlette nodes; they now compare to each
other in document order (e.g., when in a list, .sort() can be called
for document order).  Resulting XPath/XSLT speedup
  * XSLT whitespace stripping optimized; xml:space handling fixed
  * XML string utilities now in module Ft.Xml.Lib.XmlString,
implemented in C, as part of Domlette optimizations
  * Mini-SAX interface added to the Domlette Expat library, via
Ft.Xml.Sax. The mini is due to the fact that only the interfaces
required for parsing XSLT stylesheets are exposed.
  * XML catalogs and XSLT stylesheets now read via the fast mini-SAX API
  * Many more Domlette speed and memory optimizations
* RDF core: various optimizations result in speedup of RDF completes and
  faster database access
* RDF core: better Unicode handling; improvements to the way statements
  are printed, compared, iterated over, reified, serialized/deserialized
* RDF core: optimized RDFS validation (90% speedup plus other
  optimizations) plus updated to current standard
* XML core: Ft.Xml.MarkupWriter introduced--very friendly interface for
  generating XML content based on the XSLT writers, but adding
  convenience methods for common element creation patterns, and
  for inserting chunks of literal markup
* XML core: FtMiniDom removed
* XML core: All dependencies on PyExpat removed
* XML core: Domlette nodes have new attributes:
  * xpathNamespaces, a dict of in-scope namespaces
  * xpathAttributes, the node's attributes, not counting
those for namespace bindings
* Environment variable XML_CATALOG_FILES now supported
* XPath: extension functions that access the underlying OS are now
  disabled by default (e.g., f:spawnv(), f:system(), f:env-var())
* In Ft.Lib.Uri.OsPathToUri and UriToOsPath, attemptAbsolute now
defaults
  to True
* XLink: xlink:show='replace' behaves more usefully  sensibly
* BerkeleyDB (bsddb) RDF and repository drivers added (Py 2.3+ only)
* MySQL RDF and repository drivers optimized
* Repository: XSLT DocDefs repository can now use extension
  functions/elements
* Repository: better handling of external entity resolution
* Doc generation issues resolved.  API docs can now be generated for
  every module in 4Suite (various
* XHTML 1.0 Transitional DTD added to default catalog
* Many more bug fixes and enhancements.  See also
http://uche.ogbuji.net/tech/akara/?
xslt=irc.xsltdate=2005-04-11#03:52:25

4Suite is a comprehensive platform for XML and RDF processing, with base
libraries and a server framework.  It is implemented in Python and C,
and provides Python and XSLT APIs, Web and command line interfaces.

For general information, see:

http://4suite.org
http://uche.ogbuji.net/tech/4Suite/
http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/4suite-section

For the files, see:

ftp://ftp.4suite.org/pub/4Suite/

Sources:

ftp://ftp.4suite.org/pub/4Suite/4Suite-1.0b1.tar.gz

Windows installer:

ftp://ftp.4suite.org/pub/4Suite/4Suite-1.0b1.win32-py2.2.exe
ftp://ftp.4suite.org/pub/4Suite/4Suite-1.0b1.win32-py2.3.exe
ftp://ftp.4suite.org/pub/4Suite/4Suite-1.0b1.win32-py2.4.exe

Windows zip:

ftp://ftp.4suite.org/pub/4Suite/4Suite-1.0b1.zip

You can also get the files on Sourceforge:

https://sourceforge.net/projects/foursuite/
https://sourceforge.net/project/showfiles.php?group_id=39954

Documentation:

In the locations specified above, with filenames of the form

4Suite-docs-1.0b1.*

Release notes
--

If you have built a 4Suite repository using an older version of 4Suite,
you will probably have to make adjustments for this new release.  If you
used 0.12.0a3, or a more recent version, then you will have to follow
the
migration instructions detailed in the following message:

http://lists.fourthought.com/pipermail/4suite/2004-October/012933.html

In general, it's worth being familiar with the following document:

http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/backup

There have been on and off problems for Mac OS X users.  We think these
are now resolved.  Please see the following page for current status,
notes and recommendations:

http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/osx

Installation locations have changed since 0.12.0a3 on both Windows and
Unix. See the current installation directory layout document at:

http://4suite.org/docs/installation-locations.xhtml

If there is a server config files at the default location for the
build and platform (e.g. /usr/local/lib/4Suite/4ss.conf by default on
UNIX), it will be renamed to 4ss.conf.old and then overwritten.

For insulation 

ANN: Python Computer Graphics Kit v2.0.0alpha3

2005-04-16 Thread Matthias Baas
The third alpha release of version 2 of the Python Computer Graphics
Kit is available at http://cgkit.sourceforge.net


What is it?
---

The Python Computer Graphics Kit is a generic 3D package written in
C++ and Python that can be used for a variety of domains such as
scientific visualization, photorealistic rendering, Virtual Reality or
even games. The package contains a number of generic modules that can
be useful for any application that processes 3D data. This includes
new types such as vectors, matrices and quaternions. Furthermore, the
package can read and store 3D models in memory where they can be
manipulated by Python programs. The kit comes with tools that can be
used to display the scene either interactively or by rendering it
offline via a RenderMan renderer.


What's new?
---

- New polyhedron geometry (made up of general concave polygons that
may have holes)
- New storage classes FACEVARYING and FACEVERTEX for primitive
variables
- OBJ import and export (including the material files)
- OFF export and improved import
- ASF/AMC import
- BVH import
- an additional maxscript that exports a Biped skeleton and motion
into ASF/AMC

+ several smaller enhancements and bugfixes (see changelog)


Windows binary versions are available for Python 2.3 and Python 2.4.


For more information, visit:

http://cgkit.sourceforge.net


- Matthias -

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

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


ANN: Python 2.3.2 for PalmOS available

2005-04-16 Thread [EMAIL PROTECTED]
Hello,

Some months ago i did a port of the Python2.3.2 interpreter to PalmOS.
I didnt port any C module or created modules for PalmOS API's. But you
can run an interpreter and use stdin/stdout from a form.

There is also a tool to freeze scripts and use the interpreter as a
pseudo-shared library.

While talking with Facundo while in a PyAr meeting (python-argentina,
http://www.python.org/ar ) he told me that there is some interest in
this platform.

So, ive made an initial release that has no documentation on how to use
it or compile it (it requires codewarrior). If there is any interest on
this, please let me know so we can work on getting this as a real port.

As usual, this is just a proof of concept and is ugly in many ways.
(ie, in Palm, code segments must be less than 64K, so some files had to
be split and rearranged  ).

If anyone want to check this out, heres the url:
http://pyar.decode.com.ar/Members/ltorre/PythonPalm

Regards,

Lucio.

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

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


omniORB 4.0.6 and omniORBpy 2.6 released

2005-04-16 Thread Duncan Grisby
I am pleased to announce the release of omniORB version 4.0.6 and
omniORBpy version 2.6.

omniORB is a robust, high performance CORBA implementation for C++;
omniORBpy is a version for Python.

These are new stable releases. They are mainly bugfix releases, with
small new features. See the release notes for details.

As usual, the releases can be downloaded from SourceForge:

  http://sourceforge.net/projects/omniorb/

omniORB's home page is

  http://omniorb.sourceforge.net/

Enjoy!

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


twainmodule build for Python 2.4 Available

2005-04-16 Thread Kevin Gill
The twainmodule build for python 2.4 is now available. 

The project home page is at:
   http://twainmodule.sourceforge.net
You can retrieve the binaries from:
   http://sourceforge.net/project/showfiles.php?group_id=46985 

Kevin
--
http://mail.python.org/mailman/listinfo/python-announce-list
   Support the Python Software Foundation:
   http://www.python.org/psf/donations.html


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 argument to 'f', yet this
 binding persists for the rest of the surrounding function.

 Here is the same code using suite-based keyword arguments

 f():
  if a:
  x = 1
  else:
  x = 2

   f(**def():

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


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: 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


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


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: 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


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:
string to be replaced=string to replace with

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 'text-x 
(text-x)'
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 string to be replaced=string to replace 
with\n

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

It all works well for rule count up to 800+ but when my 

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: 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 where you cant' get lost in the param 

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: 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: 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


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: 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


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: 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: 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: 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


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: 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


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: 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


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:

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


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: 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 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: XML parsing per record

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

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: 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):
thunk(6,7)

do x,y in f():
# x==6, y==7
stuff(x,y)

IMO
 

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:

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: 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 specifier:
   # 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]
   function fget at 0x00EC4770


-  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 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: unicode em space in regex

2005-04-16 Thread Martin v. Lwis
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: 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.
/F
--
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: 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: 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


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 http://www.python.org/peps/pep-0008.html -- Style 
Guide for Python Code and http://www.python.org/peps/pep-0257.html 
-- 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: 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.lasttoken=self.spaces and self.spaces:
 self.out.write(self.lineend)


 def __call__(self, toktype, toktext,
 (srow,scol), (erow,ecol), line):
 ''' 

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: 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: 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: 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: 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


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: 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


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: 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
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: 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 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: 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: 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.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  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: 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: 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:

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: 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: 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
[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 multiline string.

This has many 

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 specifier:
   # 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.,
 expr where: where-suite

and where-suite 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 ::suite
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', function foo at 
0x02EE8D14))

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]
   function fget at 0x00EC4770
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: 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

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 name will remove a binding just as for vars()). 
::suite 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: 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 able to 

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: 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:suite 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 ::suite 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: 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 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:suite 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 ::suite 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 ::suite 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:suite
y = 1  # indentation as if where:suite 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 suite for ::suite
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: 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', function foo at 
 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':function foo at 0x02EE8D14}

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

so
 def foo(**kw): print kw

followed by

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

will print the same. Since ::suite 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: 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


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: 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


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: 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  oldpos:

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: 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: 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
specifier 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


[ python-Bugs-1183585 ] try to open /dev/null as directory

2005-04-16 Thread SourceForge.net
Bugs item #1183585, was opened at 2005-04-15 08:56
Message generated for change (Comment added) made by gbrandl
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1183585group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Roberto A. Foglietta (robang)
Assigned to: Nobody/Anonymous (nobody)
Summary: try to open /dev/null as directory

Initial Comment:

bash-2.05b# strace python 21 | grep open | grep null
open(/dev/null, O_RDONLY|O_NONBLOCK|O_DIRECTORY) = -1
ENOTDIR (Not a directory) 

--

Comment By: Georg Brandl (gbrandl)
Date: 2005-04-16 07:54

Message:
Logged In: YES 
user_id=849994

I don't quite understand what you're trying to tell us here.

Are you just calling Python this way and observing the
system calls? Then, what system do you use? What version?
What kernel, etc.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1183585group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1182614 ] dir() does not include _

2005-04-16 Thread SourceForge.net
Bugs item #1182614, was opened at 2005-04-13 18:21
Message generated for change (Settings changed) made by nickjacobson
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1182614group_id=5470

Category: None
Group: Python 2.4
Status: Closed
Resolution: None
Priority: 5
Submitted By: Nick Jacobson (nickjacobson)
Assigned to: Nobody/Anonymous (nobody)
Summary: dir() does not include _

Initial Comment:
At the interpreter prompt, dir() does not include the
variable _

 dir()
['__builtins__', '__doc__', '__name__']
 x = 5
 dir()
['__builtins__', '__doc__', '__name__', 'x']
 _
['__builtins__', '__doc__', '__name__', 'x']


--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1182614group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1163563 ] Sub threads execute in restricted mode

2005-04-16 Thread SourceForge.net
Bugs item #1163563, was opened at 2005-03-15 00:56
Message generated for change (Comment added) made by bcannon
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1163563group_id=5470

Category: Threads
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: anothermax (yetanothermax)
Assigned to: Nobody/Anonymous (nobody)
Summary: Sub threads execute in restricted mode

Initial Comment:
I'm using the JEP product which allows integration
of Java with Python (see http://jepp.sourceforge.net) via
starting a Python interpreter in the same process as the 
JVM.
This integrates with python via the C interface, allowing 
the user to 'eval' python code (amongst other features).

It seems that since Python 2.3.5 any threads (using the 
threading module) created via code that has been 
evaluated through the jep.eval() interface (i.e.Python C 
interface )are executed in restricted mode and cannot, 
for example, create files. Code that is just evaled (i.e not 
in a subthread) thread has no restrictions.

The error reported is:
IOError: file() constructor not accessible in restricted 
mode

(see http://sourceforge.net/forum/forum.php?
thread_id=1247793forum_id=376782) - I've given a JEP 
specific example here.

There seems to be a similar problem with mod_python
(see 
http://www.modpython.org/pipermail/mod_python/2005-
January/017129.html)

Reading through the release notes for Python 2.3.5
I see:
 Bug #754449: threading.Thread will no longer mask 
exceptions raised during interpreter shutdown with 
another exception caused by attempting to output the 
initial exception. This fix also includes a backport of rev. 
1.41 from HEAD. 

This might be the problem as it seems to involve the 
porting of 2.4 threading code back to the 2.3 tree.

I've attached a Java file which shows the problem when 
using JEP.
The error output is:
Exception in thread Thread-1:
Traceback (most recent call last):
  File C:\Python24\Lib\threading.py, line 442, in 
__bootstrap
  File string, line 5, in run
IOError: file() constructor not accessible in restricted 
mode

2.4.1c1 (#63, Mar 10 2005, 10:36:41) [MSC v.1310 32 
bit (Intel)]
Creating file from main thread...
Done
Creating file from sub thread...
Done


--

Comment By: Brett Cannon (bcannon)
Date: 2005-04-16 12:21

Message:
Logged In: YES 
user_id=357491

To answer the comment on bug #754449 and the email I got
from someone, there is no way my fix for that bug would
cause this.  I only touched the 'threading' module, nothing
else.  That is in pure Python and thus has no direct way of
modifying what does and does not execute in restricted mode.
 If I understand how restricted execution works that is all
set at the C level.

Plus the fix only deals with the teardown code; it in no way
interfaces with how threads are executed.  All changed code
come after the thread and completed execution.  The only
thing it does ahead of time is store a reference to stdout.

In other words it ain't my fault to the best of my
knowledge.  =)

--

Comment By: Alan Davies (goatpunch)
Date: 2005-03-30 22:24

Message:
Logged In: YES 
user_id=967140

The same problem definately does occur with mod_python, 
I've found it to occur with Python 2.3.5 and 2.4 on Win32:

http://www.modpython.org/pipermail/mod_python/2005-
March/017802.html

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1163563group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1184380 ] example broken in section 1.12 of Extending Embedding

2005-04-16 Thread SourceForge.net
Bugs item #1184380, was opened at 2005-04-16 14:36
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1184380group_id=5470

Category: Documentation
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: bamoore (bamoore)
Assigned to: Nobody/Anonymous (nobody)
Summary: example broken in section 1.12 of Extending  Embedding

Initial Comment:
In section 1.12 of Extending and Embedding the Python
Interpreter Release 2.4, the example (spammodule) does
not compile on linux with distutils.  I get the following:
~/sandbox/python/c_api_test$ python2.4 spam-setup.py build
running build
running build_ext
building 'spam' extension
creating build
creating build/temp.linux-i686-2.4
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall
-Wstrict-prototypes -fPIC -I/usr/include/python2.4 -c
spammodule.c -o build/temp.linux-i686-2.4/spammodule.o
spammodule.c:7: error: conflicting types for
`PySpam_System'
spammodule.h:21: error: previous declaration of
`PySpam_System'
error: command 'gcc' failed with exit status 1

I think the solution is to change line 12 of the
spammodule header file listing from:

#define PySpam_System_PROTO (char *command)

to:

#define PySpam_System_PROTO (const char *command)

as that seems to compile for me.  (though not tested
from another C extension).

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1184380group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1183468 ] check for return/yield outside function is wrong

2005-04-16 Thread SourceForge.net
Bugs item #1183468, was opened at 2005-04-14 20:53
Message generated for change (Comment added) made by logistix
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1183468group_id=5470

Category: Parser/Compiler
Group: AST
Status: Open
Resolution: None
Priority: 5
Submitted By: Neil Schemenauer (nascheme)
Assigned to: Nobody/Anonymous (nobody)
Summary: check for return/yield outside function is wrong

Initial Comment:
The code currently uses c_nestlevel.  That's incorrect
as this example code demonstrates:

 class A:
... return
... 
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: Error when calling the metaclass bases
PyClass_New: dict must be a dictionary

Not sure what the fix is but I wanted to file a bug so
it doesn't get forgotten.

--

Comment By: logistix (logistix)
Date: 2005-04-16 17:05

Message:
Logged In: YES 
user_id=699438

Patch 1184418 is (sortof) posted.  SF is giving me grief when 
I try to do it as a real attachment though.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1183468group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1184449 ] Read-only property attributes raise wrong exception

2005-04-16 Thread SourceForge.net
Bugs item #1184449, was opened at 2005-04-16 19:16
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1184449group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Barry A. Warsaw (bwarsaw)
Assigned to: Raymond Hettinger (rhettinger)
Summary: Read-only property attributes raise wrong exception

Initial Comment:
In
http://mail.python.org/pipermail/python-dev/2005-April/052681.html
I describe how attributes defined as properties raise
inconsistent errors depending on whether the property
is defined in C or Python.  By default in C, you'll get
a TypeError while in Python you'll get an AttributeError.

I think both should raise AttributeErrors. Here is a
patch against Python 2.4 which should be ported to 2.5
(and possibly 2.3 if we care).


--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1184449group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1184449 ] Read-only property attributes raise wrong exception

2005-04-16 Thread SourceForge.net
Bugs item #1184449, was opened at 2005-04-16 19:16
Message generated for change (Comment added) made by bwarsaw
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1184449group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Barry A. Warsaw (bwarsaw)
Assigned to: Raymond Hettinger (rhettinger)
Summary: Read-only property attributes raise wrong exception

Initial Comment:
In
http://mail.python.org/pipermail/python-dev/2005-April/052681.html
I describe how attributes defined as properties raise
inconsistent errors depending on whether the property
is defined in C or Python.  By default in C, you'll get
a TypeError while in Python you'll get an AttributeError.

I think both should raise AttributeErrors. Here is a
patch against Python 2.4 which should be ported to 2.5
(and possibly 2.3 if we care).


--

Comment By: Barry A. Warsaw (bwarsaw)
Date: 2005-04-16 19:23

Message:
Logged In: YES 
user_id=12800

Well, I was going to attach a patch, but it seems SF is
borked and won't let me upload anything (yes the stupid
checkbox was checked).  The patch is simple though: change
PyExc_TypeError to PyExc_AttributeError on lines 147 and 202
in Objects/descrobject.c (rev 2.38)

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1184449group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com