ANN: Amara XML Toolkit 1.0b2

2005-04-21 Thread Uche Ogbuji
http://uche.ogbuji.net/tech/4Suite/amara
ftp://ftp.4suite.org/pub/Amara/

Changes in this release:

* More mutation API improvements (del and assignment can now be used
  with elements as well as attributes) [1][2][3]
* Slight improvements in 4Suite XSLT compatability (still some
  remaining issues)
* Bug fixes

[1] http://copia.ogbuji.net/blog/2005-04-17/Amara_gets
[2] http://copia.ogbuji.net/blog/2005-04-18/Elements_v
[3] http://copia.ogbuji.net/blog/2005-04-18/Deletion_a

Amara XML Toolkit is a collection of Python tools for XML processing--
not just tools that happen to be written in Python, but tools built from
the ground up to use Python idioms and take advantage of the many
advantages of Python.

Amara builds on 4Suite [http://4Suite.org], but whereas 4Suite focuses
more on literal implementation of XML standards in Python, Amara
focuses on Pythonic idiom.  It provides tools you can trust to conform
with XML standards without losing the familiar Python feel.

The components of Amara are:

* Bindery: data binding tool (a very Pythonic XML API)
* Scimitar: implementation of the ISO Schematron schema language for
XML; converts Schematron files to Python scripts
* domtools: set of tools to augment Python DOMs
* saxtools: set of tools to make SAX easier to use in Python
* Flextyper: user-defined datatypes in Python for XML processing

There's a lot in Amara, but here are highlights:

Amara Bindery: XML as easy as py


Bindery turns an XML document into a tree of Python objects
corresponding to
the vocabulary used in the XML document, for maximum clarity.  For
example,
the document 

monty
  python spam=eggsWhat do you mean bleh/python
  python ministry=abuseBut I was looking for argument/python
/monty

Becomes a data structure such that you can write

binding.monty.python.spam

In order to get the value eggs or

binding.monty.python[1]

In order to get the value But I was looking for argument.

There are other such tools for Python, and what makes Anobind unique is
that it's driven by a very declarative rules-based system for binding
XML to the Python data.  You can register rules that are triggered by
XPattern expressions specialized binding behavior.  It includes XPath
support and supports mutation.  Bindery is very efficient, using SAX
to generate bindings.

Scimitar: Schematron for Pytthon


Merged in from a separate project, Scimitar is an implementation of ISO
Schematron that compiles a Schematron schema into a Python validator
script.

You typically use scimitar in two phases.  Say you have a schematron
schema schema1.stron and you want to validate multiple XML files
against it, instance1.xml, instance2.xml, instance3.xml.

First you run schema1.stron through the scimitar compiler script,
scimitar.py:

scimitar.py schema1.stron

The generated file, schema1.py, can be used to validate XML instances:

python schema1.py instance1.xml

Which emits a validation report.

Amara DOM Tools: giving DOM a more Pythonic face


DOM came from the Java world, hardly the most Pythonic API possible.
Some DOM-like implementations such as 4Suite's Domlettes mix in some
Pythonic idiom. Amara DOM Tools goes even further.

Amara DOM Tools feature pushdom, similar to xml.dom.pulldom, but
easier to use.  It also includes Python generator-based tools for
DOM processing, and a function to return an XPath location for
any DOM node.

Amara SAX Tools: SAX without the brain explosion


Tenorsax (amara.saxtools.tenorsax) is a framework for linerarizing SAX
logic so that it flows more naturally, and needs a lot less state
machine wizardry.

License
---

Amara is open source, provided under the 4Suite variant of the Apache
license.  See the file COPYING for details.

Installation


Amara requires Python 2.3 or more recent and 4Suite 1.0a4 or more
recent.  Make sure these are installed, unpack Amara to a convenient
location and run

python setup.py install


-- 
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-announce-list

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-20, Bill Mill schreef [EMAIL PROTECTED]:
 On 20 Apr 2005 13:39:42 GMT, Antoon Pardon [EMAIL PROTECTED] wrote:
 Op 2005-04-20, Bill Mill schreef [EMAIL PROTECTED]:
 
 You write this af if other solutions can't be consistent.

 Propose one, and I won't write it off without thinking, but my bias is
 way against it from experience. Knowledge gets scattered across the
 program,

Knowledge always gets scattered across the program. The end
index can vary endlessly but that doesn't seem to worry
you. So why is a varying start index so worrysome?

 unless you're defining the start index every time you use the
 list, which seems no better than adding an offset to me.

I don't see why the start index can't be accessible through
a method or function just like the length of a list is now.

My favourite would be a range method so we would have
the following idiom:

  for i in lst.range():
do something with lst[i]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-20, Roy Smith schreef [EMAIL PROTECTED]:
 Antoon Pardon  [EMAIL PROTECTED] wrote:
Op 2005-04-20, Roy Smith schreef [EMAIL PROTECTED]:
 Antoon Pardon [EMAIL PROTECTED] wrote:

 Personnaly I would like to have the choice. Sometimes I prefer to
 start at 0, sometimes at 1 and other times at -13 or +7.

 Argggh.  Having two (or more!) ways to do it, would mean that every time I 
 read somebody else's code, I would have to figure out which flavor they are 
 using before I could understand what their code meant.  That would be evil.

This is nonsens. table[i] = j, just associates value j with key i.
That is the same independend from whether the keys can start from
0 or some other value. Do you also consider it more ways because
the keys can end in different values?

 There are certainly many examples where the specific value of the
 first key makes no difference.  A good example would be

 for element in myList:
 print element

 On the other hand, what output does

myList = [spam, eggs, bacon]
print myList[1]

 produce?  In a language where some lists start with 0 and some start
 with 1, I don't have enough information just by looking at the above
 code.

Yes you have. The fact that a language allows a choice doesn't
contradict there is a default, when no choice is specified.

My preference would be that it would produce spam, because
if you want the *first* element, you want the element
associated withe the key 1.

Or maybe the language would force you to give a start index,
so that you would have to write:

  MyList = [3 - spam, eggs, bacon]

End of course the language would provide instances or methods
so you could ask what the first index was.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Dan Bishop
[EMAIL PROTECTED] wrote:

 What languages besides Python use the Python slicing convention?

Java uses it for the substring method of strings.

 In C starting at
 0 may be justified because of the connection between array
subscripting
 and pointer arithmetic, but Python is a higher-level language where
 such considerations are less relevant.

Maybe less relevant, but relevant nonetheless.

First, there's the desire for familiarity.  Many Python programmers are
also C programmers, and that fact has had an influence on the
development of the language.  That's why we write x += 0x20 rather
than x := x + $20.  Why not array indexing as well?

More importantly, there are reasons for counting from zero that have
nothing to do with pointers.

The biggest reason involves modular arithmetic: r=n%d satifies 0 = r 
d, which conveniently matches Python's array syntax.

   DAY_NAMES = [Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]
   def weekday_name(date):
  return DAY_NAMES[date.toordinal() % 7]

Modular arithmetic's preference for 0-based counting goes beyond array
indexing.  For example, consider our notation for time, from 00:00:00
to 23:59:59.

   def time_add(time, delta):
  
  time  = an (hour, minute, second) tuple for a time of day
  delta = an (hour, minute, second) tuple for an amount of time

  Returns time+delta, as an (hour, minute, second) tuple.
  
  hour = time[0] + delta[0]
  minute = time[1] + delta[1]
  second = time[2] + delta[2]
  # Normalize the time
  second = ((hour * 60) + minute) * 60 + second
  minute, second = divmod(second, 60)
  hour, minute = divmod(minute, 60)
  hour %= 24
  return hour, minute, second

Imagine that the time notation went from 01:01:01 to 24:60:60.  Try
writing a time_add function for that.  The only simple way I can think
of is to temporarily convert to zero-based notation!

   def time_add(time, delta):
  # Add like terms and convert to zero-based notation.
  hour = time[0] + delta[0] - 1
  minute = time[1] + delta[1] - 1
  second = time[2] + delta[2] - 1
  # Normalize the time
  second = ((hour * 60) + minute) * 60 + second
  minute, second = divmod(second, 60)
  hour, minute = divmod(minute, 60)
  hour %= 24
  # Convert back to one-based notation on output
  return hour + 1, minute + 1, second + 1

 Along the same lines, I think the REQUIREMENT that x[0] rather than
 x[1] be the first element of list x is a mistake. At least the
 programmer should have a choice, as in Fortran or VBA.

If you really want 1-based arrays, just do what most BASIC programmers
do: Ignore x[0].

 months = [None, Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec]
 print months[4]
Apr

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


regarding main function

2005-04-21 Thread praba kar
Dear All,

   I want to know the difference between calling 
a function directly and through main function
compose() 

if __name__ == __main__:
compose()

 


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: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-20, Peter Hansen schreef [EMAIL PROTECTED]:
 Terry Hancock wrote:
 However, I used to make off by one errors all the time in both C and 
 Fortran,
 whereas I hardly ever make them in Python.

 This should probably be the overriding concern in this
 case.

 I can't remember the last time I made an off-by-one error
 in Python (or, really, whether I ever have), whereas I
 can't remember the last C program I wrote which didn't have
 one.

I do so frequently.

I often have to process files where each line is a record,
each record having a number of fields seperated with a
delimiter.

So the idiom for treating such files has become

  for line in the_file:
lst = line.split(delimiter)

The problem is that the fields in lst are associated
with a number that is off by one as they are normally
counted. If I go and ask my colleague which field
contains some specific data and he answers:
the 5th, I have to remind my self I want lst[4]

This is often a cause for errors.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-20, Terry Hancock schreef [EMAIL PROTECTED]:
 On Wednesday 20 April 2005 07:52 am, Antoon Pardon wrote:
 Personnaly I would like to have the choice. Sometimes I prefer to
 start at 0, sometimes at 1 and other times at -13 or +7.

 Although I would classify that as a rare use case.  So, it ought
 to be possible to do it, but not necessarily easy.

The -13 and +7 may be rare cases, but I wouldn't call one as a
start index a rare case. I often get data in files where each line
is a record with delimited fields. When I ask which field contains
certain data, I get an answer that depends on counting starting
with one. So starting with one as index would seem the more natural
choice here.

As far as I'm concerend, 0 as a starting index is a rare use
case. In the programs I write about 45% is a natural 1 for
first index, about 50% is a don't care and 5% is a natural
0 first index and some fraction is others. So yes in most
of my programs 0 as a starting index works fine, but that
is because in a lot of programs it doesn't matter much
which would be the first index.

Now I can understand that for others the 0 as a natural
start index is more frequent, but if we have two frequent
use cases, it seems to me the language should provide the
choice more easily as it does now.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Raymond Hettinger
[Antoon Pardon]
 I don't see why the start index can't be accessible through
 a method or function just like the length of a list is now.

 My favourite would be a range method so we would have
 the following idiom:

   for i in lst.range():
 do something with lst[i]

After going to all that trouble, you might as well also get the value at that
position:

for i, x in enumerate(lst):
do something with lst[i] also known as x


Raymond Hettinger


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


Re: regarding main function

2005-04-21 Thread [EMAIL PROTECTED]
if you run in the same file there is no difference.

Block under __main__ will be executed if you run that file only but
if you import that file from another file, then if you don't put your
code inside __main__ your code it will be executed (this is not what
you want).

Example:

You have 1 file called mydll.py
inside mydll you have :

def func1():
   print 'Helo world'

# you want to test your func1()
func1() # when you run you get 'Helo world'

then you have another file called MyCode.py which you like to call
func1(), inside this file you have this code:
import mydll
mydll.func1()

# you hope you get 'Helo World'
# In fact you get :
# 'Helo World'
# 'Helo World'
--
This happened because when you import mydll python will execute all
code in mydll including the one you put it for test.

So to overcome this problem if you want to test your code put inside
block __main__, next time you import your mydll it won't execute any
codes inside __main__

Hope this help.

Pujo

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


Re: PyObject_New not running tp_new for iterators?

2005-04-21 Thread Gregory Bond
I wrote:
[snip]
 What am I missing?
The fundamental problem is that this:
   if (!(ro = PyObject_New(MyIter, MyIterType)))
  return NULL;
is really only a malloc() - it doesn't call the tp_new function at all. 
 This is not really clear in the 2.3 version of the C API document that 
I was consulting - the 2.4 version is much clearer.

I have no idea how to do in C all the things that calling a class 
constructor in Python does.  Am I supposed to be calling tp_new  
tp_init directly?

In the end, this particular class really only needs to be created from a 
factory function, so I removed the tp_new member altogether and just 
wrote a C function to initialise the object, and called that from the C 
factory function.

[The above is not particular to the fact that my class is an iterator - 
all C classes have the same behaviour.  My test of a plain-old class 
probably looked like it worked due to lucky memory patterns.]

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


deprecation of has_key?

2005-04-21 Thread nicksjacobson
I haven't heard of any plans to deprecate the dictionary has_key
method, as the in keyword makes it obsolete.

i.e.
if key in dict:

instead of
if dict.has_key():


Is there some reason to keep has_key?

--Nick

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-20, Terry Hancock schreef [EMAIL PROTECTED]:
 On Wednesday 20 April 2005 12:28 pm, Roy Smith wrote:
 Terry Hancock wrote:
  I used to make off by one errors all the time in both C and Fortran,
  whereas I hardly ever make them in Python. 
 
 Part of the reason may be that most loops over lists involve
 iterators, 

 both endpoints are mentioned explicitly.  C++/STL also uses iterators,
 but the syntax is repulsive.

 That's true of course.  It's more likely to show up in manipulating
 lists or strings.  And Python provides a much richer environment for
 processing strings, so one has to deal with explicit indexing much
 less.

 But I still think that I make fewer error per instance of dealing with
 intervals. It's rare that I even have to think about it much when
 writing such a thing.   Negative indexing also helps a lot.

I'm anbivallent about negative indexes. It helps a lot, but can
be annoying a lot too. IMO it deters from the, its easier to
be forgiven than to get permission, style of programming.

It happens rather regularly that I need to do some calculations
and if the start conditions were good, I get a valid index for
a list and otherwise I get an invalid index. From this specification
the following seems a natural way to program

  try:
index = calculate(...)
lst[index] = ...
...
  except IndexError
...

But of course this doesn't work because a negative index in this
case is an invalid index but python allows it.

I sometimes think python should have been more explicite here,
using a marker for the start-index and end-index, may '^' and
'$'. So if you wanted the last element you had to write:

  lst[$]

And for the next to last element:

  lst[$ - 1]


This would make accessing list elements counted from the rear
almost just as easy as it is now but wouldn't interfere with
the ask forgiveness programming style.

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


Re: Lex

2005-04-21 Thread jozo
I NEED HELP!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Ron
[EMAIL PROTECTED] wrote:
Many people I know ask why Python does slicing the way it does.
Can anyone /please/ give me a good defense/justification???
I'm referring to why mystring[:4] gives me
elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element).
Many people don't like idea that 5th element is not invited.
(BTW, yes I'm aware of the explanation where slicing
is shown to involve slices _between_ elements.  This
doesn't explain why this is *best* way to do it.)
Chris
Hi Chris,
What I've found is foreword slicing with positive stepping is very 
convenient for a lot of things. :-)

But when you start trying to use reverse steps, it can get tricky.
There are actually 4 different ways to slice and dice. So we have a 
pretty good choice. So the trick is to match the slice method to what 
you need, and also use the correct index's for that method.

Where s = 'abcd'
With s[i,j]
Foreword slices index, forward steps
a,  b,  c,  d
i=  0,  1,  2,  3
j=  1,  2,  3,  4
s[0,4] = 'abcd'
s[1,3] = 'bc'
Foreword slice index (-steps)
a,  b,  c,  d
i=  0,  1,  2,  3
j= -5, -4, -3, -2
s[3,-5] = 'dcba'
s[2,-4] = 'cb'
Reverse slice index (+steps)
a,  b,  c,  d
i= -4, -3, -2, -1
j=  1,  2,  3,  4
s[-4,4] = 'abcd'
s[-3,3] = 'bc'
Reverse slice index (-steps)
a,  b,  c,  d
i= -4, -3, -2, -1
j= -5, -4, -3, -2
s[-1,-5] = 'dcba'
s[-2,-4] = 'cb'
(Maybe this could be made a little more symetrical for Python 3000?)
Cheers,
Ron_Adam
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Paul Rubin
Antoon Pardon [EMAIL PROTECTED] writes:
 I sometimes think python should have been more explicite here,
 using a marker for the start-index and end-index, may '^' and
 '$'. So if you wanted the last element you had to write:
 
   lst[$]
 
 And for the next to last element:
 
   lst[$ - 1]

I like this.  I don't know how many times I've gotten screwed by
wanting the n'th element from the last for variable n, and saying
lst[n] then realizing I have a bug when n=0.  lst[$-n] works perfectly.
-- 
http://mail.python.org/mailman/listinfo/python-list


python LEX

2005-04-21 Thread jozo
I have to work on python lexical definition in Lex. I spent lots of my
time to find regular expresions written for Lex of Python language but
nothing.
Can somebody help me?

I nEED hELP 


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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-21, Raymond Hettinger schreef [EMAIL PROTECTED]:
 [Antoon Pardon]
 I don't see why the start index can't be accessible through
 a method or function just like the length of a list is now.

 My favourite would be a range method so we would have
 the following idiom:

   for i in lst.range():
 do something with lst[i]

 After going to all that trouble, you might as well also get the value at that
 position:

 for i, x in enumerate(lst):
 do something with lst[i] also known as x

No you wouldn't, enumerate always starts with 0.

So if you write a class with list-like behaviour except that the
start index can be different from 0, enumerate is useless
because lst[i] won't be x in that case.

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


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-21 Thread Bill Davy
Hi Scott,
Nice idea.  Tried that but no more information about where the file was 
(not) found (see below).
But many thanks for a useful flag.  I did not see them in the documentation. 
What should I be lkooking for? [StopPres: Ah ha -h why did I not think of 
that?]
Bill

# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python24\lib\site.pyc matches C:\Python24\lib\site.py
import site # precompiled from C:\Python24\lib\site.pyc
# C:\Python24\lib\os.pyc matches C:\Python24\lib\os.py
import os # precompiled from C:\Python24\lib\os.pyc
import nt # builtin
# C:\Python24\lib\ntpath.pyc matches C:\Python24\lib\ntpath.py
import ntpath # precompiled from C:\Python24\lib\ntpath.pyc
# C:\Python24\lib\stat.pyc matches C:\Python24\lib\stat.py
import stat # precompiled from C:\Python24\lib\stat.pyc
# C:\Python24\lib\UserDict.pyc matches C:\Python24\lib\UserDict.py
import UserDict # precompiled from C:\Python24\lib\UserDict.pyc
# C:\Python24\lib\copy_reg.pyc matches C:\Python24\lib\copy_reg.py
import copy_reg # precompiled from C:\Python24\lib\copy_reg.pyc
# C:\Python24\lib\types.pyc matches C:\Python24\lib\types.py
import types # precompiled from C:\Python24\lib\types.pyc
# C:\Python24\lib\locale.pyc matches C:\Python24\lib\locale.py
import locale # precompiled from C:\Python24\lib\locale.pyc
import _locale # builtin
# C:\Python24\lib\codecs.pyc matches C:\Python24\lib\codecs.py
import codecs # precompiled from C:\Python24\lib\codecs.pyc
import _codecs # builtin
import encodings # directory C:\Python24\lib\encodings
# C:\Python24\lib\encodings\__init__.pyc matches 
C:\Python24\lib\encodings\__ini
t__.py
import encodings # precompiled from C:\Python24\lib\encodings\__init__.pyc
# C:\Python24\lib\encodings\aliases.pyc matches 
C:\Python24\lib\encodings\aliase
s.py
import encodings.aliases # precompiled from 
C:\Python24\lib\encodings\aliases.py
c
# C:\Python24\lib\encodings\cp1252.pyc matches 
C:\Python24\lib\encodings\cp1252.
py
import encodings.cp1252 # precompiled from 
C:\Python24\lib\encodings\cp1252.pyc
# C:\Python24\lib\warnings.pyc matches C:\Python24\lib\warnings.py
import warnings # precompiled from C:\Python24\lib\warnings.pyc
# C:\Python24\lib\linecache.pyc matches C:\Python24\lib\linecache.py
import linecache # precompiled from C:\Python24\lib\linecache.pyc
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
Type help, copyright, credits or license for more information.
 import sys
# C:\Python24\lib\encodings\cp850.pyc matches 
C:\Python24\lib\encodings\cp850.py

import encodings.cp850 # precompiled from 
C:\Python24\lib\encodings\cp850.pyc
 import SHIP
Traceback (most recent call last):
  File stdin, line 1, in ?
ImportError: No module named SHIP
 import SHIP_d
Traceback (most recent call last):
  File stdin, line 1, in ?
ImportError: No module named SHIP_d
 import _SHIP
Traceback (most recent call last):
  File stdin, line 1, in ?
ImportError: No module named _SHIP
 import _SHIP_d
Traceback (most recent call last):
  File stdin, line 1, in ?
ImportError: DLL load failed: The specified module could not be found.
 _SHIP_d
Traceback (most recent call last):
  File stdin, line 1, in ?
NameError: name '_SHIP_d' is not defined

Scott David Daniels [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Bill Davy wrote:
 Thanks Jaime,

 I'm making gradual progress and am finding it quite satisfying.  Resorted 
 to tracing Python in MSVC6 to see what it was trying to IMPORT, which is 
 a bit heavy but thank heavens for the sources.
 You might try running python from a command window and running it -v as 
 in:

 python -v prog.py -args ...

 --Scott David Daniels
 [EMAIL PROTECTED] 


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


Re: building a small calculator

2005-04-21 Thread Steve Holden
[EMAIL PROTECTED] wrote:
Thats great info. Thanks.
I guess I would know about this if I read through all the manuals, but
I'm awefull at reading that kind of stuff. I'll just have to plow
through it somehow.
Take your time. Feel free to ask questions. Simon Brunning recommended 
the tutor list - those guys really can help, and it's not like using 
that list bars you from posting on comp.lang.python.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python LEX

2005-04-21 Thread Tim Daneliuk
jozo wrote:
I have to work on python lexical definition in Lex. I spent lots of my
time to find regular expresions written for Lex of Python language but
nothing.
Can somebody help me?
I nEED hELP 


http://systems.cs.uchicago.edu/ply/
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: inner sublist positions ?

2005-04-21 Thread tiissa
Bernard A. wrote:
 maybe have you some better / faster ideas / implementations ? or even
 a more pythonic to help me learning that

You may want to look at string matches algorithm (a good review: [1]).
In particular there are classics like Boyer-Moore and some involving
minimal automatons similar to your regular expression ideas.

[1] http://www-igm.univ-mlv.fr/~lecroq/string/index.html

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


Re: python LEX

2005-04-21 Thread Tim Daneliuk
Tim Daneliuk wrote:
jozo wrote:
I have to work on python lexical definition in Lex. I spent lots of my
time to find regular expresions written for Lex of Python language but
nothing.
Can somebody help me?
I nEED hELP
http://systems.cs.uchicago.edu/ply/
Whoops - I did not read your question carefully enough ... sorry, cannot
help with what you actually asked.
Slinks off ...
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Can an object of a C type have random members added? tp_dictoffset?

2005-04-21 Thread Gregory Bond
One of the cool things about Python is the ability to decorate objects 
with random extra members:
	class C:
		def __init__(self):
			self.foo = 0
	c = C()
	c.bar = 1

I have a class implemented in C using tp_members to specify (read-only) 
access to data members in the C struct. I'd like to be able to do the 
decoration trick with objects of this class.  Is this possible?

[The documentation for tp_dictoffset eseems to hint that this is 
possible. how do I use it?]
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread Maxim Kasimov
1. comment for debug
   It can be used in the same way, as the comments for debugging are used, but it will be 
easier than to use  or ''', or using features of text-editors,
   when it is necessary to comment piece of code which already contains ''' or/and 
 strings already, or there is another #-comments.
   Using goto, you do not need to edit a code, which is unfamiliar to you.
2. obfuscators
   goto can be used in the same way, as many of java-obfuscators do
Speaking in other words:
  1) goto exempts from necessity to install new software (it is critical for 
remote working, for example, installing X11 may be impossible at all)
  2) enables to make new, better software (better obfuscators)
--
Best regards,
Maxim Kasimov
mailto: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Jython in Ant Build Process

2005-04-21 Thread Simon Brunning
On 4/21/05, Maurice LING [EMAIL PROTECTED] wrote:
 I am looking for a way to use Jython in Ant build process. I have some
 pure Python scripts (not using any C extensions) that I'll like to
 incorporate into Java using Jython. I heard that this can be done but
 you can I set up Ant to do this? Sorry, I'm no expert with Ant.

http://www.pycs.net/users/177/stories/11.html

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread Tim Daneliuk
Reinhold Birkenfeld wrote:
John Bokma wrote:
Mage wrote:

praba kar wrote:

Dear All,
 In Python what is equivalent to goto statement

You shouldn't use goto in high-level languages.
Nonsense
+1

Thank you!
Above all your claim is well justified. These brilliant arguments
you have put forth really explain in a magnificent way why goto is a
sane addition to any HLL.
Reinhold
OK - Here's some reasoning that may illuminate it.  We could, in theory,
reduce any language to the minimal Boehm  Jacopini control structures
(iirc there were only four).  In effect, anything beyond these is
syntactic sugar.  IOW, feel free to use a minimalist Turing Machine
to implement your next 100,000 line program.
I, on the other hand, have a really hard time finding infinite tapes (in
both directions) and a suitably fast tape reader to implement such
ideas. (I also seem to recall that any digital circuit can be
implemented with nothing more than AND and NOT gates, but I'd rather
not, thanks - I don't have enough probes on my oscilloscope to debug
that kind of hardware.)
Control structures/directives evolve to solve real problems. 'goto',
properly used, can actually clarify code, especially when dealing with
exceptions and the like. Oh, we may rename it and call it 'break' or
'try/except' or whatever suits the language author's fancy, but the
concept is similar, if not identical.  'goto' certainly could be
synthesized in Python with the appropriate try/except hierarchy
and custom exceptions, but in many cases this would *really* be overkill -
a simple 'goto' would be considerably simpler *and* probably easier
to understand.  Note that I am not arguing for 'goto' in Python,
merely trying to respond to your point about why it is does not inherently
appropriate for HLLs.
Some HLLs almost have to have it by definition.  I cut my teeth as programmer
writing for embedded realtime systems in a HLL (PL/M).  While you could,
in theory, completely avoid 'goto' in a realtime environment, it would
make all manner of practical programming problems kind of ugly to implement.
BTW, all modern systems come complete with 'goto' implemented in
*hardware* - they're called interrupts.
More to the point, I have seen some really tortured code written in the
name of maintaining religious purity of some kind (Structure, Object
Orientation,...). While language constructs can promote better- or
worse code structuring, at the end of the day, programming is still the
expression of human thought. Some people think clearly, some don't, and
this has little to do with just what language structures are in use.
Python is elegant at almost every level, and I am certainly not
arguing for 'goto' in the language.  But to reflexively assume that
it has *no* place in a modern HLL is, I think, a bit overstated.
I must now 'goto' sleep ... and I cannot think of a better way
to express this...
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyGTK on Mouse over event ?

2005-04-21 Thread [EMAIL PROTECTED]
the POINTER MOTION MASK doesn't do the trick either. This is the first
time i'm using python and pyGTK and it's really sad to see that a
simple mouseover is hard to program. :s

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


Re: Enumerating formatting strings

2005-04-21 Thread Steve Holden
Michael Spencer wrote:
Andrew Dalke wrote:
I see you assume that only \w+ can fit inside of a %()
in a format string.  The actual Python code allows anything
up to the balanced closed parens.
Gah! I guess that torpedoes the regexp approach, then.
Thanks for looking at this
Michael
While Andrew may have found the fatal flaw in your scheme, it's worth 
pointing out that it works just fine for my original use case.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python 2.3.2 for PalmOS available

2005-04-21 Thread Fraca7
On Tue, 19 Apr 2005 08:03:15 -0700, Lucio Torre wrote:

 Do you have any experience on PODS? The whole thing is based on
 Codewarrior and Codewarrior for palm is dead.

Nope. Actually, I'm kind of reluctant to use IDEs and it seems PODS is
targeted towards Eclipse users; I'd rather use prc-tools since I'm used to
the GNU development tools.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deprecation of has_key?

2005-04-21 Thread Steve Holden
[EMAIL PROTECTED] wrote:
I haven't heard of any plans to deprecate the dictionary has_key
method, as the in keyword makes it obsolete.
i.e.
if key in dict:
instead of
if dict.has_key():
Is there some reason to keep has_key?
Two words: backward compatibility. To lose that method now would break 
thousands of existing programs. The 2.4 library would probably 
experience breakage too ... let's see:

$ find /lib/python2.4/ -name *.py -exec grep has_key {} \; | wc -l
587
Oops!
The method might disappear in Python 3.0, when we will be allowed to 
break backward compatibility - you are correct in saying it's no longer 
necessary.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python instances

2005-04-21 Thread Bengt Richter
On Wed, 20 Apr 2005 08:33:48 -0400, Kent Johnson [EMAIL PROTECTED] wrote:

[EMAIL PROTECTED] wrote:
 Guess i shouldn't think of the __init__(self) function as a constructor
 then.

No, that's not it. You shouldn't think of variables defined outside of a 
method as instance variables.

In Java for example you can write something like

public class MyClass {
 private List list = new ArrayList();

 public void add(Object x) {
 list.add(x);
 }
}

In this case list is a member variable of MyClass instances; 'this' is 
implicit in Java.

In Python, if you write something that looks similar, the meaning is different:

class MyClass:
 list = []

 def add(self, x):
 self.list.append(x)

In this case, list is an attribute of the class. The Java equivalent is a 
static attribute. In 
Python, instance attributes have to be explicitly specified using 'self'. So 
instance attributes 
have to be bound in an instance method (where 'self' is available):

class MyClass:
 def __init__(self):
 self.list = []

 def add(self, x):
 self.list.append(x)


The following shows nothing static anywhere, yet a class has been defined, an 
instance created, and
__init__ called with initial value, and the value retrieved as an attribute of 
the returned instance,
and it's all an expression.

  type('C', (), {'__init__': lambda 
  self,v:setattr(self,'foo',v)})('hello').foo
 'hello'

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Raymond Hettinger
  [Antoon Pardon]
  I don't see why the start index can't be accessible through
  a method or function just like the length of a list is now.
 
  My favourite would be a range method so we would have
  the following idiom:
 
for i in lst.range():
  do something with lst[i]
 
  After going to all that trouble, you might as well also get the value at
that
  position:
 
  for i, x in enumerate(lst):
  do something with lst[i] also known as x

 No you wouldn't, enumerate always starts with 0.

You don't get it.  Your proposed list-like class indicates its start index.
enumerate() can be made to detect that start value so that the above code always
works for both 0-based and 1-based arrays.


Raymond Hettinger







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


Dictionary question.

2005-04-21 Thread hawkesed
Hi,
  I am semi new to Python. Here is my problem : I have a list of 100
random integers. I want to be able to construct a histogram out of the
data. So I want to know how many 70's, 71's, etc. I can't figure out
how to do this. A dictionary is supposedly can do key value pairs
right? I want to be able to see if say 75 is in the data structure, and
what its value is, then increment its value as I go through the list
finding items.
  I am sure there is a way to do this. Is a dictionary what I should be
using? Thanks for any help. Hope this makes sense, its getting very
late here.
Regards all.
Ed

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-21, Raymond Hettinger schreef [EMAIL PROTECTED]:
  [Antoon Pardon]
  I don't see why the start index can't be accessible through
  a method or function just like the length of a list is now.
 
  My favourite would be a range method so we would have
  the following idiom:
 
for i in lst.range():
  do something with lst[i]
 
  After going to all that trouble, you might as well also get the value at
 that
  position:
 
  for i, x in enumerate(lst):
  do something with lst[i] also known as x

 No you wouldn't, enumerate always starts with 0.

 You don't get it.  Your proposed list-like class indicates its start index.
 enumerate() can be made to detect that start value so that the above code 
 always
 works for both 0-based and 1-based arrays.

Oh you mean if it would be made a buildin class.

Personnally I would still prefer my range solution. I often find
enumerate gives me too much. Often enough I want to assign new values
to the elements in the list. I have no need for the old value, that
is also provided by enumerate.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Steve Holden
[EMAIL PROTECTED] wrote:
Terry Hancock wrote:
snip
So I like Python's slicing because it bites *less* than intervals
in C or Fortran.
I disagree. Programming languages should not needlessly surprise
people, and a newbie to Python probably expects that x[1:3] =
[x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95,
Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention,
and I don't know of Fortran or R programmers who complain (don't follow
Matlab enough to say). There are Python programmers, such as the OP and
me, who don't like the Python convention. What languages besides Python
use the Python slicing convention?
The principle of least surprise is all very well, but needless surprise 
of newbies is a dangerous criterion to adopt for programming language 
design and following it consistently would lead to a mess like Visual 
Basic, which grew by accretion until Microsoft realized it was no longer 
tenable and broke backward compatibility.

Along the same lines, I think the REQUIREMENT that x[0] rather than
x[1] be the first element of list x is a mistake. At least the
programmer should have a choice, as in Fortran or VBA. In C starting at
0 may be justified because of the connection between array subscripting
and pointer arithmetic, but Python is a higher-level language where
such considerations are less relevant.
But Pythonicity required that there should be one obvious way to do 
something. How obvious is having two ways? Then when you read code you 
would continually be asking yourself is this a one-based or a 
zero-based structure?, which is not a profitable use of time.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Reinhold Birkenfeld
Antoon Pardon wrote:

 I sometimes think python should have been more explicite here,
 using a marker for the start-index and end-index, may '^' and
 '$'. So if you wanted the last element you had to write:
 
   lst[$]
 
 And for the next to last element:
 
   lst[$ - 1]
 
 
 This would make accessing list elements counted from the rear
 almost just as easy as it is now but wouldn't interfere with
 the ask forgiveness programming style.

How would you pass this argument to __getitem__?
What would be allowed, only '$-x' or also '$+x' or what else?
What type would '$' be?

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


Re: goto statement

2005-04-21 Thread Reinhold Birkenfeld
Maxim Kasimov wrote:

1) goto exempts from necessity to install new software
 (it is critical for remote working, for example, installing X11 may be
 impossible at all)

Attributing the need for a language feature to restrictions of your ambience
is hilarious.

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


Re: Dictionary question.

2005-04-21 Thread Simon Brunning
On 21 Apr 2005 02:47:42 -0700, hawkesed [EMAIL PROTECTED] wrote:
   I am semi new to Python. Here is my problem : I have a list of 100
 random integers. I want to be able to construct a histogram out of the
 data. So I want to know how many 70's, 71's, etc. I can't figure out
 how to do this. A dictionary is supposedly can do key value pairs
 right? I want to be able to see if say 75 is in the data structure, and
 what its value is, then increment its value as I go through the list
 finding items.
   I am sure there is a way to do this. Is a dictionary what I should be
 using? Thanks for any help. Hope this makes sense, its getting very
 late here.

Sounds like homework, so I'll just say that yes, a dictionary would be
ideal for what you are trying to do.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary question.

2005-04-21 Thread Steve Holden
Simon Brunning wrote:
On 21 Apr 2005 02:47:42 -0700, hawkesed [EMAIL PROTECTED] wrote:
 I am semi new to Python. Here is my problem : I have a list of 100
random integers. I want to be able to construct a histogram out of the
data. So I want to know how many 70's, 71's, etc. I can't figure out
how to do this. A dictionary is supposedly can do key value pairs
right? I want to be able to see if say 75 is in the data structure, and
what its value is, then increment its value as I go through the list
finding items.
 I am sure there is a way to do this. Is a dictionary what I should be
using? Thanks for any help. Hope this makes sense, its getting very
late here.

Sounds like homework, so I'll just say that yes, a dictionary would be
ideal for what you are trying to do.
And I will add that you have two different cases to cope with: the first 
time you come across a particular value you have to create a new element 
with a value of one. The second and subsequent times you have to add one 
to an existing element.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-21, Reinhold Birkenfeld schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:

 I sometimes think python should have been more explicite here,
 using a marker for the start-index and end-index, may '^' and
 '$'. So if you wanted the last element you had to write:
 
   lst[$]
 
 And for the next to last element:
 
   lst[$ - 1]
 
 
 This would make accessing list elements counted from the rear
 almost just as easy as it is now but wouldn't interfere with
 the ask forgiveness programming style.

 How would you pass this argument to __getitem__?

Well assuming lst.last, was the last index of lst, __getitem__
would get lst.last and lst.last - 1 passed.

 What would be allowed, only '$-x' or also '$+x' or what else?

Any expression where an int is allowed.

 What type would '$' be?

It would be an int.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-21, Steve Holden schreef [EMAIL PROTECTED]:
 [EMAIL PROTECTED] wrote:
 Terry Hancock wrote:
 
 snip
 
So I like Python's slicing because it bites *less* than intervals
 
 in C or Fortran.
 
 I disagree. Programming languages should not needlessly surprise
 people, and a newbie to Python probably expects that x[1:3] =
 [x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95,
 Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention,
 and I don't know of Fortran or R programmers who complain (don't follow
 Matlab enough to say). There are Python programmers, such as the OP and
 me, who don't like the Python convention. What languages besides Python
 use the Python slicing convention?
 
 The principle of least surprise is all very well, but needless surprise 
 of newbies is a dangerous criterion to adopt for programming language 
 design and following it consistently would lead to a mess like Visual 
 Basic, which grew by accretion until Microsoft realized it was no longer 
 tenable and broke backward compatibility.

 Along the same lines, I think the REQUIREMENT that x[0] rather than
 x[1] be the first element of list x is a mistake. At least the
 programmer should have a choice, as in Fortran or VBA. In C starting at
 0 may be justified because of the connection between array subscripting
 and pointer arithmetic, but Python is a higher-level language where
 such considerations are less relevant.
 
 But Pythonicity required that there should be one obvious way to do 
 something. How obvious is having two ways?

How obvious is that lists can be any length? Do you consider it
an unbounded number of ways, that lists can be any length?

Like users have a choice in how long they make a list, they
should have a choice where the indexes start. (And that
shouldn't be limited to 0 and 1).

 Then when you read code you 
 would continually be asking yourself is this a one-based or a 
 zero-based structure?, which is not a profitable use of time.

No you wouldn't. If you have the choice you just take the start
index that is more natural. Sometimes that is 0 sometimes that
is 1 and other times it is some whole other number. The times
I had the opportunity to use such structures, the question of
whether it was zero-based or one-based, rarely popped up.
Either it was irrelevant or it was clear from what you were
processing.

That you are forced to use zero-based structures, while the
problem space you are working on uses one-based structures
is a far bigger stumbling block where you continually have
to be aware that the indexes in your program are one off
from the indexes the problem is expressed in.

The one obvious way is to use the same index scheme as the
one that is used in the specification or problem setting.
Not to use always zero no matter what.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Reinhold Birkenfeld
Antoon Pardon wrote:
 Op 2005-04-21, Reinhold Birkenfeld schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:

 I sometimes think python should have been more explicite here,
 using a marker for the start-index and end-index, may '^' and
 '$'. So if you wanted the last element you had to write:
 
   lst[$]
 
 And for the next to last element:
 
   lst[$ - 1]
 
 
 This would make accessing list elements counted from the rear
 almost just as easy as it is now but wouldn't interfere with
 the ask forgiveness programming style.

 How would you pass this argument to __getitem__?
 
 Well assuming lst.last, was the last index of lst, __getitem__
 would get lst.last and lst.last - 1 passed.

Then it would be an alias for len(lst)-1 ?

 What would be allowed, only '$-x' or also '$+x' or what else?
 
 Any expression where an int is allowed.

Okay.

 What type would '$' be?
 
 It would be an int.

Where would it be allowed? Only in subscriptions?

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


Re: python LEX

2005-04-21 Thread Miki Tebeka
Hello jozo,

 I have to work on python lexical definition in Lex. I spent lots of my
 time to find regular expresions written for Lex of Python language but
 nothing.
 Can somebody help me?
http://www.antlr.org/grammar/list (search for Python)

You can search in projects like Pyrex and Parrot for their parser
implementation.

HTH.
--

Miki Tebeka [EMAIL PROTECTED]
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys


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

Re: memory profiler?

2005-04-21 Thread Diez B. Roggisch
Peter Hansen wrote:

 John Reese wrote:
 Is there a memory or heap profiler for python programs?  So that, for
 example, if a program was bloating over time I could see how many of
 each object there were and maybe even where the references were?
 
 The gc module has a variety of helpful features
 like that.

I created a qt-based memory analyzer on top of the gc module. I plan to
release it soon - it has been helpful to me for a few projects. Its a
client-server application that collects data through an in-process running
thread that delivers object histograms. The client fetches these and allows
to display the development of objects based various criteria over the time.
It can also record these data for offline-analysis. So far the in-proccess
threads communicate their histograms either by pyro or xmlrpc servers.  

Unfortunately debugging ZOPE with the xmlrpc server lead to a mem-leak
itself :( - so currently I'm no confident enough to release it. 
-- 
Regards,

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


Re: deprecation of has_key?

2005-04-21 Thread Steve Holden
Luis Bruno wrote:
Hello,
Steve Holden wrote:
Two words: backward compatibility. To lose that method now would break 
thousands of existing programs. The 2.4 library would probably 
experience breakage too ... let's see:

$ find /lib/python2.4/ -name *.py -exec grep has_key {} \; | wc -l
587

Is there any interest in changing that to the key in dict sintax?
The general principles on which maintenance is based for Python decree 
that such changes not be made gratuitously: the code as it is works now, 
so it is only worth changing when has_key is removed.

If a module were being edited for other reasons there would be no 
objection to removal of the has_key usage then, but the chance of 
breakage due to careless modification is high enough to want to avoid it 
unless really *necessary*.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Antoon Pardon
Op 2005-04-21, Reinhold Birkenfeld schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
 Op 2005-04-21, Reinhold Birkenfeld schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:

 I sometimes think python should have been more explicite here,
 using a marker for the start-index and end-index, may '^' and
 '$'. So if you wanted the last element you had to write:
 
   lst[$]
 
 And for the next to last element:
 
   lst[$ - 1]
 
 
 This would make accessing list elements counted from the rear
 almost just as easy as it is now but wouldn't interfere with
 the ask forgiveness programming style.

 How would you pass this argument to __getitem__?
 
 Well assuming lst.last, was the last index of lst, __getitem__
 would get lst.last and lst.last - 1 passed.

 Then it would be an alias for len(lst)-1 ?

In the context of current python lists yes. But if you would
go further and allow lists to start from an other index than
0 then not.

 What would be allowed, only '$-x' or also '$+x' or what else?
 
 Any expression where an int is allowed.

 Okay.

 What type would '$' be?
 
 It would be an int.

 Where would it be allowed? Only in subscriptions?

Yes, the idea would be that the brackets indicate a
scope where $ would be the last index and ^ would
be the first index. So if you wanted the middle
element you could do: lst[(^ + $) // 2]

But outsides the brackets the scope where this
has any meaning wouldn't be present.

Not that I think this idea has any chance. Already
I can hear people shout that this is too perlish.


But here is another idea.

Sometime ago I read about the possibility of python
acquiring a with statement. So that instead of having
to write:

  obj.inst1 ...
  obj.inst2 ...
  obj.inst1 ...

You could write:

  with obj:
.inst1 ...
.inst2 ...
.inst1 ...


If this would get implemented we could think of a left bracked
as implicitely exucting a with statement.  If we then had a list
like class where the start-index could be different from zero and
which had properties first and last indicating the first and last
index we could then write something like:

  lst[.last]  for the last element or
  lst[.last - 1]  for the next to last element.
  lst[.first] for the first element
  lst[(.first + .last) // 2]  for the middle element

Maybe this makes the proposal again pythonic enough to get
a little consideration.

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


Re: goto statement

2005-04-21 Thread Sergei Organov
Maxim Kasimov [EMAIL PROTECTED] writes:

 1. comment for debug
 
 It can be used in the same way, as the comments for debugging are
 used, but it will be easier than to use  or ''', or using
 features of text-editors, when it is necessary to comment piece of
 code which already contains ''' or/and  strings already, or
 there is another #-comments. Using goto, you do not need to edit a
 code, which is unfamiliar to you.

... and then you end up with situation when another goto jumps directly
into the body of the code you've just commented with your goto. Happy
debugging!

BTW, don't you want comefrom statement to be added to the language
to make debugging even more fun?

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


Python Mayavi Problem

2005-04-21 Thread Alexej Goehring








Hi,



I read your Mayavi question from about a year ago, because I
have exactly the same problem. I believe it has to do with windows, because I have
seen it work under Linux. Did anyone reply to your query and if so, do you know
why the screen goes red?



I attached your email so that you know what I am talking
about.





Thanks



Alexej



Hello NG, I'm trying to follow the mayavi documentation in order to runmayavi from python. In Chapter 4. Using MayaVi from Python, there isa simple example like this:# generate the data.from Numeric import *import scipyx = (arange(50.0)-25)/2.0y = (arange(50.0)-25)/2.0r = sqrt(x[:,NewAxis]**2+y**2)z = 5.0*scipy.special.j0(r) # Bessel function of order 0# now dump the data to a VTK file.import pyvtk# Flatten the 2D array data as per VTK's requirements.z1 = reshape(transpose(z), (-1,))point_data = pyvtk.PointData(pyvtk.Scalars(z1))grid = pyvtk.StructuredPoints((50,50, 1), (-12.5, -12.5, 0), (0.5,0.5, 1))data = "" point_data)data.tofile('test.vtk')import mayaviv = mayavi.mayavi() # create a MayaVi window.d = v.open_vtk('test.vtk', config=0) # open the data file.# The config option turns on/off showing a GUI control for thedata/filter/module.# load the filters.f = v.load_filter('WarpScalar', config=0) n = v.load_filter('PolyDataNormals', 0)n.fil.SetFeatureAngle (45) # configure the normals.# Load the necessary modules.m = v.load_module('SurfaceMap', 0)a = v.load_module('Axes', 0)a.axes.SetCornerOffset(0.0) # configure the axes module.o = v.load_module('Outline', 0)v.Render() # Re-render the scene.Everything goes fine, but at the end I obtain the mayavi windowcompletely red (without the expected surface/image), and when I clickon this window I get different errors depending on which Python editorI run:1) Pythonwin: Error: Microsoft Visual C++ Runtime Error. EverythingCrashes. After this, I get a vtkwindow coming up and showing me thealways-present error message from mayavi:Generic Warning: In /debian/stage/vtk-4.2.4/Rendering/vtkTkRenderWidget.cxx, line 638A TkRenderWidget is being destroyed before it associatedvtkRenderWindowis destroyed. This is very bad and usually due to the order in which objects are being destroyed. Always destroy the vtkRenderWindow beforedestroying the user interface componentsI don't know why, but with mayavi this warning is EXTREMELY common...2) IDLE for Python: All is frozen, nothing happen, I have to killPython;3) Python Command Line: No windows appears, nothing happen.Moreover, I would like to be able to compile my Python application toa standalone EXE file by using py2exe, but py2exe complains about somemissing modules (either from mayavi and for scipy), and the createdEXE does not start.I have installed Python using the Enthought Installer for Python (withlots of site-packages inside), located at:http://www.enthought.com/python/I'm running Win2000, without administrator privileges (if this canmake differences).Does anyone have an idea?Thanks for every suggestion.Andrea.








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

Re: goto statement

2005-04-21 Thread Sergei Organov
Tim Daneliuk [EMAIL PROTECTED] writes:

[...]

 Some HLLs almost have to have it by definition.  I cut my teeth as programmer
 writing for embedded realtime systems in a HLL (PL/M).  While you could,
 in theory, completely avoid 'goto' in a realtime environment, it would
 make all manner of practical programming problems kind of ugly to implement.
 BTW, all modern systems come complete with 'goto' implemented in
 *hardware* - they're called interrupts.

Well, I'm writing for embedded realtime systems in C/C++ and have never
encountered a single need to use goto. Comparing interrupts to goto
doesn't make any sense for me either. For example, most architectures
have 'branch' *hardware* instructions that are much more close
equivalents to goto than interrupts are, but that doesn't justify use of
goto in high-level languages in any way.

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


Re: Lex

2005-04-21 Thread Diez B. Roggisch
jozo wrote:

 I NEED HELP!!!

Shouting won't give you help. 

Reading this

http://www.catb.org/~esr/faqs/smart-questions.html

and coming back with a more elaborate question might.

-- 
Regards,

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


Re: Define Constants

2005-04-21 Thread codecraig
Thanks for the input.

i am renaming my module to be customthing.  I noticed that is how many
python modules are, so I will stick to the convention.

Thanks for the help.

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


Design advice for unit test asserters

2005-04-21 Thread Gary
I'm working on a project where I'm doing various file manipulations.
I'm not familiar with the idioms are common or good for this situation,
so I'd appreciate advice and suggestions.

Question 1:  A number of checks apply to a set of files.  So I'm
wondering whether to have something like:

 def test_SomeTest(...):
 ...
 self.AssertAllFilesExist(fileList)

or

 def test_SomeTest(...):
 ...
 [ self.AssertFileExists(f) for f in fileList ]

In a statically typed, tiny method design approach, the former would be
preferred.  But in Python the latter seems easy enough and more
natural.  And I'm wondering if I'm missing some other Python idiom that
would be even better.

Question 2:  A more complicated example:  My object defines its own
conditions that can be queried, e.g.

 def test_SomeTest(...):
 myObject.DoSomething()
 self._assert(myObject.isFileTypeQ(someFile))

but the parameter someFile is often an expression that should be
encapsulated into the assertion.  This gives me two possibilities:  I
can define a stand-alone query that takes myObject as a parameter:

 def AssertIsTypeQ(theObjectBeingTested, rawFileInfo):
 someComputedFile = DoStuff(rawFileInfo)
 return theObjectBeingTested.isFileTypeQ(someComputedFile)

and then call it from within various tests as:

 self._assert(AssertIsFileTypeQ(myObject, someFile)

or I can define an intermediate unit test case:

 class myTester(unittest.TestCase):
def AssertIsFileTypeQ(self, rawFileInfo):
  someComputedFile = DoStuff(rawFileInfo)
  self.theObject.isFileTypeQ(someComputedFile)

and then define my test cases as

 class test_MyObjectX(myTester):

   def test_Sometest():
  self.theObject = ClassBeingTested()
  self.theObject.DoSomething()
  self.AssertIsFileTypeQ(someFile)

With these simple cases, this seems like six of one and a half dozen of
the other.  But the problem grows, in that there are several of these
assertions, and they often need to be applied to lists of things.  At
one point I was getting really complicated by abstracting out both the
looping and the computed file names, passing in a functor containing
the simple test and the name (for the message).  I gave up on this and
now I'm leaning towards the first, but again, I wonder if I'm missing a
better or more natural way to solve this problem.

Thanks,

Gary

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


Re: Python instances

2005-04-21 Thread Kent Johnson
Bengt Richter wrote:
The following shows nothing static anywhere, yet a class has been defined, an 
instance created, and
__init__ called with initial value, and the value retrieved as an attribute of 
the returned instance,
and it's all an expression.
  type('C', (), {'__init__': lambda 
self,v:setattr(self,'foo',v)})('hello').foo
 'hello'
I have no idea what point you are trying to make, except maybe that it is possible to obfuscate a 
simple class definition.

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


Re: goto statement

2005-04-21 Thread Diez B. Roggisch
 implement. BTW, all modern systems come complete with 'goto' implemented
 in *hardware* - they're called interrupts.

That's not goto - that is a asynchronous function call - much closer related
to multithreading.

In an interrupt, you can always jump back to the main program using rte
(return from interrupt) - or whatever that is called on the respective
processor.

Of course you _can_ alter all sorts of state, including the stackframe and
the PC when inside an interrupt - thus you can create goto for e.g.
multithreading. But I wouldn't call that builtin-goto...


-- 
Regards,

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


Re: goto statement

2005-04-21 Thread Maxim Kasimov
Sergei Organov wrote:
Maxim Kasimov [EMAIL PROTECTED] writes:

1. comment for debug
   It can be used in the same way, as the comments for debugging are
   used, but it will be easier than to use  or ''', or using
   features of text-editors, when it is necessary to comment piece of
   code which already contains ''' or/and  strings already, or
   there is another #-comments. Using goto, you do not need to edit a
   code, which is unfamiliar to you.

 and then you end up with situation when another goto jumps directly
into the body of the code you've just commented with your goto. Happy
debugging!
BTW, don't you want comefrom statement to be added to the language
to make debugging even more fun?
if you can't control what you do - it is you private problem, not mine. 
Is't it?
--
Best regards,
Maxim Kasimov
mailto: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Jython in Ant Build Process

2005-04-21 Thread Kent Johnson
Maurice LING wrote:
I am looking for a way to use Jython in Ant build process. I have some 
pure Python scripts (not using any C extensions) that I'll like to 
incorporate into Java using Jython. I heard that this can be done but 
you can I set up Ant to do this? Sorry, I'm no expert with Ant.
The ant script task lets you embed Jython in Ant build files using Bean Scripting Framework. See 
the Ant docs for script for some (non-Jython) examples.

The links in the Ant docs are out-of-date.
BSF is here: http://jakarta.apache.org/bsf/manual.html
Jython is here: http://www.jython.org
Kent
--
http://mail.python.org/mailman/listinfo/python-list


freeze and expat

2005-04-21 Thread Operation Latte Thunder
I am playing around with jabberpy, and on a lark decided to try to freeze
one of the included samples, test_client.py

The freeze/build worked fine, but when I attempted to run the resulting
binary, I got an error hinting that it couldn't find parsers.expat:

canal:/home/chris/build% ./test_client
Traceback (most recent call last):
  File /home/chris/build/../test_client.py, line 15, in ?
import jabber
  File /usr/lib/python2.3/site-packages/jabber.py, line 67, in ?
import xmlstream
  File /usr/lib/python2.3/site-packages/xmlstream.py, line 36, in ?
import xml.parsers.expat
ImportError: No module named parsers.expat

I have tried this with python2.3.5 and 2.4.1, and played around with the -m
option on the freeze cmd line, but no joy.  Google seems to delight in
frustating me...

In a much simpler case than the test_client.py, the following also fails:

import xml.parsers.expat
print Hello world

Though it runs from the interpreter... ideas?

-- 
[EMAIL PROTECTED]   | Roma Invicta!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-21 Thread Jaime Wyant
If you're really desperate, write a python script that changes -

#include python.h

to

#ifdef _DEBUG
 #undef _DEBUG
 #include python.h
 #define _DEBUG
#else
 #include python.h
#endif

Then run the script each time you generate a new wrapper file and
everything ought to be OK.

jw

On 4/20/05, Bill Davy [EMAIL PROTECTED] wrote:
 Hi Jaime,
 
 SWIG-1.3.24/Lib/python/python.swg does not have the [#include python.h]
 but has lots of Pythonesque includes but all *.swg
 Still, I am hoping I can make MSVC6 do some of the work of putting things in
 the right place for Release and Debug builds.
 
 Rgds,
 Bill.
 
 Jaime Wyant [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]...
 I fight the python24_d.lib problem with swig daily.  The way I got
 around it was to modify swig's python configuration module.  Mine was
 located at
 
 /lib/swig1.3/python/python.swg
 
 (I'm using cygwin)
 
 At the top, I changed
 
 #include python.h
 
 to
 
 #ifdef _DEBUG
   #undef _DEBUG
   #include python.h
   #define _DEBUG
 #else
   #include python.h
 #endif
 
 Somewhere in the includes, python uses a pragma telling the MSVC
 compiler which library to link the object files against.  Because
 you're building a _DEBUG build, you magically get the python24_d.lib
 library.
 
 hth,
 jw
 
 On 4/18/05, Bill Davy [EMAIL PROTECTED] wrote:
  I downlaoded and installed
  http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi
 
  I'm trying to build an extension using SWIG 1.3.24 and the linker needs
  python24_d.lib (I do not have the DLL either).  I've not found it in any
 of
  the
  downloads.
 
  So I tried to download the source to build it myself.  Of
  http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tar.bz2 and
  http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz, WinZip (9.0 SR1)
  just says Error reading header after processing 0 entries.
 
  Additionally, I've had no joy downloading the unzipper
  (ftp://sources.redhat.com/pub/bzip2/v102/bzip2-102-x86-win32.exe) from the
  site cited for the unzipper (http://sources.redhat.com/bzip2/).  It
 flashed
  up a
  black console window momentarily.
 
  Oh, this is so frustrating! :-(
 
  Can anyone point me in the right direction?
 
  And then I can get to grips with my work.
 
  tia
  Bill
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 --
 

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


Re: Design advice for unit test asserters

2005-04-21 Thread Kent Johnson
Gary wrote:
I'm working on a project where I'm doing various file manipulations.
I'm not familiar with the idioms are common or good for this situation,
so I'd appreciate advice and suggestions.
Question 1:  A number of checks apply to a set of files.  So I'm
wondering whether to have something like:
 def test_SomeTest(...):
 ...
 self.AssertAllFilesExist(fileList)
or
 def test_SomeTest(...):
 ...
 [ self.AssertFileExists(f) for f in fileList ]
Personally I avoid using list comprehensions with side-effects; if I don't actually want the list I 
write it out:
  for f in fileList:
self.AssertFileExists(f)

Question 2:  A more complicated example:  My object defines its own
conditions that can be queried, e.g.
 def test_SomeTest(...):
 myObject.DoSomething()
 self._assert(myObject.isFileTypeQ(someFile))
but the parameter someFile is often an expression that should be
encapsulated into the assertion.  This gives me two possibilities:  I
can define a stand-alone query that takes myObject as a parameter:
 def AssertIsTypeQ(theObjectBeingTested, rawFileInfo):
 someComputedFile = DoStuff(rawFileInfo)
 return theObjectBeingTested.isFileTypeQ(someComputedFile)
I would write this method to actually do the assertion:
 def AssertIsTypeQ(theObjectBeingTested, rawFileInfo):
 someComputedFile = DoStuff(rawFileInfo)
 self.assert_(theObjectBeingTested.isFileTypeQ(someComputedFile))
and then call it from within various tests as:
  self.AssertIsFileTypeQ(myObject, someFile)
I think of it as extending the standard assertions with domain-specific ones.
I often write methods called checkSomething() that do a bit of work and check the result. So I might 
 actually call the above method something like checkDoStuffIsFileTypeQ().

So, the convention I use is
- write assertSomething() primitives that just check a condition
- write checkSomething() methods that do some work and check the result
- build the actual tests using the above
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: XML parsing per record

2005-04-21 Thread Willem Ligtenberg
I'll first try it using SAX, because I want to have as little dependancies
as possible. I already have BioPython as a dependancy. And I personally
don't like to install lot's of packages for a program to work. So I don't
want to impose that on other people.
But thanks anyway and I might go for the cElementTree later on, if the
ordinary SAX proves to slow...

On Wed, 20 Apr 2005 08:03:00 -0400,
Kent Johnson wrote:

 Willem Ligtenberg wrote:
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?
 
 The XML file I need to parse contains information about genes.
 So the first element is a gene and then there are a lot sub-elements with
 sub-elements. I only need some of the informtion and want to store it in
 my an object called gene. Lateron this information will be printed into a
 file, which in it's turn will be fed into some other program.
 This is an example of the XML
 ?xml version=1.0?
 !DOCTYPE Entrezgene-Set PUBLIC -//NCBI//NCBI Entrezgene/EN 
 NCBI_Entrezgene.dtd
 Entrezgene-Set
   Entrezgene
 snip
   /Entrezgene
 /Entrezgene-Set
 
 This should get you started with cElementTree:
 
 import cElementTree as ElementTree
 
 source = 'Entrezgene.xml'
 
 for event, elem in ElementTree.iterparse(source):
  if elem.tag == 'Entrezgene':
  # Process the Entrezgene element
  geneid = 
 elem.findtext('Entrezgene_track-info/Gene-track/Gene-track_geneid')
  print 'Gene id', geneid
 
  # Throw away the element, we're done with it
  elem.clear()
 
 Kent

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


Re: Define Constants

2005-04-21 Thread beliavsky
A recipe for Constants in Python by Alex Martelli is at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 .

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


recording data between [ and ]

2005-04-21 Thread rbt
Output from 'netstat -b' on a win2003 server will show what binary is 
responsible for the connection. For example, it may list something like 
this along with other connection specific data:

[lsass.exe]
[System]
[firefox.exe]
[iexplorer.exe]
How might I process the output so that anything within brackets is 
recorded to a log file of my own making? I know how to parse and record 
things to a file, I don't know how to look make '[' and ']' appear as 
special characters so that I can record what's between them.

Basically, I want a script that will read output and stop each time it 
encounters a '[' and record until it gets to ']' where upon it would 
stop recording and then proceed on repeating the above operation as it 
goes thru the remaining data.

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


Private class?

2005-04-21 Thread codecraig
Hi,
  First, I come from a Java background.

  Ok, so I have this idea that I want to create an EventBus...basically
a central class where objects can register themselves as listeners for
different events.  This central class also has methods so that objects
can fire events.  Something like this...

Say we have object MrTree and object MotherNature.  MrTree listens for
EVENT_GROW_LEAVES.  So, when MrTree hears about EVENT_GROW_LEAVES,
MrTree will do just that, grow some leaves.  So, while our python app
is running, MotherNature needs to tell MrTree to grow leaves.  I am
suggesting something like this...

1. MrTree has a method, growLeaves()

2. MrTree registers for the event, EventBus.register(MrTree,
EVENT_GROW_LEAVES)

3. MotherNature fires grow leaves, EventBus.fire(EVENT_GROW_LEAVES)

4. MrTree's growLeaves method gets called by EventBus.

Now, in Java I would make EventBus a Singleton so that only one
instance of it would exist.  And I would have MrTree implement
EventListener interface, where the interface defines a method like
growLeaves().  So when MotherNature tells the EventBus to fire the
event, EventBus loops through it's list of listeners and calls,
growLeaves()

How would I go about doing this in Python?  Here is my quick idea

class EventListener:
def eventOccurred(self, eventType): pass

class MrTree(EventListener):
def __init__(self):
EventListener.__init__(self)
EventBus.register(self, EventBus.EVENT_GROW_LEAVES)

def eventOccurred(self, eventType):
if eventType == EventBus.EVENT_GROW_LEAVES:
print Growing Leaves

class EventBus:
EVENT_GROW_LEAVES = 0

__listeners = {}

def register(listener, eventType):
if __listeners.has_key(eventType):
curListeners = __listeners.get(eventType)
curListeners.append(listener)
else:
__listeners[eventType] = [listener]

def fire(eventType):
if __listeners.has_key(eventType):
x = __listeners.get(eventType)
for l in x:
l.eventOccurred(eventType)

class MotherNature:
def doSomeStuff():
print doing whatever Mother Nature does...
EventBus.fire(EventBus.EVENT_GROW_LEAVES)


...so that is what I am thinking.  However, i guess my issue is how to
make EventBus a singleton or prevent it from being instaniated and
making it's methods statically accessible.

thanks.

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


Re: XML parsing per record

2005-04-21 Thread Willem Ligtenberg
Sorry I just decided that I want to use your solution, but I am wondering
is cElemenTree in expat or is that something different?

On Wed, 20 Apr 2005
08:03:00 -0400, Kent Johnson wrote:

 Willem Ligtenberg wrote:
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?
 
 The XML file I need to parse contains information about genes.
 So the first element is a gene and then there are a lot sub-elements with
 sub-elements. I only need some of the informtion and want to store it in
 my an object called gene. Lateron this information will be printed into a
 file, which in it's turn will be fed into some other program.
 This is an example of the XML
 ?xml version=1.0?
 !DOCTYPE Entrezgene-Set PUBLIC -//NCBI//NCBI Entrezgene/EN 
 NCBI_Entrezgene.dtd
 Entrezgene-Set
   Entrezgene
 snip
   /Entrezgene
 /Entrezgene-Set
 
 This should get you started with cElementTree:
 
 import cElementTree as ElementTree
 
 source = 'Entrezgene.xml'
 
 for event, elem in ElementTree.iterparse(source):
  if elem.tag == 'Entrezgene':
  # Process the Entrezgene element
  geneid = 
 elem.findtext('Entrezgene_track-info/Gene-track/Gene-track_geneid')
  print 'Gene id', geneid
 
  # Throw away the element, we're done with it
  elem.clear()
 
 Kent

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


Strings

2005-04-21 Thread Dan
I've having trouble coming to grip with Python strings.

I need to send binary data over a socket.  I'm taking the data from a
database.  When I extract it, non-printable characters come out as a
backslash followed by a three numeric characters representing the
numeric value of the data.  I guess this is what you would call a raw
Python string.  I want to convert those four characters ( in C-think,
say \\012 ) into a single character and put it in a new string.

There's probably a simple way to do it, but I haven't figured it out.
What I've done so far is to step through the string, character by
character.  Normal characters are appended onto a new string.  If I
come across a '\' character, I look for the next three numeric
characters.  But I don't know how to convert this code into a single
character and append it onto the new string.

I'm sure what I'm doing is long and convoluted.  Any suggestions would
be appreciated.

Dan

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


Re: Private class?

2005-04-21 Thread PA
On Apr 21, 2005, at 15:13, codecraig wrote:
...so that is what I am thinking.  However, i guess my issue is how to
make EventBus a singleton or prevent it from being instaniated and
making it's methods statically accessible.
Not directly related to your question, but... you may want to take a  
look at NSNotification  Co. for, er, inspiration :)

Introduction to Notifications
http://developer.apple.com/documentation/Cocoa/Conceptual/ 
Notifications/index.html

Here is a -gasp- Java implementation as well:
http://dev.alt.textdrive.com/file/ZOE/Frameworks/SZFoundation/ 
SZNotification.java

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


Re: XML parsing per record

2005-04-21 Thread Simon Brunning
On 4/21/05, Willem Ligtenberg [EMAIL PROTECTED] wrote:
 Sorry I just decided that I want to use your solution, but I am wondering
 is cElemenTree in expat or is that something different?

Nope, cElemenTree is  very much its own man. See
http://effbot.org/zone/celementtree.htm.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
--
http://mail.python.org/mailman/listinfo/python-list


Re: XML parsing per record

2005-04-21 Thread Paul McGuire
Don't assume that just because you have a 2.4G XML file that you have
2.4G of data.  Looking at these verbose tags, plus the fact that the
XML is pretty-printed (all those leading spaces - not even tabs! - add
up), I'm guessing you only have about 5-10% actual data, and the rest
is just XML tagging/untagging and spaces.  (For example, 373 characters
used to represent a date/time - this is a sin!)

As XML goes, this looks pretty dead easy to parse with non-XML parser
means.  It looks like all of your leaf nodes open and close on the same
line, which would be easy to extract with regexp's or pyparsing.
Especially since you mention I only need some of the informtion, you
don't even have to build a full document tree representation.  SAX
parsers would also be good, since you could only trigger on the
matching subset of tags that you are really interested in.  Lastly, you
could even try a pyparsing approach.  I usually don't recommend
pyparsing for XML since there are already many good XML-targeted tools
out there, but it is very easy to throw together something in pyparsing
that extracts, say, all of the object-id_id entries, or all of the
gene-source structures.  What is the subset of information you are
looking to extract?

-- Paul

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


__del__ and reference count problem

2005-04-21 Thread flupke
Hi,
i'm starting work and a simple database layer and wanted to use the 
__del__ to open and close a connection. However, i get an erro when 
executing this script:

class Table:
refcount = 0
def __init__(self, name):
self.name = name
print table %s  % repr(self)
Table.refcount += 1
print refcount = %s % str(Table.refcount)
def __del__(self):
Table.refcount -= 1
if (Table.refcount == 0):
print Last table standing
else:
print There is/are still %d table(s) left. % Table.refcount
def __getitem__(self,item):
return not implemented
def howMany(self):
if (Table.refcount == 1):
print Only 1 table
else:
print There are %d tables active. % Table.refcount
if __name__ == '__main__':
suppliera = Table(suppliers)
supplierb = Table(suppliers)
print Supplier returned from a %s: %s % (1, suppliera[1])
print Supplier returned from b %s: %s % (2, supplierb[2])
suppliera.howMany()
supplierb.howMany()
This produces the following output and error:
table __main__.Table instance at 0x008D5C10
refcount = 1
table __main__.Table instance at 0x008D5C38
refcount = 2
Supplier returned from a 1: not implemented
Supplier returned from b 2: not implemented
There are 2 tables active.
There are 2 tables active.
Exception exceptions.AttributeError: 'NoneType' object has no attribute 
'refcount' in bound method Table.__del__ of __main__.Table instance 
at 0x008D5C10 ignored
Exception exceptions.AttributeError: 'NoneType' object has no attribute 
'refcount' in bound method Table.__del__ of __main__.Table instance 
at 0x008D5C38 ignored

What am i doing wrong?
Thanks
Benedict
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread Grant Edwards
On 2005-04-21, Sergei Organov [EMAIL PROTECTED] wrote:

 Well, I'm writing for embedded realtime systems in C/C++ and
 have never encountered a single need to use goto.

I have encountered situations in C programs where the best
thing to use was a goto.  Those situations have always been
handled beutifully by a raise in Python.

 Comparing interrupts to goto doesn't make any sense for me
 either. For example, most architectures have 'branch'
 *hardware* instructions that are much more close equivalents
 to goto than interrupts are, but that doesn't justify use of
 goto in high-level languages in any way.

I agree.  The jump or branch instruction corresponds
exactly to a goto.  An interrupt is more like a signal and a
signal handler in C.  Sort of like an asynchronous function
call or thread context switch.

-- 
Grant Edwards   grante Yow!  Now that we're
  at   in LOVE, you can BUY
   visi.comthis GOLDFISH for a 48%
   DISCOUNT.
-- 
http://mail.python.org/mailman/listinfo/python-list


python classes/file structure

2005-04-21 Thread codecraig
What is the best/common way to structure ur python code for an
application?

For example...if I create some custom GUI widgets I have this

C:\stuff
-- gui
--: MyCustomWidget.py
--: TestWidgets.py

so MyCustomWidget.py has one class, class MyCustomWidget: ...

so from TestWidgets.py i have to do this

from gui import *

widget = gui.MyCustomWidget.MyCustomWidge()

...seems weird, how should I structure this?  Is it not common to have
one class in a .py?

thanks

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


Re: Strings

2005-04-21 Thread keirr
I'd use the int and chr casts.  e.g.,

new_string = 
a = '012'
new_string += chr(int(a))

Just in case the 012 is an octal code I'll mention that to cast to int
in general you can pass the base, as in int('034',8) or int('AF',16)

Cheers,

 Keir.

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


Regular Expressions - Python vs Perl

2005-04-21 Thread codecraig
Hi,
  I am interested in regular expressions and how Perl and Python
compare.  Particulary, I am interested in performance (i.e. speed),
memory usage, flexibility, completeness (i.e. supports simple and
complex regex operations...basically is RegEx a strong module/library
in Python?)

  Anyone have any information on this?  Any numbers, benchmarks?

Thanks so much.  I know this is a python user group...but try to be has
un-biased as you can.

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


Re: recording data between [ and ]

2005-04-21 Thread Peter Hansen
rbt wrote:
Output from 'netstat -b' on a win2003 server will show what binary is 
responsible for the connection. For example, it may list something like 
this along with other connection specific data:

[lsass.exe]
[System]
[firefox.exe]
[iexplorer.exe]
How might I process the output so that anything within brackets is 
recorded to a log file of my own making? I know how to parse and record 
things to a file, I don't know how to look make '[' and ']' appear as 
special characters so that I can record what's between them.
Does this help?
 import re

 s = '''stuff   [lsass.exe]
... [System]  more stuff
... x [firefox.exe] ..
... '''

 re.findall(r'\[([^]]*)\]', s)
['lsass.exe', 'System', 'firefox.exe']
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread John Bokma
Do Re Mi chel La Si Do wrote:

 +1

I am modded up :-D

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread John Bokma
Reinhold Birkenfeld wrote:

 John Bokma wrote:
 Mage wrote:
 
 praba kar wrote:
 
Dear All,

   In Python what is equivalent to goto statement

  

 You shouldn't use goto in high-level languages.
 
 Nonsense
 
 Thank you!
 
 Above all your claim is well justified.

You are probably smart enough to think of several situations that 
justify the use of a goto (or something that is a goto in disguise, like 
an early return in a function, a break or a continue, or a switch).

One can abuse a goto in any language, like every other language 
construction. But don't make it a shouldn't like a law.

Some people take Dijkstra too serious. Learn to think for yourself, I am 
sure he did.

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strings

2005-04-21 Thread Peter Hansen
Dan wrote:
I've having trouble coming to grip with Python strings.
I need to send binary data over a socket.  I'm taking the data from a
database.  When I extract it, non-printable characters come out as a
backslash followed by a three numeric characters representing the
numeric value of the data.  I guess this is what you would call a raw
Python string.  I want to convert those four characters ( in C-think,
say \\012 ) into a single character and put it in a new string.
Does this help?
 s = 'foo \\012 bar'

 s.decode('string-escape')
'foo \n bar'
 print s.decode('string-escape')
foo
 bar

Note that the \n in the first one is because I didn't
*print* the result, but merely allowed the interpreter
to call repr() on it.  repr() for a newline is of course
backslash-n, so that's what you see (inside quotation marks)
but the string itself has only 9 characters in it, as
you wished.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread Mage
Michael Soulier wrote:

On 4/20/05, Maxim Kasimov [EMAIL PROTECTED] wrote:
  

but what if i just can't to do this becouse i'm working thrue ssh, and have 
to use 
only installed editors (such as vi)



Then learn to use vi. 

:.,+10s/^/#
 comment the next 10 lines
  

Or if you don't like that you can use sftpfs with gui editor.

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


Re: recording data between [ and ]

2005-04-21 Thread rbt
Peter Hansen wrote:
rbt wrote:
Output from 'netstat -b' on a win2003 server will show what binary is 
responsible for the connection. For example, it may list something 
like this along with other connection specific data:

[lsass.exe]
[System]
[firefox.exe]
[iexplorer.exe]
How might I process the output so that anything within brackets is 
recorded to a log file of my own making? I know how to parse and 
record things to a file, I don't know how to look make '[' and ']' 
appear as special characters so that I can record what's between them.

Does this help?
  import re
 
  s = '''stuff   [lsass.exe]
... [System]  more stuff
... x [firefox.exe] ..
... '''
 
  re.findall(r'\[([^]]*)\]', s)
['lsass.exe', 'System', 'firefox.exe']
-Peter
Yes, it does... may take me a few minutes to get my head around it 
though. Why do re's have to be so arcane and complicated... especially 
in Python?

It's hard to preach 'ease of use' with stuff such as this in the 
language. Perhaps one day it can be rolled up into something that 
*really* is easy to understand:

import string
fp = file('filename')
data = fp.read()
fp.close()
string.between(data,[,])
--
http://mail.python.org/mailman/listinfo/python-list


Re: Private class?

2005-04-21 Thread Brian van den Broek
codecraig said unto the world upon 2005-04-21 09:13:
Hi,
  First, I come from a Java background.
SNIP
...so that is what I am thinking.  However, i guess my issue is how to
make EventBus a singleton or prevent it from being instaniated and
making it's methods statically accessible.
thanks.
I don't come from a Java, or any other language, background, so I
cannot warrant that any of these will seem helpful to you. But there
are a lot of Singleton and Singleton-like patterns floating about.
Here's some:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/102187
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286206
http://fraca7.free.fr/blog/index.php?2005/03/23/6-design-patterns-part-iii---singleton
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: deprecation of has_key?

2005-04-21 Thread Denis S. Otkidach
On Thu, 21 Apr 2005 05:43:36 -0400 Steve Holden wrote:

SH Two words: backward compatibility. To lose that method now would
SH break thousands of existing programs.
[...]
SH The method might disappear in Python 3.0, when we will be allowed to
SH break backward compatibility - you are correct in saying it's no
SH longer necessary.

I believe it's a bad idea to remove this method, since behavior of both
item in dict and for item in dict (especially the later) in Python
does't seem sane to me.  Just look at reverse operations:

dict.fromkeys(seq) - d.keys(), d.iterkeys() - OK
dict(iterable) - d.iteritems()  - why not iter(d)?
dict(l) - d.items() - why not list(d)?
dict(seq) - d.keys(), d.iterkeys()  - looks very strange.

And those (item in dict and for item in dict) are related of course,
since the following should pass:

for item in d:
assert item in d

That's the reason why I always prefer to use has_key() and iteritems()
to in and iter().  Readability counts.

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


Is there a package with convolution and related methods?

2005-04-21 Thread Charles Krug
List:

Is there a Python package with Convolution and related methods?

I'm working on modeling some DSP processes in Python.  I've rolled one
up, but don't feel much like reinventing the wheel, especially if
there's already something like Insanely Efficient FFT for Python
already.

Thanks


Charles

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


How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Charles Krug
List:

I'm working on some methods that operate on (mathematical) vectors as
in:

def Convolution(x, y)
Returns a list containing the convolution of vectors x and y

Is there any way to determine at runtime that x and y are iterible
collections?

Do I *coughs* simply *coughs* trap the exception created by:

for v in x:

when v is a scaler quantity?

Thanks


Charles

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Rocco Moretti
Steve Holden wrote:
The principle of least surprise is all very well, but needless surprise 
of newbies is a dangerous criterion to adopt for programming language 
design and following it consistently would lead to a mess like Visual 
Basic, which grew by accretion until Microsoft realized it was no longer 
tenable and broke backward compatibility.
Well, *needless* surprise of newbies is never a good thing. If it were, 
it wouldn't be needless, now would it? :-) Surprising newbies just to 
surprise newbies is just cruel, but there is room in this world for it 
may suprise you now, but you'll thank us later and situations where 
there is a newbie way and an other way, and the other way is 
chosen because it's the easiest thing for the most people in the long run.

But I agree, having the easiest thing for newbies as your sole 
criterion for language design is a road to madness, for no other reason 
than that newbies don't stay newbies forever.
--
http://mail.python.org/mailman/listinfo/python-list


Re: deprecation of has_key?

2005-04-21 Thread Steven Bethard
Denis S. Otkidach wrote:
I believe it's a bad idea to remove this method, since behavior of both
item in dict and for item in dict (especially the later) in Python
does't seem sane to me.  Just look at reverse operations:
dict.fromkeys(seq) - d.keys(), d.iterkeys() - OK
dict(iterable) - d.iteritems()  - why not iter(d)?
dict(l) - d.items() - why not list(d)?
dict(seq) - d.keys(), d.iterkeys()  - looks very strange.
And those (item in dict and for item in dict) are related of course,
since the following should pass:
for item in d:
assert item in d
That's the reason why I always prefer to use has_key() and iteritems()
to in and iter().
Huh?  I'm not following your logic.  Why is item in dict less readable 
than dict.has_key(item)?  Something to do with expecting inverses that 
don't exist?

Personally, I use item in dict because it's quite readable to me, and 
generally faster.

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


Re: Private class?

2005-04-21 Thread Kent Johnson
codecraig wrote:
class EventListener:
def eventOccurred(self, eventType): pass
The EventListener class is not needed in Python; you can include it for its documentation value if 
you like but Python does not require interfaces the way Java does.

class EventBus:
EVENT_GROW_LEAVES = 0
__listeners = {}
def register(listener, eventType):
if __listeners.has_key(eventType):
curListeners = __listeners.get(eventType)
curListeners.append(listener)
else:
__listeners[eventType] = [listener]
def fire(eventType):
if __listeners.has_key(eventType):
x = __listeners.get(eventType)
for l in x:
l.eventOccurred(eventType)
...so that is what I am thinking.  However, i guess my issue is how to
make EventBus a singleton or prevent it from being instaniated and
making it's methods statically accessible.
One way to do this is to make an EventBus module and make __listeners, register() and fire() be 
module attributes. Your client code would look like
import EventBus
...
EventBus.register(...)
EventBus.fire(...)

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


Re: goto statement

2005-04-21 Thread Sergei Organov
Maxim Kasimov [EMAIL PROTECTED] writes:
 Sergei Organov wrote:
  Maxim Kasimov [EMAIL PROTECTED] writes:
 
 
 1. comment for debug
 
 It can be used in the same way, as the comments for debugging are used,
 but it will be easier than to use  or ''', or using features of
 text-editors, when it is necessary to comment piece of code which already
 contains ''' or/and  strings already, or there is another #-comments.
 Using goto, you do not need to edit a code, which is unfamiliar to
 you.

   and then you end up with situation when another goto jumps directly
  into the body of the code you've just commented with your goto. Happy
  debugging!

 if you can't control what you do - it is you private problem, not mine. Is't
 it?

Hopefully I do control what I do. However, wasn't it you who spoke about
code, which is unfamiliar? Obviously you advocate using goto to
comment out a code that has been written by somebody else. I don't see
any way for you or me to control what those somebody did with goto
provided that goto is there in the language, sorry.

Overall, using goto for commenting something out is not any better than
 or ''', as the code to be commented out could contain labels and you
will need to find and comment out all the goto that jump to these labels
as well. Happy debugging!

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


Re: goto statement

2005-04-21 Thread Sergei Organov
Grant Edwards [EMAIL PROTECTED] writes:

 On 2005-04-21, Sergei Organov [EMAIL PROTECTED] wrote:
 
  Well, I'm writing for embedded realtime systems in C/C++ and
  have never encountered a single need to use goto.
 
 I have encountered situations in C programs where the best
 thing to use was a goto.  Those situations have always been
 handled beutifully by a raise in Python.

setjmp/longjump?

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


Re: How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Fredrik Lundh
Charles Krug wrote:
I'm working on some methods that operate on (mathematical) vectors as
in:
def Convolution(x, y)
Returns a list containing the convolution of vectors x and y
Is there any way to determine at runtime that x and y are iterible
collections?
Do I *coughs* simply *coughs* trap the exception created by:
   for v in x:
when v is a scaler quantity?
why not leave trapping exceptions to whoever uses your function?
/F
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Larry Bates
Others may know better ways but the 2 I know of are:

1) If you know that the arguments will be lists or tuples
you can use isinstance().

if not isinsance(arg, (list, tuple):
print arg must be list or tuple)

2) Or if you not you could see if the argument has next and
__iter__ methods (more general solution)

if  hasattr(arg, 'next') and not hasattr(arg, '__iter__'):
# perform work on iterable

else:
print arg must be an iterable


Larry Bates


Charles Krug wrote:
 List:
 
 I'm working on some methods that operate on (mathematical) vectors as
 in:
 
 def Convolution(x, y)
 Returns a list containing the convolution of vectors x and y
 
 Is there any way to determine at runtime that x and y are iterible
 collections?
 
 Do I *coughs* simply *coughs* trap the exception created by:
 
 for v in x:
 
 when v is a scaler quantity?
 
 Thanks
 
 
 Charles
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deprecation of has_key?

2005-04-21 Thread Denis S. Otkidach
On Thu, 21 Apr 2005 08:50:25 -0600 Steven Bethard wrote:

SB Huh?  I'm not following your logic.  Why is item in dict less
SB readable than dict.has_key(item)?  Something to do with expecting
SB inverses that don't exist?
SB 
SB Personally, I use item in dict because it's quite readable to me,
SB and generally faster.

For me dictionary is a collection of key-value pairs, but not a
collection of keys (that's what set is).

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


Re: How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Roy Smith
Charles Krug  [EMAIL PROTECTED] wrote:
 Do I *coughs* simply *coughs* trap the exception created by:

for v in x:

when v is a scaler quantity?

Sure.  Why not?  If you're coming from a type-bondage language like
C++ or Java, it probabliy feels strange, but it's the Python way.  It
looks like what you want to catch is TypeError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread Grant Edwards
On 2005-04-21, Sergei Organov [EMAIL PROTECTED] wrote:
 Grant Edwards [EMAIL PROTECTED] writes:

 On 2005-04-21, Sergei Organov [EMAIL PROTECTED] wrote:
 
  Well, I'm writing for embedded realtime systems in C/C++ and
  have never encountered a single need to use goto.
 
 I have encountered situations in C programs where the best
 thing to use was a goto.  Those situations have always been
 handled beutifully by a raise in Python.

 setjmp/longjump?

I've always found setjmp/longjmp much more confusing and hard
to maintain than a simple goto.  It also requires library
support that goto doesn't.

-- 
Grant Edwards   grante Yow!  Your CHEEKS sit like
  at   twin NECTARINES above
   visi.coma MOUTH that knows no
   BOUNDS --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recording data between [ and ]

2005-04-21 Thread Diez B. Roggisch
 Yes, it does... may take me a few minutes to get my head around it
 though. Why do re's have to be so arcane and complicated... especially
 in Python?
 
 It's hard to preach 'ease of use' with stuff such as this in the
 language. Perhaps one day it can be rolled up into something that
 *really* is easy to understand:

Welcome to the wonderful world of programming. Regular expressions are what
they are because they are modeled after a certain theory - that of finite
state automata and their correspondence to certain classes of grammars. And
they require a bit of understanding. And there is no language that does
them different - some integrate them syntactically (like perl), others
don't have them available in the standard lib at all. But if you get them,
they always look like that.

 import string
 
 fp = file('filename')
 data = fp.read()
 fp.close()
 
 string.between(data,[,])

how about

import whatever_is_needed
solve_my_problem()

? Seriously: Programming or maybe better saying the way we tell computers
what to do might evolve by standardization to a point where lots of tasks
get easier.You actual problem might be solved easier one day if
commandline-tools agree on a specific output format (viewed from today
thate means possibly xml) and standard tools to deal with these.

But as the world is complex and people want solutions to their complex
problems, IMHO programming will always be about such nitty gritty details. 


-- 
Regards,

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


Re: How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Diez B. Roggisch
Charles Krug wrote:

 List:
 
 I'm working on some methods that operate on (mathematical) vectors as
 in:
 
 def Convolution(x, y)
 Returns a list containing the convolution of vectors x and y
 
 Is there any way to determine at runtime that x and y are iterible
 collections?
 
 Do I *coughs* simply *coughs* trap the exception created by:
 
 for v in x:
 
 when v is a scaler quantity?

Yes, thats considered good practice. 
-- 
Regards,

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


Re: How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Steven Bethard
Charles Krug wrote:
List:
I'm working on some methods that operate on (mathematical) vectors as
in:
def Convolution(x, y)
Returns a list containing the convolution of vectors x and y
Is there any way to determine at runtime that x and y are iterible
collections?
Do I *coughs* simply *coughs* trap the exception created by:
for v in x:
when v is a scaler quantity?
Sure, or if you want to do it earlier, you could try something like:
def convolution(x, y):
xiter = iter(x)
yiter = iter(y)
And then use xiter and yiter in your for loops.  This will make sure 
that the TypeErrors get raised as soon as the function is called.

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


Re: deprecation of has_key?

2005-04-21 Thread Steven Bethard
Denis S. Otkidach wrote:
On Thu, 21 Apr 2005 08:50:25 -0600 Steven Bethard wrote:
SB Huh?  I'm not following your logic.  Why is item in dict less
SB readable than dict.has_key(item)?  Something to do with expecting
SB inverses that don't exist?
SB 
SB Personally, I use item in dict because it's quite readable to me,
SB and generally faster.

For me dictionary is a collection of key-value pairs, but not a
collection of keys (that's what set is).
Ahh, ok.  Now I understand.  I think you could probably search the 
python-dev archives and see why the decision was made as it was.  For 
pretty much all my purposes, key in dict is much more useful than 
item in dict.  Practicality beats Purity and all. ;)

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


A smallish Tkinter question

2005-04-21 Thread mediocre_person

What I want: A little window to open with a 0 in it. Every second, the
0 should increment by 1.
What I get: A one second delay, see the window with a 1 in it, and then
nothing appears to happen. Never see the 0, never see a 2.  Any quick
clues? Thanks. Nick. (Python 2.4, Win98).


from Tkinter import *
from time import sleep

class Clock:
def __init__(self, parent):
self.time = 0
self.display = Label(parent)
self.display[font] = Arial 16
self.display[text] = str(self.time)
self.display.pack()

def run(self): #also tried self,parent
sleep(1.0)
self.time = self.time + 1
self.display[text] = str(self.time)

win = Tk()
app = Clock(win)
app.run() #also tried run(win) with self,parent above
win.mainloop()

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


Re: Meine geilen Bilder

2005-04-21 Thread Ariane
Hi, hier sind meine geilen Bilder!
My nude Pics!!!
http://www.geile-tipps.info/go/ 

--
Posted by News Bulk Poster
Unregistered version
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can an object of a C type have random members added? tp_dictoffset?

2005-04-21 Thread Denis S. Otkidach
On Thu, 21 Apr 2005 17:55:24 +1000 Gregory Bond wrote:

GB I have a class implemented in C using tp_members to specify (read-only) 
GB access to data members in the C struct. I'd like to be able to do the 
GB decoration trick with objects of this class.  Is this possible?
GB 
GB [The documentation for tp_dictoffset eseems to hint that this is 
GB possible. how do I use it?]

Something like the following:

typedef struct {
PyObject_HEAD
PyObject *dict;
} YourObject;

static PyMemberDef module_members[] = {
{__dict__, T_OBJECT, offsetof(YourObject, dict), READONLY},
{0}
};

PyObject *
Your_New()
{
YourObject *obj;
obj = PyObject_GC_New(YourObject, Your_Type);
if (obj==NUL) return NULL;
obj-dict = PyDict_New();
if (obj-dict==NULL) {
Py_DECREF(obj);
return NULL;
}
PyObject_GC_Track(obj);
return (PyObject *)obj;
}

PyTypeObject Your_Type = {
PyObject_HEAD_INIT(PyType_Type)
# ...skipped...
offsetof(YourObject, dict), /* tp_dictoffset */
# ...skipped...
}

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


  1   2   3   >