Re: removing list comprehensions in Python 3.0

2005-07-10 Thread Bengt Richter
On Sat, 09 Jul 2005 22:32:22 -0600, Steven Bethard <[EMAIL PROTECTED]> wrote:

>Raymond Hettinger wrote:
>> [Steven Bethard]
>> 
>>>I would hope that in Python 3.0 list comprehensions and generator
>>>expressions would be able to share a large amount of implementation, and
>>>thus that the speed differences would be much smaller.  But maybe not...
>> 
>> Looking under the hood, you would see that the implementations are
>> necessarily as different as night and day.  Only the API is similar.
>
>Necessarily?  It seems like list comprehensions *could* be implemented 
>as a generator expression passed to the list constructor.  They're not 
>now, and at the moment, changing them to work this way seems like a bad 
>idea because list comprehensions would take a performance hit.  But I 
>don't understand why the implementations are *necessarily* different. 
>Could you explain?
>
>STeVe
>
>P.S. The dis.dis output for list comprehensions makes what they're doing 
>pretty clear.  But dis.dis doesn't seem to give me as much information 
>when looking at a generator expression:
>
>py> def ge(items):
>... return (item for item in items if item)
>...
>py> dis.dis(ge)
>   2   0 LOAD_CONST   1 (expression> at 0116FD20, file "", line 2>)
>   3 MAKE_FUNCTION0
>   6 LOAD_FAST0 (items)
>   9 GET_ITER
>  10 CALL_FUNCTION1
>  13 RETURN_VALUE
>
>I tried to grep through the dist\src directories for what a generator 
>expression code object looks like, but without any luck.  Any chance you 
>could point me in the right direction?

 >>> import dis
 >>> g = ge([1,2,0,3,'',4])
 >>> dis.dis(g)
 Traceback (most recent call last):
   File "", line 1, in ?
   File "d:\python-2.4b1\lib\dis.py", line 46, in dis
 raise TypeError, \
 TypeError: don't know how to disassemble generator objects

but:

 >>> dis.dis(ge)
   2   0 LOAD_CONST   1 ( at 02EE4FA0, file "", line 2>)
   3 MAKE_FUNCTION0
   6 LOAD_FAST0 (items)
   9 GET_ITER
  10 CALL_FUNCTION1
  13 RETURN_VALUE
 >>> ge.func_code
 ", line 1>
 >>> ge.func_code.co_consts
 (None,  at 02EE4FA0, file "", line 
2>)
 >>> ge.func_code.co_consts[1]
  at 02EE4FA0, file "", line 2>
 >>> dis.dis(ge.func_code.co_consts[1])
   2   0 SETUP_LOOP  28 (to 31)
   3 LOAD_FAST0 ([outmost-iterable])
 >>6 FOR_ITER21 (to 30)
   9 STORE_FAST   1 (item)
  12 LOAD_FAST1 (item)
  15 JUMP_IF_FALSE8 (to 26)
  18 POP_TOP
  19 LOAD_FAST1 (item)
  22 YIELD_VALUE
  23 JUMP_ABSOLUTE6
 >>   26 POP_TOP
  27 JUMP_ABSOLUTE6
 >>   30 POP_BLOCK
 >>   31 LOAD_CONST   0 (None)
  34 RETURN_VALUE

A little more info, anyway. HTH.

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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Thomas Lotze
Steven D'Aprano wrote:

> On the gripping hand, testing for errors before they happen will be slow
> if errors are rare:

Hm, might have something to do with why those things intended for
handling errors after they happened are called exceptions ;o)

> - If your code has side effects (eg changing existing objects, writing to
> files, etc), then you might want to test for error conditions first.
> Otherwise, you can end up with your data in an inconsistent state.

BTW: Has the context management stuff from PEP 343 been considered for
implementing transactions?

> - Why are you optimizing your code now anyway? Get it working the simplest
> way FIRST, then _time_ how long it runs. Then, if and only if it needs to
> be faster, should you worry about optimizing. The simplest way will often
> be try...except blocks.

Basically, I agree with the "make it run, make it right, make it fast"
attitude. However, FWIW, I sometimes can't resist optimizing routines that
probably don't strictly need it. Not only does the resulting code run
faster, but it is usually also shorter and more readable and expressive.
Plus, I tend to gain further insight into the problem and tools in the
process. YMMV, of course.

-- 
Thomas

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


Re: Use cases for del

2005-07-10 Thread Reinhold Birkenfeld
Ron Adam wrote:

>> >>> 'abc' is 'abcd'[:3]
>> False
> 
> Well of course it will be false... your testing two different strings! 
> And the resulting slice creates a third.
>
> Try:
> 
> ABC = 'abc'
> 
> value = ABC
> if value is ABC:   # Test if it is the same object
> pass

That's not going to buy you any time above the "is None", because identity-
testing has nothing to do with the type of the object.

Additionally, using "is" with immutable objects is horrible.

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


What is Expresiveness in a Computer Language?

2005-07-10 Thread Xah Lee
What is Expresiveness in a Computer Language

20050207, Xah Lee.

In languages human or computer, there's a notion of expressiveness.

English for example, is very expressive in manifestation, witness all
the poetry and implications and allusions and connotations and
dictions. There are a myriad ways to say one thing, fuzzy and warm and
all. But when we look at what things it can say, its power of
expression with respect to meaning, or its efficiency or precision, we
find natural languages incapable.

These can be seen thru several means. A sure way is thru logic,
linguistics, and or what's called Philosophy of Languages. One can also
glean directly the incapacity and inadequacy of natural languages by
studying the artificial language lojban, where one realizes, not only
are natural languages incapable in precision and lacking in efficiency,
but simply a huge number of things are near impossible to express thru
them.

One thing commonly misunderstood in computing industry is the notion of
expressiveness. If a language has a vocabulary of (smile, laugh, grin,
giggle, chuckle, guffaw, cackle), then that language will not be as
expressive, as a language with just (severe, slight, laugh, cry). The
former is "expressive" in terms of nuance, where the latter is
expressive with respect to meaning.

Similarly, in computer languages, expressiveness is significant with
respect to semantics, not syntactical variation.

These two contrasting ideas can be easily seen thru Perl versus Python
languages, and as one specific example of their text pattern matching
capabilities.

Perl is a language of syntactical variegations. Python on the other
hand, does not even allow changes in code's indentation, but its
efficiency and power in expression, with respect to semantics,
showcases Perl's poverty in specification.

http://xahlee.org/perl-python/what_is_expresiveness.html

© Copyright 2005 by Xah Lee.

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

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

ZipFile and file rigths

2005-07-10 Thread perchef
hi,

i have written this small code which allow me to unzip files using
python :

import zipfile
import os
import os.path

pathDir="/home/toto/Desktop"
pathZip= os.path.join(pathDir,"foobar.zip")

if zipfile.is_zipfile(pathZip):
zf = zipfile.ZipFile(pathZip)

for file in zf.namelist():
newPath = os.path.join(pathDir,file)
print newPath
if not file.endswith('/') and not os.path.exists(newPath) :
newFile = open(newPath, 'wb')
newFile.write(zf.read(file))
newFile.flush()
newFile.close()
else :
os.makedirs(newPath)

zf.close()
else:
print pathZip + " is not a zip file"

it works well but i have a small problem : i can't see how i can deal
with file rights.
When I unzip files with this script all the unzipped files haven't the
good rights.
for example :
   with this script :
   -rw-r--r-- foo.exe
   with a traditional zip program (ie : stuffit ):
   -rwxr-xr-x foo.exe
ZipInfo objects doesn't store informations about rights ?
(http://www.python.org/doc/current/lib/zipinfo-objects.html#zipinfo-objects)

How can i fix this ?

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


Re: Python Forum

2005-07-10 Thread Michael Hoffman
Throne Software wrote:
> Throne Software has opened up a Python Forum at:
> 
> http://www.thronesoftware.com/forum/
> 
> Join us!

Why shouldn't I just stay here?
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


passing arguments to a function - do I need type ?

2005-07-10 Thread Philipp H. Mohr
Hello,
I got a newbie question, I have written the following distance function:

def distance(self,element1, element2):
dist = 0

for n in range(len(element1)):
dist = dist + pow((element1[n] - element2[n]),2)
print 'dist' + dist
return sqrt(dist)


and in order to be able to use len() and index element1[] the function
needs to know that the arguments element1 and element2 are both listst or
doesn't it ?

I get the following error msg:

Traceback (most recent call last):
  File "Memory.py", line 105, in ?
start.inputVector(inP2)
  File "Memory.py", line 97, in inputVector
allDimensions[0].newAttribute(vector)
  File "Memory.py", line 56, in newAttribute
dist = self.distance(n.getCenter,newElement)
  File "Memory.py", line 75, in distance
for n in range(len(element1)):
TypeError: len() of unsized object



AND if I take len out I get:



Traceback (most recent call last):
  File "Memory.py", line 105, in ?
start.inputVector(inP2)
  File "Memory.py", line 97, in inputVector
allDimensions[0].newAttribute(vector)
  File "Memory.py", line 56, in newAttribute
dist = self.distance(n.getCenter,newElement)
  File "Memory.py", line 76, in distance
dist = dist + pow((element1[n] - element2[n]),2)
TypeError: unsubscriptable object



Thank you very much for your help.

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


Newbie Alert! Upgrading Python?

2005-07-10 Thread El
Hi,

Sorry to bother you folks with a real newbie question, but I am sure that 
this is the place for me to ask.

Python 1.5.1 (final) and Python Win32 Extensions are installed on my 4 year 
old computer.  My computer has always been upgraded to include the latest 
programs and Windows updates.

However, I have NEVER upgraded Python?  Therefore, my questions:

1.  Should I upgrade to the new Python 2.4.1 (Final)?

2.  If so, should I uninstall the old version first and reboot, or can I 
just install the new version over the old version?

3.  Are the Win32 extensions included in the final version, or are the 
extensions a separate download?

I do not use Python, but I am assuming that something on my computer must. 
LOL.

Thank you for any enlightenment you can render.

Elliot


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


Re: [ANNOUNCE] pysudoku 0.1

2005-07-10 Thread sudoku
Thanks Glenn,

I added your link to our Sudoku Links List: http://sudoku.jouwpagina.nl

Xander


"Glenn Hutchings" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
> Announcing PySuDoku version 0.1, yet another Sudoku program written in
> Python.  But this one has features that I don't see in any of the others:
>
>  * Cute interactive solving mode via Tkinter.
>  * Puzzle generation option, for making your own puzzles.
>  * Nicely packaged for installation via distutils.
>
> Sudoku, for the remaining 27 people in the world who don't know already, 
> is
> a logic puzzle where you have to fill in the numbers in a 9x9 grid so that
> each row, column and 3x3 box has exactly one of the numbers 1-9 in them.
>
> You can get pysudoku at:
>
>http://www.freewebtown.com/zondo/programs
> 


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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Steven D'Aprano
On Sun, 10 Jul 2005 12:15:25 +0530, Dark Cowherd wrote:

> http://www.joelonsoftware.com/items/2003/10/13.html

Joel Spolsky might be a great C++ programmer, and his advice on user
interface design is invaluable, but Python is not C++ or Java, and his
arguments about exceptions do not hold in Python.

Joel argues:

"They are invisible in the source code. Looking at a block of code,
including functions which may or may not throw exceptions, there is no way
to see which exceptions might be thrown and from where. This means that
even careful code inspection doesn't reveal potential bugs."

I don't quiet get this argument. In a random piece of source code, there
is no way to tell whether or not it will fail just by inspection. If you
look at:

x = 1
result = myfunction(x)

you can't tell whether or not myfunction will fail at runtime just by
inspection, so why should it matter whether it fails by crashing at
runtime or fails by raising an exception?

Joel's argument that raising exceptions is just a goto in disguise is
partly correct. But so are for loops, while loops, functions and methods!
Like those other constructs, exceptions are gotos tamed and put to work
for you, instead of wild and dangerous. You can't jump *anywhere*, only
highly constrained places.

Joel also writes:

"They create too many possible exit points for a function. To write
correct code, you really have to think about every possible code path
through your function. Every time you call a function that can raise an
exception and don't catch it on the spot, you create opportunities for
surprise bugs caused by functions that terminated abruptly, leaving data
in an inconsistent state, or other code paths that you didn't think about."

This is a better argument for *careful* use of exceptions, not an argument
to avoid them. Or better still, it is an argument for writing code which
doesn't has side-effects and implements data transactions. That's a good
idea regardless of whether you use exceptions or not.

Joel's concern about multiple exit points is good advice, but it can be
taken too far. Consider the following code snippet:

def myfunc(x=None):
result = ""
if x is None:
result = "No argument given"
elif x = 0:
result = "Zero"
elif 0 < x <= 3:
resutl = "x is between 0 and 3"
else:
result = "x is more than 3"
return result

There is no benefit in deferring returning value as myfunc does, just
for the sake of having a single exit point. "Have a single exit point"
is a good heuristic for many functions, but it is pointless make-work for
this one. (In fact, it increases, not decreases, the chances of a bug. If
you look carefully, myfunc above has such a bug.

Used correctly, exceptions in Python have more advantages than
disadvantages. They aren't just for errors either: exceptions can be
triggered for exceptional cases (hence the name) without needing to track
(and debug) multiple special cases.

Lastly, let me argue against one of Joel's comments:

"A better alternative is to have your functions return error values when
things go wrong, and to deal with these explicitly, no matter how verbose
it might be. It is true that what should be a simple 3 line program often
blossoms to 48 lines when you put in good error checking, but that's life,
and papering it over with exceptions does not make your program more
robust."

Maybe that holds true for C++. I don't know the language, and wouldn't
like to guess. But it doesn't hold true for Python. This is how Joel might
write a function as a C programmer:

def joels_function(args):
error_result = 0
good_result = None
process(args)
if error_condition():
error_result = -1  # flag for an error
elif different_error_conditon():
error_result = -2
else:
more_processing()
if another_error_conditon():
error_result = -3
do_more_work()
good_result = "Success!"
if error_result != 0:
return (False, error_result)
else:
return (True, good_result)


and then call it with:

status, msg = joels_function(args)
if status == False:
print msg
# and fail...
else:
print msg
# and now continue...


This is how I would write it in Python:

def my_function(args):
process(args)
if error_condition():
raise SomeError("An error occurred")
elif different_error_conditon():
raise SomeError("A different error occurred")
more_processing()
if another_error_conditon():
raise SomeError("Another error occurred")
do_more_work()
return "Success!"

and call it with:

try:
result = my_function(args)
print "Success!!!"
except SomeError, msg:
print msg
# and fail...
# and now continue safely here...


In the case of Python, calling a function that may raise an exception is
no more difficult or unsafe than calling a function that returns a status
flag and a result, but writing the function itself is much ea

Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Roy Smith
Thomas Lotze <[EMAIL PROTECTED]> wrote:
> Basically, I agree with the "make it run, make it right, make it fast"
> attitude. However, FWIW, I sometimes can't resist optimizing routines that
> probably don't strictly need it. Not only does the resulting code run
> faster, but it is usually also shorter and more readable and expressive.

Optimize for readability and maintainability first.  Worry about speed 
later.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Alert! Upgrading Python?

2005-07-10 Thread Thorsten Kampe
* El (2005-07-10 11:56 +0100)
> Sorry to bother you folks with a real newbie question, but I am sure that 
> this is the place for me to ask.
> 
> Python 1.5.1 (final) and Python Win32 Extensions are installed on my 4 year 
> old computer.  My computer has always been upgraded to include the latest 
> programs and Windows updates.
> 
> However, I have NEVER upgraded Python?

Is that a question?

> Therefore, my questions:
> 
> 1.  Should I upgrade to the new Python 2.4.1 (Final)?

No, why?
 
> 2.  If so, should I uninstall the old version first and reboot, or can I 
> just install the new version over the old version?

No.
 
> 3.  Are the Win32 extensions included in the final version, or are the 
> extensions a separate download?

No, yes.
 
> I do not use Python, but I am assuming that something on my computer must. 
> LOL.

If you don't use it: uninstall Python. If something else uses it: keep
it as it is as your app might break with the new Python - even though
2.4 is backwards compatible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread John Roth

"Thomas Lotze" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Steven D'Aprano wrote:
>
>
> Basically, I agree with the "make it run, make it right, make it fast"
> attitude. However, FWIW, I sometimes can't resist optimizing routines that
> probably don't strictly need it. Not only does the resulting code run
> faster, but it is usually also shorter and more readable and expressive.
> Plus, I tend to gain further insight into the problem and tools in the
> process. YMMV, of course.

Shorter, more readable and expressive are laudable goals in and
of themselves. Most of the "advice" on optimization assumes that
after optimization, routines will be less readable and expressive,
not more.

In other words, I wouldn't call the activity of making a routine
more readable and expressive of intent "optimization." If it runs
faster, that's a bonus. It frequently will, at least if you don't add
method calls to the process.

John Roth
>
> -- 
> Thomas
> 

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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Thorsten Kampe
* John Roth (2005-07-09 21:48 +0100)
> "Thorsten Kampe" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>>* Steve Juranich (2005-07-09 19:21 +0100)
>>> I know that this topic has the potential for blowing up in my face,
>>> but I can't help asking.  I've been using Python since 1.5.1, so I'm
>>> not what you'd call a "n00b".  I dutifully evangelize on the goodness
>>> of Python whenever I talk with fellow developers, but I always hit a
>>> snag when it comes to discussing the finer points of the execution
>>> model (specifically, exceptions).
>>>
>>> Without fail, when I start talking with some of the "old-timers"
>>> (people who have written code in ADA or Fortran), I hear the same
>>> arguments that using "if" is "better" than using "try".  I think that
>>> the argument goes something like, "When you set up a 'try' block, you
>>> have to set up a lot of extra machinery than is necessary just
>>> executing a simple conditional."
>>>
>>> I was wondering how true this holds for Python, where exceptions are
>>> such an integral part of the execution model.  It seems to me, that if
>>> I'm executing a loop over a bunch of items, and I expect some
>>> condition to hold for a majority of the cases, then a "try" block
>>> would be in order, since I could eliminate a bunch of potentially
>>> costly comparisons for each item.  But in cases where I'm only trying
>>> a single getattr (for example), using "if" might be a cheaper way to
>>> go.
>>>
>>> What do I mean by "cheaper"?  I'm basically talking about the number
>>> of instructions that are necessary to set up and execute a try block
>>> as opposed to an if block.
>>
>> "Catch errors rather than avoiding them to avoid cluttering your code
>> with special cases. This idiom is called EAFP ('easier to ask
>> forgiveness than permission'), as opposed to LBYL ('look before you
>> leap')."
>>
>> http://jaynes.colorado.edu/PythonIdioms.html
> 
> It depends on what you're doing, and I don't find a "one size fits all"
> approach to be all that useful.

I think, it's a common opinion in the Python community (see for
instance "Python in a Nutshell") that EAFP is the Pythonic way to go
and - except in very rare cases - much preferred to LBYL.

Speed considerations and benchmarking should come in after you wrote
the program. "Premature optimisation is the root of all evil" and
"first make it work, then make it right, then make it fast" (but only
if it's not already fast enough) - common quotes not only with Python
developers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Module Exposure

2005-07-10 Thread George Sakkis
"Jacob Page" <[EMAIL PROTECTED]> wrote:

> If the union of two integers yielded a set of integers, then
> it'd make more since for the union of two Intervals to yield an
> IntervalSet.

AFAIK union is defined over sets, not numbers, so I'm not sure what you
mean by the "union of two integers". What I'm saying is that while the
union of two intervals is always defined (since intervals are sets),
the result set is not guaranteed to be an interval. More specifically,
the result is an interval if and only if the intervals overlap, e.g.
(2,4] | [3,7] = (2,7]
but
(2,4] | [5,7] = { (2,4], [5,7] }
That is, the set of intervals is not closed under union. OTOH, the set
of intervals _is_ closed under intersection; intersecting two
non-overlapping intervals gives the empty interval.

George

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


Re: passing arguments to a function - do I need type ?

2005-07-10 Thread Jorgen Grahn
(You posted your question as a followup to oen of Xah Lee's musings.
That is not the best of ideas, since people with threaded newsreaders
tend not to see it. Just post (creating a new thread) next time.)

On Sun, 10 Jul 2005 11:19:31 +0100 (BST), Philipp H. Mohr <[EMAIL PROTECTED]> 
wrote:
> Hello,
> I got a newbie question, I have written the following distance function:
>
> def distance(self,element1, element2):
> dist = 0
>
> for n in range(len(element1)):
> dist = dist + pow((element1[n] - element2[n]),2)
> print 'dist' + dist
> return sqrt(dist)
>
> and in order to be able to use len() and index element1[] the function
> needs to know that the arguments element1 and element2 are both listst or
> doesn't it ?

Yeah, or something else supporting len(x) and x[n].

> I get the following error msg:
...
> TypeError: len() of unsized object
...
> AND if I take len out I get:
...
> TypeError: unsubscriptable object

Well, that depends on the types of the arguments
you're passing to the method, doesn't it? A call like

  distance([1,1], [0,0])

works fine for me. And here is a slightly simpler implementation
which avoids len (thus accepting a wider range of argument types)
and pow:

def distance(element1, element2):
dist=0
for a, b in zip(element1, element2):
n = float(a-b)
dist += n*n
return math.sqrt(dist)

(Dunno if that's the correct formula for n-dimensional distance.
I have forgotten way too much math in the past ten years.)

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Jorgen Grahn
On Sun, 10 Jul 2005 22:10:50 +1000, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Sun, 10 Jul 2005 12:15:25 +0530, Dark Cowherd wrote:
>
>> http://www.joelonsoftware.com/items/2003/10/13.html
>
> Joel Spolsky might be a great C++ programmer, and his advice on user
> interface design is invaluable, but Python is not C++ or Java, and his
> arguments about exceptions do not hold in Python.

Of course, his arguments do not even "hold" in C++ or Java, in the sense
that everyone should be expected to accept them. Most C++ programmers would
find his view on exceptions slightly ... exotic.

He has a point though: exceptions suck. But so do error codes. Error
handling is difficult and deadly boring.

(Then there's the debate about using exceptions for handling things that
aren't really errors, and what the term 'error' really means ...)

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing arguments to a function - do I need type ?

2005-07-10 Thread George Sakkis
"Philipp H. Mohr" <[EMAIL PROTECTED]> wrote:

> Hello,
> I got a newbie question, I have written the following distance function:
>
> def distance(self,element1, element2):
> dist = 0
>
> for n in range(len(element1)):
> dist = dist + pow((element1[n] - element2[n]),2)
> print 'dist' + dist
> return sqrt(dist)
>
>
> and in order to be able to use len() and index element1[] the function
> needs to know that the arguments element1 and element2 are both listst or
> doesn't it ?

No it doesn't; it finds out at runtime. Also they don't have to be
list; any object that defines __len__ will do.

> I get the following error msg:
>
> Traceback (most recent call last):
>   File "Memory.py", line 105, in ?
> start.inputVector(inP2)
>   File "Memory.py", line 97, in inputVector
> allDimensions[0].newAttribute(vector)
>   File "Memory.py", line 56, in newAttribute
> dist = self.distance(n.getCenter,newElement)
>   File "Memory.py", line 75, in distance
> for n in range(len(element1)):
> TypeError: len() of unsized object

So obviously n.getCenter is not a list.

> AND if I take len out I get:
>
>
>
> Traceback (most recent call last):
>   File "Memory.py", line 105, in ?
> start.inputVector(inP2)
>   File "Memory.py", line 97, in inputVector
> allDimensions[0].newAttribute(vector)
>   File "Memory.py", line 56, in newAttribute
> dist = self.distance(n.getCenter,newElement)
>   File "Memory.py", line 76, in distance
> dist = dist + pow((element1[n] - element2[n]),2)
> TypeError: unsubscriptable object

Same problem; n.getCenter and/or newElement are not lists (or other
subscriptable objects for that matter). Just print them before you call
distance to convince yourself.

By the way, you don't use 'self' anywhere, so perhaps distance should
be a function, not method. Also, the pythonic way of writing it (since
2.4) is:

from math import sqrt
from itertools import izip

def distance(sequence1, sequence2):
return sqrt(sum((x-y)**2 for x,y in izip(sequence1, sequence2)))

> Thank you very much for your help.
> 
> Phil

Regards,
George

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


Re: Yet Another Python Web Programming Question

2005-07-10 Thread Jorey Bump
Daniel Bickett <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> I neglected to mention an important fact, and that is the fact that I
> am limited to Apache, which elminates several suggestions (that are
> appreciated none-the-less).

"Limited to Apache" is not the same as "using apache in a restricted 
environment", so we may need more clarification.

If you are looking for a solution that sits on top of apache somehow, and 
you have system administrative access, there are a lot of choices, 
including ones that use mod_python. If something is not intended to 
interface directly with apache, it can still be proxied through apache 
while it runs on an alternate local port (a standalone app with an 
embedded web server, for example).

If you mean that you're in a typical hosted environment with insufficient 
privileges to install or configure much of anything, you might be stuck 
with CGI. Since you mention in your original post that you have a folder 
in your home directory that's in sys.path, your provider is trying to do 
something to support python applications (hopefully, the path is specific 
to your virtual host, to avoid namespace collisions). In any case, if 
this was done to support mod_python, you can meet some of your criteria 
with mod_python.publisher, but you will almost certainly want to use a 
staging platform to develop your apps beforehand, since it is necessary 
to either restart apache or touch imported modules after editing.

BTW, this is how I use Python for web applications myself: Each virtual 
host gets a special directory prepended to the PYTHONPATH, in which the 
bulk of my applications are created as packages. Then I use 
mod_python.publisher to publish single modules that serve as interfaces, 
converting values from requests and passing them on to the packages, 
which I try to make web agnostic (in fact, I develop most of the backend 
code locally before even trying it out on the web, so I can use it in 
other application domains). 

I've looked at other offerings, but as soon as I see proprietary markup 
or commands embedded in HTML, I lose interest, so I feel your pain.

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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Aahz
Roy, I know you actually know this stuff, but for the benefit of
beginners

In article <[EMAIL PROTECTED]>,
Roy Smith  <[EMAIL PROTECTED]> wrote:
>
>3) In some cases, they can lead to faster code.  A classic example is 
>counting occurances of items using a dictionary:
>
>   count = {}
>   for key in whatever:
>  try:
> count[key] += 1
>  except KeyError:
> count[key] = 1
>
>compared to
>
>   count = {}
>   for key in whatever:
>  if count.hasKey(key):
> count[key] += 1
>  else:
> count[key] = 1

Except that few would write the second loop that way these days::

for key in whatever:
if key in count:
...

Using ``in`` saves a bytecode of method lookup on ``has_key()`` (which is
the correct spelling).  Or you could choose the slightly more convoluted
approach to save a line::

for key in whatever:
count[key] = count.get(key, 0) + 1

If whatever had ``(key, value)`` pairs, you'd do::

key_dict = {}
for key, value in whatever:
key_dict.setdefault(key, []).append(value)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another Python Web Programming Question

2005-07-10 Thread Paul Boddie
"Robert Brewer" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Daniel Bickett wrote:
> > I neglected to mention an important fact, and that is the fact that I
> > am limited to Apache, which elminates several suggestions (that are
> > appreciated none-the-less).
> 
> Do you have access to mod_python, mod_rewrite, FastCGI, or SCGI? Then
> CherryPy 2.1 is still a great option for you with Apache:
> http://www.cherrypy.org/wiki/WSGIServers
> http://www.cherrypy.org/wiki/BehindApache

According to the "quick facts" page [1] "CherryPy powered web
applications are in fact stand-alone Python applications embedding
their own multi-threaded web server", suggesting that if the hosting
environment is "limited to Apache" and if this can also be taken to
mean that the environment doesn't permit long-running server processes
apart from Apache, then CherryPy isn't likely to be suitable.

Karigell was also mentioned, but according to the documentation
("Working with Apache or Xitami" [2]) "Apache will be used as a proxy
between the client and the built-in server, so you have to configure
Apache so that it sends the requests to the built-in server", also
suggesting that in limited hosting environments Karigell won't be
suitable either.

Spyce, on the other hand, seems to work with mod_python, although I
agree with Andrew Clover that the inquirer probably knows what they
want to do using a "traditional" Web application programming style and
doesn't need a framework which decides lots of things on their behalf.
Moreover, I'd imagine that not all restrictive hosting environments
make mod_python available to their clients.

My meagre contribution to the genre is WebStack [3] which does run in
the most plain of hosting environments (CGI) as well as others. Really
intended for the writing of frameworks, the programming style might
suit someone who wants to have control over the most elementary
aspects of Web programming. As Andrew said, there are plenty of
choices...

Paul

[1] http://www.cherrypy.org/wiki/CherryPyQuickFacts
[2] http://karrigell.sourceforge.net/en/apache.htm
[3] http://www.python.org/pypi/WebStack
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Ralf W. Grosse-Kunstleve
--- Kay Schluehr <[EMAIL PROTECTED]> wrote:

>  > I stripped your code down to the essence. See attachment.
> > For the user your approach then becomes:
> >
> >   class grouping:
> > __metaclass__ = autoattr
> > def __init__(self, x, y, z):
> >   pass
> 
> No. This is clearly NOT what I had in mind. I translated your original
> proposal which introduced a punctuation syntax '.x' for constructor
> parameters forcing the interpreter to create equally named object
> attributes into a naming convention that can be handled by a metaclass
> customizer.

I see.

> The grouping.__init__ above does exacly nothing according
> to my implementation. I would never accept dropping fine-tuning
> capabilities. The "auto_" prefix is all the declarative magic.

I got only negative feedback regarding the fine-tuning idea, e.g.
http://mail.python.org/pipermail/python-list/2005-July/288833.html. After
thinking about it for a while I also came to the conclusion that runtime
performance and simplicity is indeed the higher value for a general-purpose
solution. Without a supporting syntax change (the idea received almost hysteric
opposition) I don't think fine-tuning can be supported without a noticeable
runtime-penalty.

My syntax-change proposal was meant not to change the user interface. I.e. it
was meant to preserve "grouping(x=1,y=2,z=3)", no matter how x,y,z are handled
in the constructor. Under your proposal the decision to use "auto init" becomes
 a visible part of the user interface and may therefore be irreversible in
practical applications.

> > My __autoinit__ suggestion would result in (assuming object supports
> > this by default):
> >
> >   class grouping(object):
> > def __autoinit__(self, x, y, z):
> >   pass
> >
> > I think that's far more intuitive.
> 
> Being intuitive is relative to someones intuition. 

If someone looks at the code there is no question he/she knows immediately what
is going on. In contrast, the __metaclass__ statement is potentially separated
from the __init__ definition by unrelated code, leading to surprises (on top of
intimidation for beginners). I don't think that's the best style. It is
generally better if the framework doesn't allow for artificial separations in
the first place.

Cheers,
Ralf

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Roy Smith
[EMAIL PROTECTED] (Aahz) wrote:
> Using ``in`` saves a bytecode of method lookup on ``has_key()`` (which is
> the correct spelling).

You are right.  My example is somewhat out of date w/r/t newer language 
features, and writing hasKey() instead of has_key() was just plain a 
mistake.  Thanks for the corrections.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Forum

2005-07-10 Thread Peter Hansen
Devan L wrote:
> I see a total of 12 posts and 8 users.

Which at least makes it a record so far, surpassing every other "hey, i 
just made a new forum, it's awesome and everyone should join!" post that 
has been made here in the past, by about 9 posts and 5 users... ;-)

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


Re: Newbie Alert! Upgrading Python?

2005-07-10 Thread Peter Hansen
Thorsten Kampe wrote:
> * El (2005-07-10 11:56 +0100)
>>Python 1.5.1 (final) and Python Win32 Extensions are installed on my 4 year 
> 
> If you don't use it: uninstall Python. If something else uses it: keep
> it as it is as your app might break with the new Python - even though
> 2.4 is backwards compatible.

Python 2.4 is most definitely not 100% backwards compatible with Python 
1.5.1, so "don't upgrade!" is correct advice if Python is in use by some 
application that expects it to be 1.5.1...

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread raptor
I think u are wrong.. I think perl is much more exrpressive in
semantics than Python..

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Steven D'Aprano
On Sun, 10 Jul 2005 07:20:34 -0700, raptor wrote:

> I think u are wrong.. I think perl is much more exrpressive in
> semantics than Python..

Well, with such great command of natural language as you are displaying,
how could anyone argue with your conclusion?

-- 
Steven.

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


Re: passing arguments to a function - do I need type ?

2005-07-10 Thread Steven D'Aprano
On Sun, 10 Jul 2005 11:19:31 +0100, Philipp H. Mohr wrote:

> Hello,
> I got a newbie question, I have written the following distance function:

Great. Now, how about you tell us what you expect it to do? I assume
it calculates the Euclidean distance between two points. (If you
don't know what Euclidean distance is, don't worry about it -- it is
basically just the "normal" distance.)

Should it calculate the distance between points on a line? 2-D points on
a plane? 3-D points in space? Higher dimensions?

I'm going to assume you want your function to operate on any number of
dimensions.

> def distance(self,element1, element2):

You don't need "self" unless it is a method of a class.

> dist = 0
> for n in range(len(element1)):
> dist = dist + pow((element1[n] - element2[n]),2)
> print 'dist' + dist

Why are you printing the SQUARE of the distance?

> return sqrt(dist)

Okay, here is a simpler method, complete with comments:

def distance(point1, point2):
"""Return the distance between two points in N-dimensional space.

Example: if the points are (a,b) and (c,d) respectively, returns the
Euclidean distance d = sqrt( (c-a)**2 + (d-b)**2 )

Both points should have the same number of coordinates, each of which
is a float or int. Points can be given as lists or tuples.
"""
sum_sq = 0  # sum of squares of the differences
if len(point1) != len(point2):
# check for errors here because they might not be picked 
# up later if we don't
raise ValueError("Points have different number of dimensions")
for i in range(len(point1)):
x, y = point1[i], point2[i]  # extract the next two ordinates
sum_sq = sum_sq + (y-x)**2  # and add the square of the difference
return sum_sq**0.5

If you really care about accuracy, you should use the sqrt function from
the math module rather than **0.5.

Here is another version, using zip.

def distance(point1, point2):
if len(point1) != len(point2):
raise ValueError("Points have different number of dimensions")
L = zip(point1, point2)
sum_sq = 0
for x,y in L:
sum_sq = sum_sq + (y-x)**2
return sum_sq**0.5

And finally, a one-liner using list comprehensions and no error-checking.

def distance(point1, point2):
return sum([(y-x)**2 for x,y in zip(point1, point2)])**0.5



> and in order to be able to use len() and index element1[] the function
> needs to know that the arguments element1 and element2 are both listst
> or doesn't it ?

No. Lots of things can be passed to len() and indexed.

> I get the following error msg:
> 
> Traceback (most recent call last):
>   File "Memory.py", line 105, in ?
> start.inputVector(inP2)
>   File "Memory.py", line 97, in inputVector
> allDimensions[0].newAttribute(vector)
>   File "Memory.py", line 56, in newAttribute
> dist = self.distance(n.getCenter,newElement)
>   File "Memory.py", line 75, in distance
> for n in range(len(element1)):
> TypeError: len() of unsized object

And what is element1 when you get that error message? That's the first
thing I would look at. 

> AND if I take len out I get:
> 
> 
> Traceback (most recent call last):
>   File "Memory.py", line 105, in ?
> start.inputVector(inP2)
>   File "Memory.py", line 97, in inputVector
> allDimensions[0].newAttribute(vector)
>   File "Memory.py", line 56, in newAttribute
> dist = self.distance(n.getCenter,newElement)
>   File "Memory.py", line 76, in distance
> dist = dist + pow((element1[n] - element2[n]),2)
> TypeError: unsubscriptable object

Firstly, you seem to have a lot of modules there. What happens when you
call distance directly? Can you get it to work then?

Secondly, what are the values for element1 and element2?


-- 
Steven.

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


Re: passing arguments to a function - do I need type ?

2005-07-10 Thread Paul McGuire
Is getCenter a function?  If so, you need to invoke distance using:
dist = self.distance( n.getCenter(), newElement )

Of course, that is assuming that newElement is a local variable of type
list/tuple/etc.

-- Paul

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


Re: passing arguments to a function - do I need type ?

2005-07-10 Thread Philipp H. Mohr
Hello,

thank you very much for all your help. I have solved the problem - you
guys where right, the problem was some where else.

I have another class which got an accessor:

def getCenter(self):
global center
return center


and I called it by saying n.getCenter, but this returns:

>

I changed it to n.getCenter() and now it works. Despite some small
problems I am really getting to like python.

Thank you,
Phil


On Sun, 10 Jul 2005, Paul McGuire wrote:

> Is getCenter a function?  If so, you need to invoke distance using:
> dist = self.distance( n.getCenter(), newElement )
>
> Of course, that is assuming that newElement is a local variable of type
> list/tuple/etc.
>
> -- Paul
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


PyArg_ParseTuple help

2005-07-10 Thread zyqnews
hello all,
  how to parse the arguments of a c function with PyArg_ParseTuple?
 The prototype of the c function is :
  int func(unsigned char * in , int inlen, unsigned char * v, unsigned
char * out, int * outlen);

The problem is , when the func returns, there will be results in out
and outlen. Is the following format is correct?

PyObject* wrap_func(PyObject* self, PyObject* args)
{
  unsigned char *in;
  int inlen;
  unsigned char *v;
  unsigned char *out;
  int outlen;

  PyArg_ParseTuple(args, "s|i|s|s|i", &in, &inlen, &v, &out, &outlen);

  result = func(in, inlen, v, out, &outlen);// notice out and &outlen

  return Py_BuildValue("i", result);
}

Thanks

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


Re: Berkely DB – many writers, many readers

2005-07-10 Thread Eric S. Johansson
Andy Leszczynski wrote:
> 
> I need to now option I open the Berkley DB (both db and env) to have 
> configuration for multiple writers and multiple readers.  Via multiple 
> processes  and multiple threads. No trx needed.

the simple answer is you can't.  bdbm is probably single writer multiple 
reader.  I believe if you use of the the most recent sleepy cat 
database, you have support for multiple readers and writers in any context.

when I did this, I stuck my gdbm database into a multithreaded 
stand-alone process.  I used XML RPC for access and used a per key 
locking mechanism internal to the data storage and retrieval process. 
This locking mechanism set appropriate locks so that a writer for 
specific key would wait for all readers of that key to finish, and block 
all subsequent readers until it was done.

so far is working pretty well but I haven't tried it in a high load 
situation.

---eric

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Pete Barrett
On 10 Jul 2005 02:57:04 -0700, "Xah Lee" <[EMAIL PROTECTED]> wrote:

>Similarly, in computer languages, expressiveness is significant with
>respect to semantics, not syntactical variation.
>
It may just be me, but I tend to think of a computer language as a
tool for directing computers to perform specific actions. Do we talk
about the expressiveness of a spade?

There's a similar concept in the 'possible uses' of a tool (a spade is
an excellent tool for digging the garden, but you wouldn't use it to
clean your teeth; you *could* use a toothbrush to dig the garden, but
you wouldn't if a spade was available). Similarly with computer
languages - some are better for certain tasks than others, but I don't
think 'expressiveness' is the way to describe that.

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Jürgen Exner
Xah Lee wrote:
> What is Expresiveness in a Computer Language[...]

Just for the records at Google et.al. in case someone stumbles across Xah's 
masterpieces in the future:
Xah is very well known as the resident troll in many NGs and his 
'contributions' are less then useless.

Best is to just ignore him.

But for heaven's sake unless you want to embarrass yourself really badly 
don't take any of his postings serious because he has proven again and again 
that he has no clue whatsoever about computer science or programming.

jue 


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


An absolute Newbie question

2005-07-10 Thread wpog
Hello,

I have a question about using "IDLE", and that is whenever I start write my  
own program in the "Python Shell" it will automatically execute whatever 
command I have written, for example: >>> print 'Hello World"

So, how to I get it to not execute, so that I can write a program that has 
ordinary executable functions, and stuff like that?

I do have some experience with Turbo Pascal, and so I'm hoping that this 
will be an even easier language to learn, and thus far it does seem so, but 
I need to get past this first;-).

Thanks in advance,

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


Re: computer algebra packages

2005-07-10 Thread François Pinard
[Florian Diesch]

> Probably this is usable for you (I never used any of them):

>  This system MAXIMA is [...] based on the original implementation of
>  Macsyma at MIT [...]

Wow!  A derivative of Joel Moses' integrator!!  I was not aware this
existed, so thanks for the pointer.  It worked out of the box for me!

> Description: A user-friendly frontend for MAXIMA
>  Mascyma is (trying to be) a user-friendly graphical frontend for the Computer
>  Algebra System GNU MAXIMA.  It is written in Python and provides two GUIs,
>  one of which based on PyGTK, the other based on wxPython.

I was not successful googling for this one.  Would you have an URL handy?

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An absolute Newbie question

2005-07-10 Thread dirk dierickx
On Sun, 10 Jul 2005 16:41:23 +, wpog wrote:

> So, how to I get it to not execute, so that I can write a program that has 
> ordinary executable functions, and stuff like that?

file > open new window

the new window will not execute your code you type in there.

-- 
The first thing we do, let's kill all the lawyers.
-- Wm. Shakespeare, "Henry VI", Part IV

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


Re: An absolute Newbie question

2005-07-10 Thread Brian van den Broek
wpog said unto the world upon 10/07/2005 12:41:
> Hello,
> 
> I have a question about using "IDLE", and that is whenever I start write my  
> own program in the "Python Shell" it will automatically execute whatever 
> command I have written, for example: >>> print 'Hello World"
> 
> So, how to I get it to not execute, so that I can write a program that has 
> ordinary executable functions, and stuff like that?
> 
> I do have some experience with Turbo Pascal, and so I'm hoping that this 
> will be an even easier language to learn, and thus far it does seem so, but 
> I need to get past this first;-).
> 
> Thanks in advance,
> 
> wpog

Take a look at .

But the quick answer:

Launch IDLE.
File Menu -> New Window
Type away. (Be sure to explicitly save with the py or pyw extension, 
as IDLE does not add it for you.)

HTH,

Brian vdB


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


Efficiency of using long integers to hold bitmaps

2005-07-10 Thread Jeff Melvaine
I note that I can write expressions like "1 << 100" and the result is stored 
as a long integer, which means it is stored as an integer of arbitrary 
length.  I may need to use a large number of these, and am interested to 
know whether the storage efficiency of long integers is in danger of 
breaking my code if I use too many.  Would I do better to write a class that 
defines bitwise operations on arrays of integers, each integer being assumed 
to contain at most 32 bits?  I cannot find information in the Python manuals 
for 2.4.1 that would allow me to resolve this question; perhaps the 
intention is that programmers should not rely on implementation details.

Thanks in advance,

Jeff 


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


Re: An absolute Newbie question

2005-07-10 Thread Scott Durkin
wpog,

In IDLE, go to the File menu and select New Window.  You can write your
program there.  Just save the file with the extension .py, such as
hello.py

Once the program is written, you can save the changes and press F5 to run
the script.

If you haven't checked out the links below, you might want to refer to them:

http://www.ibiblio.org/obp/thinkCSpy
http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html

Scott Durkin



   S  c  o  t  t J.D  u  r  k  i  n


 Computer Science    Preston Junior High

[EMAIL PROTECTED]    http://staffweb.psdschools.org/sdurkin

___   _  ___   _  ___   _  ___   _  ___   _
   [(_)] |=|[(_)] |=|[(_)] |=|[(_)] |=|[(_)] |=|
'-`  |_| '-`  |_| '-`  |_| '-`  |_| '-`  |_|
   /mmm/  / /mmm/  / /mmm/  / /mmm/  / /mmm/  /
 |||||
 |||
 ___  \_  ___  \_  ___  \_
   Computer   Room  [(_)] |=|[(_)] |=|[(_)] |=|
 Lab  N205   '-`  |_| '-`  |_| '-`  |_|
/mmm//mmm//mmm/


   970.419.7358    2005-2006
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Efficiency of using long integers to hold bitmaps

2005-07-10 Thread Raymond Hettinger
[Jeff Melvaine]
> I note that I can write expressions like "1 << 100" and the result is stored
> as a long integer, which means it is stored as an integer of arbitrary
> length.  I may need to use a large number of these, and am interested to
> know whether the storage efficiency of long integers is in danger of
> breaking my code if I use too many.  Would I do better to write a class that
> defines bitwise operations on arrays of integers, each integer being assumed
> to contain at most 32 bits?


Both array() objects and long integers are equally space efficient.
In contrast, a list of integers takes up a lot of space (the list is
stored as an array of pointers to individual integer objects).

Raymond

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


Re: computer algebra packages

2005-07-10 Thread François Pinard
> >  Mascyma is (trying to be) a user-friendly graphical frontend for
> >  the Computer Algebra System GNU MAXIMA.

> I was not successful googling for this one.  Would you have an URL handy?

Oops, OK!  Found it at  http://cens.ioc.ee/~pearu/misc/maxima/  .

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-10 Thread Ron Adam
Reinhold Birkenfeld wrote:
> Ron Adam wrote:
> 
> 
>>>>>> 'abc' is 'abcd'[:3]
>>>False
>>
>>Well of course it will be false... your testing two different strings! 
>>And the resulting slice creates a third.
>>
>>Try:
>>
>>ABC = 'abc'
>>
>>value = ABC
>>if value is ABC:   # Test if it is the same object
>>pass
> 
> 
> That's not going to buy you any time above the "is None", because identity-
> testing has nothing to do with the type of the object.

Ok, I retested it... Not sure why I was coming up with a small 
difference before.It seemed strange to me at the time which 
is part of why I asked.

My point was using strings "could" work in same context as None,  (if 
None acted as del), with out a performance penalty.  Anyway, this is all 
moot as it's an solution to a hypothetical situation that is not a good 
idea.

> Additionally, using "is" with immutable objects is horrible.

Why is it "horrible"?  Oh nevermind.  ;-)


Cheers,
Ron


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


Re: bsddb environment lock failure -- resolved

2005-07-10 Thread Barry
Upgrading db4 to db4-4.1.25-14.rpm seems to have take care of this. 



On 7/10/05, Barry <[EMAIL PROTECTED]> wrote:
> I have python2.4.1 installed on two machines:
> -- one is Fedora core 1, where the bsddb module works fine
> -- one is Redhat ES 3.0, and I installed mysql 4.1 (and
> mysql-python2.1) after putting the newer python on the machine.
> 
> python2.2, which came with Redhat ES, works fine, so I suppose I
> messed up the build.
> 
> I much appreciate any insight in how to fix this.
> 
> Barry
> 
> Here are some details:
> 
> When trying to open (or create) a db, I get this error
> 
>   File "/opt/Python-2.4.1/Lib/bsddb/__init__.py", line 285, in hashopen
> e = _openDBEnv()
>   File "/opt/Python-2.4.1/Lib/bsddb/__init__.py", line 339, in _openDBEnv
> e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK 
> |
> db.DB_INIT_MPOOL)
> bsddb._db.DBError: (38, 'Function not implemented -- process-private: unable 
> to
> initialize environment lock: Function not implemented')
> 
> I tried rebuilding python2.4.1, but 'make test' shows bsddb errors.
> 
>  First, there is:
> 
> test_bsddb3 skipped -- Use of the `bsddb' resource not enabled
> 
> test_whichdb shows the environment lock error
> 
> At the end, it's anydbm, bsddb, shelve, and whichdb failed.
> 
> I don't which of the differences in setup are important here, but both
> python.2.4.1 are installed in /opt
> 
> both have libdb-4.1, although slightly different:
> 
> The Fedora machine has libdb from db4-4.1.25-14.rpm
> The Redhat, from db4-4.1.25-8.1 -- this one also has libdb_cxx-3.1.so
> - libdb_cxx-3.3.so
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ZipFile and file rigths

2005-07-10 Thread ralobao
You can use os.chmod to fix it.

Here the description:

os.chmod

Docstring:
chmod(path, mode)

Change the access permissions of a file.

Cheers,

perchef escreveu:
> hi,
>
> i have written this small code which allow me to unzip files using
> python :
>
> import zipfile
> import os
> import os.path
>
> pathDir="/home/toto/Desktop"
> pathZip= os.path.join(pathDir,"foobar.zip")
>
> if zipfile.is_zipfile(pathZip):
> zf = zipfile.ZipFile(pathZip)
>
> for file in zf.namelist():
>   newPath = os.path.join(pathDir,file)
>   print newPath
>   if not file.endswith('/') and not os.path.exists(newPath) :
>   newFile = open(newPath, 'wb')
>   newFile.write(zf.read(file))
>   newFile.flush()
>   newFile.close()
>   else :
>   os.makedirs(newPath)
>
> zf.close()
> else:
> print pathZip + " is not a zip file"
>
> it works well but i have a small problem : i can't see how i can deal
> with file rights.
> When I unzip files with this script all the unzipped files haven't the
> good rights.
> for example :
>with this script :
>-rw-r--r-- foo.exe
>with a traditional zip program (ie : stuffit ):
>-rwxr-xr-x foo.exe
> ZipInfo objects doesn't store informations about rights ?
> (http://www.python.org/doc/current/lib/zipinfo-objects.html#zipinfo-objects)
> 
> How can i fix this ?

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


Re: PyArg_ParseTuple help

2005-07-10 Thread Qiangning Hong
[EMAIL PROTECTED] wrote:
> hello all,
>   how to parse the arguments of a c function with PyArg_ParseTuple?
>  The prototype of the c function is :
>   int func(unsigned char * in , int inlen, unsigned char * v, unsigned
> char * out, int * outlen);
> 
> The problem is , when the func returns, there will be results in out
> and outlen. Is the following format is correct?

As the ``out'' and ``outlen'' are used for output, you should not pass
them to a python function as parameters.  Instead, you'd better make the
return value of the python function to represent them (if the python
caller wants them, of course).  In your case, returning a python string
object will be a good choice if outlen is the length of out array, since
a python string knows its length.

So, you need only parse the parameters of ``in'', ``inlen'' and ``v'' in
the wrap function.  And even further, the python caller can pass a
python string to replace ``in'' and ``inlen''.  Then, the prototype of
the function is something like:

def func(ins, v)

which returns a string.

[...]

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


urllib2.urlopen hangs, urllib.urlopen works?

2005-07-10 Thread Chris
hello,
I have an odd behaviour. I try to download some files connected to a 
specific webpage (e.g. all stylesheets) with
urllib2.urlopen(x)
This seems to hang on the 2nd file or so.

Doing the exact same thing via
urllib.urlopen(x)
does work without a hitch...

I don't really to use urllib instead of urllib2 but am wondering where 
the problem is and if there is a workaround (or just my own stupidity)?
Also with urllib I cannot send my own user-agent header as i wanted to do...

thanks for any hint!

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


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Ron Adam
Roy Smith wrote:

> Thomas Lotze <[EMAIL PROTECTED]> wrote:
> 
>>Basically, I agree with the "make it run, make it right, make it fast"
>>attitude. However, FWIW, I sometimes can't resist optimizing routines that
>>probably don't strictly need it. Not only does the resulting code run
>>faster, but it is usually also shorter and more readable and expressive.
> 
> 
> Optimize for readability and maintainability first.  Worry about speed 
> later.

Yes, and then...

If it's an application that is to be used on a lot of computers, some of 
them may be fairly old.  It might be worth slowing your computer down 
and then optimizing the parts that need it.

When it's run on faster computers, those optimizations would be a bonus.

Cheers,
Ron

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


Re: Python Module Exposure

2005-07-10 Thread Jacob Page
George Sakkis wrote:
> "Jacob Page" <[EMAIL PROTECTED]> wrote:
> 
>>If the union of two integers yielded a set of integers, then
>>it'd make more since for the union of two Intervals to yield an
>>IntervalSet.
> 
> AFAIK union is defined over sets, not numbers, so I'm not sure what you
> mean by the "union of two integers". What I'm saying is that while the
> union of two intervals is always defined (since intervals are sets),
> the result set is not guaranteed to be an interval. More specifically,
> the result is an interval if and only if the intervals overlap, e.g.
> (2,4] | [3,7] = (2,7]
> but
> (2,4] | [5,7] = { (2,4], [5,7] }
> That is, the set of intervals is not closed under union. OTOH, the set
> of intervals _is_ closed under intersection; intersecting two
> non-overlapping intervals gives the empty interval.

OK, you've convinced me now to support and, or, and xor between every 
combination of Intervals and IntervalSets, Intervals and IntervalSets, 
and IntervalSets and Intervals.  However, I'm not sure I  like the idea 
of an operation generating either one type or another.  Thus, I'll have 
| and ^ operations between Intervals always return an IntervalSet 
instead of returning either an IntervalSet or an Interval.  & will 
return an Interval.  I suppose that means I should just have + do a 
union and - return an IntervalSet.  It will just have to be documented 
which types are to be expected for the return values depending on the 
operands.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ZipFile and file rigths

2005-07-10 Thread perchef
ok thanks, it works even if it's a little bit dirty.

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread James Dennett
Pete Barrett wrote:

> On 10 Jul 2005 02:57:04 -0700, "Xah Lee" <[EMAIL PROTECTED]> wrote:
> 
> 
>>Similarly, in computer languages, expressiveness is significant with
>>respect to semantics, not syntactical variation.
>>
> 
> It may just be me, but I tend to think of a computer language as a
> tool for directing computers to perform specific actions. Do we talk
> about the expressiveness of a spade?

Spades, however, are rarely used for communication between
human beings, whereas languages, definitely including
programming languages, are.  While there's a good case to
be made that communication from a person to a computer is
the *primary* use of a programming language, communication
between programmers is a major secondary use.

> There's a similar concept in the 'possible uses' of a tool (a spade is
> an excellent tool for digging the garden, but you wouldn't use it to
> clean your teeth; you *could* use a toothbrush to dig the garden, but
> you wouldn't if a spade was available). Similarly with computer
> languages - some are better for certain tasks than others, but I don't
> think 'expressiveness' is the way to describe that.

You're missing, maybe, the very special nature of one task,
namely that of communication between programmers.  Computers
care not if you use assembly code or Python, but people often
find one or the other easier to read and understand.  (Which
is considered easier depends on the background of the reader.)

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


Re: Defending Python

2005-07-10 Thread Bruno Desthuilliers
Jorey Bump a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> wrote in 
> news:[EMAIL PROTECTED]:
> 
> 
>>Grant Edwards a écrit :
>>
>>>On 2005-07-09, Brian <[EMAIL PROTECTED]> wrote:
>>>
>>>
>>>
>folks as an easily acquired extra skill.

I agree 100% with your statement above.  Python may not be sufficient 
for being the only programming language that one needs to know -- yet, 
it does come in VERY handy for projects that need to perform tasks on 
non-Microsoft operating systems.  :-)
>>>
>>>
>>>It's also darned handy for projects that need to perform tasks
>>>on Microsft operating systems but you want to do all the
>>>development work under a real OS.
>>>
>>
>>It's also darned handy for projects that need to perform tasks on 
>>Microsft operating systems.
> 
> 
> It's also darned handy for projects that need to perform tasks... Or 
> don't... And for other things besides projects...
> 
> Anyway, it's darned handy!

it's.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An absolute Newbie question

2005-07-10 Thread wpog
WOW!!!

I really appreciate the immediate response from the community!!! I thank 
you all for all the help, and now I can start programming, and I also now 
have a resource for help for a Newbie;-)

Later on I will broach the subject of creating .exe programs so that anyone 
can run them on Windows, but that won't be for a while yet, but I did 
download ":cx_Freeze-3.0.1-win32-py24"; however, I don't have a clue on 
what the hell I'm doing yet, so I'll get to that later.

Anyway, I once again thank you all for the support, and suggestions, and I 
hope to actually create something that people might use, like a magic 8 
ball generator!;-p

Best Regards,
wpog




"Scott Durkin" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> wpog,
> 
> In IDLE, go to the File menu and select New Window.  You can write
> your program there.  Just save the file with the extension .py, such
> as hello.py
> 
> Once the program is written, you can save the changes and press F5 to
> run the script.
> 
> If you haven't checked out the links below, you might want to refer to
> them: 
> 
> http://www.ibiblio.org/obp/thinkCSpy
> http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html
> 
> Scott Durkin
> 
> 
> 
>S  c  o  t  t J.D  u  r  k  i  n
> 
> 
>  Computer Science    Preston Junior High
> 
> [EMAIL PROTECTED]    http://staffweb.psdschools.org/sdurkin
> 
> ___   _  ___   _  ___   _  ___   _  ___   _
>[(_)] |=|[(_)] |=|[(_)] |=|[(_)] |=|[(_)] |=|
> '-`  |_| '-`  |_| '-`  |_| '-`  |_| '-`  |_|
>/mmm/  / /mmm/  / /mmm/  / /mmm/  / /mmm/  /
>  |||||
>  |||
>  ___  \_  ___  \_  ___  \_
>Computer   Room  [(_)] |=|[(_)] |=|[(_)] |=|
>  Lab  N205   '-`  |_| '-`  |_| '-`  |_|
> /mmm//mmm//mmm/
> 
> 
>970.419.7358    2005-2006
> 

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Keith Thompson
"Xah Lee" <[EMAIL PROTECTED]> writes:
> What is Expresiveness in a Computer Language
>
> 20050207, Xah Lee.

 +---+ .:\:\:/:/:.
 |   PLEASE DO NOT   |:.:\:\:/:/:.:
 |  FEED THE TROLLS  |   :=.' -   - '.=:
 |   |   '=(\ 9   9 /)='
 |   Thank you,  |  (  (_)  )
 |   Management  |  /`-vvv-'\
 +---+ / \
 |  |@@@  / /|,|\ \
 |  |@@@ /_//  /^\  \\_\
   @x@@x@|  | |/ WW(  (   )  )WW
   \/|  |\|   __\,,\ /,,/__
\||/ |  | |  jgs (__Y__)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
==

-- 
Keith Thompson (The_Other_Keith) [EMAIL PROTECTED]  
San Diego Supercomputer Center <*>  
We must do something.  This is something.  Therefore, we must do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators as generalized pre-binding hooks

2005-07-10 Thread Terry Reedy

"Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> The binding of a class name is similar, and class decorators
> would seem natural, i.e.,
>
>@cdeco
>class Foo: pass
> for
>class Foo: pass
>Foo = cdeco(Foo)

This possibility was discussed on the py-dev list about a year or so ago. 
The twice monthly summaries should include this topic.  As I remember, the 
reason for limiting to functions included:

1. classes have metaclasses, functions don't have metafunctions.  No one 
gave an example for classes not handled at least as well with a metaclass.

2. certain applications require long-function_names_like_this, for which 
triple typing is substantially annoying and error-prone.

Terry J. Reedy



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


Re: Efficiency of using long integers to hold bitmaps

2005-07-10 Thread Bengt Richter
On Mon, 11 Jul 2005 02:37:21 +1000, "Jeff Melvaine" <[EMAIL PROTECTED]> wrote:

>I note that I can write expressions like "1 << 100" and the result is stored 
>as a long integer, which means it is stored as an integer of arbitrary 
>length.  I may need to use a large number of these, and am interested to 
>know whether the storage efficiency of long integers is in danger of 
>breaking my code if I use too many.  Would I do better to write a class that 
>defines bitwise operations on arrays of integers, each integer being assumed 
>to contain at most 32 bits?  I cannot find information in the Python manuals 
>for 2.4.1 that would allow me to resolve this question; perhaps the 
>intention is that programmers should not rely on implementation details.
>
>Thanks in advance,
>
Sounds like a possible^H^H^H^H^H^H^H^Hprobable premature optimization worry ;-)

What is a "large number of these" going to amount to? How many, tops?
And how many bits in each? How many operations between them? (Since integers
are immutable, operations mean allocation of space for new ones for results
and disposing of unused garbage ones (probably back to a special fast pool for
integers and longs)). Are you interested in a speed/memory tradeoff?

If your bit vectors are extremely large and sparse (have only a few bits "on"),
you might consider sets (import sets and help(sets)) of the bit numbers as 
representations.

BTW, I wonder if anyone has written an ordered bit set class in C yet. I was 
tempted ;-)

How much memory do you have? Buying more can be a pretty cheap way of solving 
space worries
if you are getting paid for your time.

You should be able to subclass int or long as a way of writing your program in 
terms of
your own bit vector class. Then you can change your mind and change the 
underlying representation
without changing the code that uses the api. Compared to plain longs it will 
cost you some speed
to keep converting results to your own type though.

Bottom line, whether your code will "break" due to storage problems or be fast 
enough
will depend on numbers you didn't provide ;-)

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


Re: Use cases for del

2005-07-10 Thread Terry Reedy

"Ron Adam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> To avoid that you either need to define the flag string as a global name
> or use it strictly in the local scope it's defined in.  Python will also
> sometimes reuse strings as an optimization instead of creating a second
> string if they are equal.  Something else to be aware of.

I believe CPython's string equality function first checks the two strings 
for identity.  So one gets most of the benefit of 'is' testing anyway.  (An 
I presume it next check for length equality.)

tjr 



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


Re: Defending Python

2005-07-10 Thread Jorey Bump
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Jorey Bump a écrit :
>> Bruno Desthuilliers <[EMAIL PROTECTED]> wrote
>> in news:[EMAIL PROTECTED]:
>> 
>>>Grant Edwards a écrit :
>>>
On 2005-07-09, Brian <[EMAIL PROTECTED]> wrote:

>>folks as an easily acquired extra skill.
>
>I agree 100% with your statement above.  Python may not be
>sufficient for being the only programming language that one needs
>to know -- yet, it does come in VERY handy for projects that need
>to perform tasks on non-Microsoft operating systems.  :-)

It's also darned handy for projects that need to perform tasks
on Microsft operating systems but you want to do all the
development work under a real OS.
>>>
>>>It's also darned handy for projects that need to perform tasks on 
>>>Microsft operating systems.
>> 
>> It's also darned handy for projects that need to perform tasks... Or 
>> don't... And for other things besides projects...
>> 
>> Anyway, it's darned handy!
> 
> it's.

+1 for this becoming the official name of Python 3000. ;)

And now for something completely different...

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

RE: Yet Another Python Web Programming Question

2005-07-10 Thread Robert Brewer
Paul Boddie wrote:
> "Robert Brewer" <[EMAIL PROTECTED]> wrote in message 
> news:<[EMAIL PROTECTED]>...
> > Daniel Bickett wrote:
> > > I neglected to mention an important fact, and that is the 
> > > fact that I am limited to Apache, which elminates several
> > > suggestions (that are appreciated none-the-less).
> > 
> > Do you have access to mod_python, mod_rewrite, FastCGI, or 
> > SCGI? Then CherryPy 2.1 is still a great option for you with
> > Apache:
> > http://www.cherrypy.org/wiki/WSGIServers
> > http://www.cherrypy.org/wiki/BehindApache
> 
> According to the "quick facts" page "CherryPy powered web
> applications are in fact stand-alone Python applications embedding
> their own multi-threaded web server", suggesting that if the hosting
> environment is "limited to Apache" and if this can also be taken to
> mean that the environment doesn't permit long-running server processes
> apart from Apache, then CherryPy isn't likely to be suitable.

Thanks for pointing that out; that page was out of date, and has now
been corrected: http://www.cherrypy.org/wiki/CherryPyQuickFacts .
CherryPy 2.1 apps can be deployed using Apache (via mod_python) or IIS
(via ASP) as the webserver *without* running the webserver built into
CherryPy. In fact, CherryPy should work with any WSGI-capable webserver,
and be deployable in a wide variety of hosting environments with no
changes to your application code.


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


Re: ZipFile and file rigths

2005-07-10 Thread Sybren Stuvel
perchef enlightened us with:
> it works well but i have a small problem : i can't see how i can
> deal with file rights.  When I unzip files with this script all the
> unzipped files haven't the good rights.

That's right. Why should they? ZIP doesn't store file permissions.

> ZipInfo objects doesn't store informations about rights ?

Correct.

> How can i fix this ?

Don't use ZIP. Use tar instead.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Terry Reedy

"Ralf W. Grosse-Kunstleve" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

I have a suggestion I don't remember seeing for flagging which vars to 
autoinit without new syntax: use '_' instead of '.'.  I have never seen 
local vars with a leading '_'.  So, in combination with whatever other 
mechanism (metaclass, __init__ decorator?)

   def __init__(self, _x, y, _z) :

would automatically do self.x = _x, self.z = _z, but not self.y = y.

Terry J. Reedy



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


Re: Yet Another Python Web Programming Question

2005-07-10 Thread Sybren Stuvel
Daniel Bickett enlightened us with:
> It would be a long while before he would find Python, and since that
> time he would have no desire to ever touch PHP again.

My thoughts exactly.

> He would, however, be compelled to write a web application again,
> but in Python now, of course.

Same here :)

> * They required installation (as opposed to, simply, the placement
> of modules), whereas the only pythonic freedom he had on his hosting
> was a folder in his /home/ dir that was in the python system path.

I can't help you here. For instance, if you want to get a proper
performance, you should install something like mod_python to get
Python functionality in Apache.

> Python using CGI, for example, was enough for him until he started
> getting 500 errors that he wasn't sure how to fix.

Check the web server's error logs.


My solution was to take a look at Cheetah. It's a template engine
that's written in Python. I've written a mod_python handler for it so
I can easily create & edit my website using Cheetah as a template
engine. Check out http://www.unrealtower.org/mycheetah if you want to
read more about the handler & other stuff I wrote. Perhaps you can
even help me improve it!

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should I use "if" or "try" (as a matter of speed)?

2005-07-10 Thread Sybren Stuvel
Steve Juranich enlightened us with:
> Without fail, when I start talking with some of the "old-timers"
> (people who have written code in ADA or Fortran), I hear the same
> arguments that using "if" is "better" than using "try". 

Then here is the counter argument:

- Starting a 'try' is, as said somewhere else in this thread, a single
  bytecode, hence simple.

- Those old-timers will probably check the data before they pass it to
  a function. Because their function has to be stable and idiot-proof
  as well, the function itself performs another check. Maybe the data
  is passed even further down a function chain, making checks before
  and after the function calls. After all, we want to be sure to only
  call a function when we're sure it won't fail, and every function
  has to gracefully bail when it's being passed bad data.

This means that there will be a _lot_ of checks in the code. Now
compare this by setting up a single try-block, and catching the
exception at the proper place in case it's being thrown.

The important part is this: those old-timers' "if" statements are
always executed - it doesn't matter whether the data is correct or
incorrect. The "heavy" part of exceptions only comes into play when
the data is incorrect, which by proper design of the program shouldn't
happen often anyway.

As far as I see it, try/except blocks are "cheaper" than "if"
statements.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Read-only class properties

2005-07-10 Thread George Sakkis
I'm trying to write a decorator similar to property, with the
difference that it applies to the defining class (and its subclasses)
instead of its instances. This would provide, among others, a way to
define the equivalent of class-level constants:

class Foo(object):
@classproperty
def TheAnswer(cls):
return "The Answer according to %s is 42" % cls.__name__

>>> Foo.TheAnswer
The Answer according to Foo is 42
>> Foo.TheAnswer = 0
exceptions.AttributeError
...
AttributeError: can't set class attribute

I read the 'How-To Guide for Descriptors'
(http://users.rcn.com/python/download/Descriptor.htm) that describes
the equivalent python implementation of property() and classmethod()
and I came up with this:

def classproperty(function):
class Descriptor(object):
def __get__(self, obj, objtype):
   return function(objtype)
def __set__(self, obj, value):
raise AttributeError, "can't set class attribute"
return Descriptor()

Accessing Foo.TheAnswer works as expected, however __set__ is
apparently not called because no exception is thrown when setting
Foo.TheAnswer. What am I missing here ?

George

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


Re: computer algebra packages

2005-07-10 Thread Robert Kern
François Pinard wrote:
> [Florian Diesch]

>>Description: A user-friendly frontend for MAXIMA
>> Mascyma is (trying to be) a user-friendly graphical frontend for the Computer
>> Algebra System GNU MAXIMA.  It is written in Python and provides two GUIs,
>> one of which based on PyGTK, the other based on wxPython.
> 
> I was not successful googling for this one.  Would you have an URL handy?

Note the deliberate spelling, and cut-and-paste.

http://home.arcor.de/mulk/projects/mascyma/index.xhtml.de

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Another newbie question from Nathan.

2005-07-10 Thread johng2001
Nathan Pinno wrote:
> Hi all,
>
>   How do I make Python get a def? Is it the "get" function, or something
> else? I need to know so that I can get a def for that computer
> MasterMind(tm) game that I'm writing.
>
>   BTW, I took your advice, and wrote some definitions for my Giant
> Calculator program. Might make the code easier to read, but harder to code
> because I have to keep going to the top to read the menu. Not that fun, but
> necessary for a smooth program, I guess.
>
>   Nathan Pinno

Read the following tutorials first, perhaps in that order.

http://honors.montana.edu/~jjc/easytut/easytut/
http://www.ibiblio.org/obp/thinkCSpy/
http://docs.python.org/tut/tut.html

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


Re: decorators as generalized pre-binding hooks

2005-07-10 Thread Bengt Richter
On Sun, 10 Jul 2005 05:35:01 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:

>Bengt Richter wrote:
>> ;-)
>> We have
>
>Have we?
>
>Looks like not a lot of interested takers so far.
>
>But I'll bite. ;-)
>
>
>
>
>> So why not
>> 
>> @deco
>> foo = lambda:pass
>> equivalent to
>> foo = deco(lambda:pass)
> >
>> and from there,
>> @deco
>>  = 
>> being equivalent to
>>  = deco()
>> 
>> e.g.,
>> @range_check(1,5)
>> a = 42
>> for
>> a = range_check(1,5)(42)
>> 
>> or
>> @default_value(42) 
>> b = c.e['f']('g')
>> for
>> b = default_value(42)(c.e['f']('g'))
>
>So far they are fairly equivalent.  So there's not really any advantage 
>over the equivalent inline function.  But I think I see what you are 
>going towards.  Decorators currently must be used when a function is 
>defined.  This option attempts to makes them more dynamic so that they 
>can be used where and when they are needed.
IMO part of the decorator benefit is clearer code, and also IMO the @range_check
and @default_value decorators succeed in that. The code generated would 
presumably
be the same, unless the exception capture discussed further down were 
implemented.

>
>How about if you make it optional too?
>
>if keep_log:
>@log_of_interesting_values
>b = get_value(c,d):
>
I'd probably pass the condition to the decorator for a less ragged look
@log_of_interesting_values(keep_log)
b = get_value(c,d)
>Or...
>
>@@keeplog log_of_interesting_values # if keeplog decorate.
>b = get_value(c,d)
>
>Just a thought.
Yes, but that is too easy to do another way. Plus I want to reserve '@@' for an 
AST-time
decoration idea I have ;-)

>
>> Hm, binding-intercept-decoration could be sugar for catching exceptions too,
>> and passing them to the decorator, e.g., the above could be sugar for
>> 
>> try:
>> b = default_value(42)(c.e['f']('g'))
>> except Exception, e:
>> b = default_value(__exception__=e) # so decorator can check
>># and either return a value or just re-raise 
>> with raise [Note 1]
>
>I'm not sure I follow this one.. Well I do a little. Looks like it might 
>be going the direction of with statements, but only applied to a single 
>expression instead of a block or suite.

Yes, it's just expanding on the idea of intercepting the value of the object 
being bound even
if the creation of that object resulted in an exception, and allowing the 
decorator to handle
it either way.
>
>
>> This might be useful for plain old function decorators too, if you wanted 
>> the decorator
>> to define the policy for substituting something if e.g. a default argument 
>> evaluation
>> throws and exception. Thus
>> 
>> @deco
>> def foo(x=a/b): pass # e.g., what if b==0?
>> as
>> try:
>> def foo(x=a/b): pass # e.g., what if b==0?
>> foo = deco(foo)
>> except Exception, e:
>> if not deco.func_code.co_flags&0x08: raise #avoid mysterious 
>> unexpected keyword TypeError
>> foo = deco(__exception__=e)
>
>Wouldn't this one work now?
I think all the second-versions would work now, but a plain decorator won't get 
control if the
def fails, so the def name won't get bound:

 >>> def deco(f): print f; return f # noop
 ...
 >>> @deco
 ... def foo(x=1/2): pass
 ...
 
 >>> foo
 
 >>> del foo
 >>> foo
 Traceback (most recent call last):
   File "", line 1, in ?
 NameError: name 'foo' is not defined
 >>> @deco
 ... def foo(x=1/0): pass
 ...
 Traceback (most recent call last):
   File "", line 1, in ?
 ZeroDivisionError: integer division or modulo by zero
 >>> foo
 Traceback (most recent call last):
   File "", line 1, in ?
 NameError: name 'foo' is not defined

>
>> [Note 1:]
>> Interestingly raise doesn't seem to have to be in the same frame or 
>> down-stack, so a decorator
>> called as above could re-raise:
>> 
>>  >>> def deco(**kw):
>>  ... print kw
>>  ... raise
>>  ...
>>  >>> try: 1/0
>>  ... except Exception, e: deco(__exception__=e)
>>  ...
>>  {'__exception__': }
>>  Traceback (most recent call last):
>>File "", line 2, in ?
>>File "", line 1, in ?
>>  ZeroDivisionError: integer division or modulo by zero
>
>Interestin.
Yes, it would seem to give one the option of catching an exception and
doing some arbitarily (so long as not new-exception-raising) recursive
or deep calls and bailing out from some leaf point with a raise.

>
>When it comes to decorators, and now the with statements, I can't help 
>but feel that there's some sort of underlying concept that would work 
>better.  It has to do with generalizing flow control in a dynamic way 
>relative to an associated block.
>
>One thought is to be able to use a place holder in an expression list to 
>tell a statement when to do the following block of code.
it depends on scope and control aspects of what you mean by "block".
But I doubt if we have much chance of introducing something is one more
bf in the storm of "with" ideas that have already been disc

Re: ZipFile and file rigths

2005-07-10 Thread Robert Kern
perchef wrote:
> hi,
> 
> i have written this small code which allow me to unzip files using
> python :
> 
> import zipfile
> import os
> import os.path
> 
> pathDir="/home/toto/Desktop"
> pathZip= os.path.join(pathDir,"foobar.zip")
> 
> if zipfile.is_zipfile(pathZip):
> zf = zipfile.ZipFile(pathZip)
> 
> for file in zf.namelist():
>   newPath = os.path.join(pathDir,file)
>   print newPath
>   if not file.endswith('/') and not os.path.exists(newPath) :
>   newFile = open(newPath, 'wb')
>   newFile.write(zf.read(file))
>   newFile.flush()
>   newFile.close()
>   else :
>   os.makedirs(newPath)
> 
> zf.close()
> else:
> print pathZip + " is not a zip file"
> 
> it works well but i have a small problem : i can't see how i can deal
> with file rights.
> When I unzip files with this script all the unzipped files haven't the
> good rights.
> for example :
>with this script :
>-rw-r--r-- foo.exe
>with a traditional zip program (ie : stuffit ):
>-rwxr-xr-x foo.exe
> ZipInfo objects doesn't store informations about rights ?
> (http://www.python.org/doc/current/lib/zipinfo-objects.html#zipinfo-objects)
> 
> How can i fix this ?

This is possibly related, I'm not sure:

http://article.gmane.org/gmane.comp.python.apple/8012

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Defending Python

2005-07-10 Thread Peter Hansen
Jorey Bump wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
>>it's.
> 
> +1 for this becoming the official name of Python 3000. ;)
> 
> And now for something completely different...
> 
> The larch!

Sorry, already taken:

'''Larch - John Guttag and Jim Horning <[EMAIL PROTECTED]>. The Larch 
Project develops aids for formal specifications. Each Larch 
specification has two components: an interface containing predicates 
written in the LIL (Larch Interface Language) designed for the target 
language and a 'trait' containing assertions about the predicates 
written in LSL, the Larch Shared Language common to all. "The Larch 
Family of Specification Languages", J. Guttag et al, IEEE Trans Soft Eng 
2(5):24-365 (Sep 1985). "Larch: Languages and Tools for Formal 
Specification", Guttag and Horning, Springer 1993.'''

Maybe "Ni!"?

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


inheritance

2005-07-10 Thread J
Hi


I am trying to make a C++ class hierarchy accessible to python scripts.
Am I right to assume that the type structure of a derived class must
have all the members of its base class declared as well ?

For example,

typedef struct
{
PyObject_HEAD
int somebaseclassmember;
} PyStructBaseClass

is the structure for a base class. In this case, the structure for a
derived class would have to look like

typedef struct
{
PyObject_HEAD
ScnNode* mObject;
int somebaseclassmember;
float somederivedclassmember

} PyStructDerivedClass;


Is this true ? I have linked the derived class type to the base class
type via tp_base. I don't think that when I instantiate a derived
class, a PyStructBaseClass is being created. I believe that if
PyStructDerivedClass was missing the "int somebaseclassmember;" then
the offset for that memory would point into the float during base class
member lookups  ???

Any thoughts ?

Cheers
Jochen

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


Re: Python Module Exposure

2005-07-10 Thread George Sakkis
"Jacob Page" <[EMAIL PROTECTED]> wrote:

> OK, you've convinced me now to support and, or, and xor between every
> combination of Intervals and IntervalSets, Intervals and IntervalSets,
> and IntervalSets and Intervals.

I'm sorry, this was not my intention .

> However, I'm not sure I  like the idea
> of an operation generating either one type or another.

I don't like it either; it makes the user's work harder by forcing him
to check the result's type, and then either process each type
differently or wrap Intervals into IntervalSets and deal with the
latter only.

> Thus, I'll have
> | and ^ operations between Intervals always return an IntervalSet
> instead of returning either an IntervalSet or an Interval.  & will
> return an Interval.  I suppose that means I should just have + do a
> union and - return an IntervalSet.  It will just have to be documented
> which types are to be expected for the return values depending on the
> operands.

This is better, but still I'm not sure if it's good enough. Splitting
the set of operators into those returning Interval and those returning
IntervalSet has to be documented of course, but nevertheles it is not
intuitive for the simple user who doesn't think about closed and
non-closed operations. It's a viable option though. The other two
options are:

- Return always an IntervalSet from all five operators (~, |, &, ^, -).
This is inconvenient for at least intersection and difference which are
known to be closed operations.

- Go back to your initial preference, that is don't support any
operator at all for Intervals. Given that in your new version there are
factories in IntervalSet as well, it's not as bad as before; simply the
user can create Intervals through the IntervalSet factories. You can
take this even further by disallowing (or discouraging at least) the
user to instantiate Intervals directly. An analogy is the Match type in
the re module. Match objects are returned by re.match() and re.search()
and they expose a set of useful methods (group(), groups(), etc.).
However if the user attempts to create a Match instance, a TypeError is
raised. Currently I like this option better; it's both user and
developer friendly :)

George

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Kenny McCormack
In article <[EMAIL PROTECTED]>,
Pete Barrett  <[EMAIL PROTECTED]> wrote:
>On 10 Jul 2005 02:57:04 -0700, "Xah Lee" <[EMAIL PROTECTED]> wrote:
>
>>Similarly, in computer languages, expressiveness is significant with
>>respect to semantics, not syntactical variation.
>>
>It may just be me, but I tend to think of a computer language as a
>tool for directing computers to perform specific actions. Do we talk
>about the expressiveness of a spade?

Most people think of natural language as "a tool for directing people to
perform specific actions" and have as much need for anything beyond that as
you seem to have.

Luckily, some people (writers, artists) are able to do more with natural
language than boss people around.  But make no mistake, that is its primary
purpose.

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


Re: computer algebra packages

2005-07-10 Thread François Pinard
[Robert Kern]
> François Pinard wrote:
> > [Florian Diesch]

> >> Mascyma is (trying to be) a user-friendly graphical frontend for
> >> the Computer Algebra System GNU MAXIMA.  It is written in Python
> >> and provides two GUIs, one of which based on PyGTK, the other based
> >> on wxPython.

> > I was not successful googling for this one.  Would you have an URL handy?

> Note the deliberate spelling, and cut-and-paste.

Thanks.  The `Mascyma' versus `Macsyma' subtlety escaped my scrutiny :-).

> http://home.arcor.de/mulk/projects/mascyma/index.xhtml.de

Their CVS server (the only download choice) is not responding.  So I'll
forget "Mascyma" for now.  Maxima does work, that's a lot already! :-) I
perused what I could find about Python on algebra or symbolic calculus,
and nothing I saw, so far, stands even a pale comparison with Maxima.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Matthias Buelow
Steven D'Aprano <[EMAIL PROTECTED]> writes:

>On Sun, 10 Jul 2005 07:20:34 -0700, raptor wrote:
>
>> I think u are wrong.. I think perl is much more exrpressive in
>> semantics than Python..
>
>Well, with such great command of natural language as you are displaying,
>how could anyone argue with your conclusion?

Folks, Xah Lee is a known troll.. don't get into any arguments among
yourselves over anything that person writes.

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


Re: An absolute Newbie question

2005-07-10 Thread Justin Straube
wpog wrote:

> I have a question about using "IDLE", and that is whenever I start write my  
> own program in the "Python Shell" it will automatically execute whatever 
> command I have written, for example: >>> print 'Hello World"
> 
> So, how to I get it to not execute, so that I can write a program that has 
> ordinary executable functions, and stuff like that?

Also if you open IDLE and in the menu bar go to Options >> Configure IDLE, 
select the 'General' tab and you can specify if you want the interactive prompt 
  or an Edit Window to open at startup.

Then hitting F5 will execute the written code, and you can also go to Run >> 
Python Shell and open an interactive prompt window.

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


Re: decorators as generalized pre-binding hooks

2005-07-10 Thread George Sakkis
"Terry Reedy" <[EMAIL PROTECTED]> wrote:

> "Bengt Richter" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > The binding of a class name is similar, and class decorators
> > would seem natural, i.e.,
> >
> >@cdeco
> >class Foo: pass
> > for
> >class Foo: pass
> >Foo = cdeco(Foo)
>
> This possibility was discussed on the py-dev list about a year or so ago.
> The twice monthly summaries should include this topic.  As I remember, the
> reason for limiting to functions included:
>
> 1. classes have metaclasses, functions don't have metafunctions.  No one
> gave an example for classes not handled at least as well with a metaclass.

Would something like the following count ?

@abstractclass
class AbstractFrame(object):

@abstractclass
@innerclass
class AbstractPanel(object):
pass

For one thing, it's more readable than the respective __metaclass__
declarations. Moreover, stacking two or more decorators is
syntactically straightforward, while for metaclasses you have to write
boilerplate code for making a subclass of the components, e.g.:
class AbstractInnerClass(AbstractClass, InnerClass): pass
Fortunately metaclasses are not that commonly used to cause
combinatorial explosion of such boilerplate classes.

> 2. certain applications require long-function_names_like_this, for which
> triple typing is substantially annoying and error-prone.

I'm not sure what you mean here; where is the 'triple typing' ? And how
is this an argument against class decorators ?
 
George

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


Re: ZipFile and file rigths

2005-07-10 Thread perchef
> ZIP doesn't store file permissions.
ok, but in that case how could stuffit retrieve these permissions ?

Thanks for the link Robert.

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


AST decoration vs byte-code-munging (Was: Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code))

2005-07-10 Thread Bengt Richter
On Sun, 10 Jul 2005 16:26:24 -0400, "Terry Reedy" <[EMAIL PROTECTED]> wrote:

>
>"Ralf W. Grosse-Kunstleve" <[EMAIL PROTECTED]> wrote in message 
>news:[EMAIL PROTECTED]
>
>I have a suggestion I don't remember seeing for flagging which vars to 
>autoinit without new syntax: use '_' instead of '.'.  I have never seen 
>local vars with a leading '_'.  So, in combination with whatever other 
>mechanism (metaclass, __init__ decorator?)
>
>   def __init__(self, _x, y, _z) :
>
>would automatically do self.x = _x, self.z = _z, but not self.y = y.
>
Of course, if it works for __init__, it should work for an arbitrary
method or even function (if a decorator is used).

I think I could write a byte-code-modifying decorator that would insert
code at the beginning of a function to do the
self.x = _x; self.z = _z # but not self.y = y
in your example, and similarly for others.
But I am not sure it's not a waste of time to do these byte-code things
except to see how using such decorators feels in practice, or whether any
byte-code munging after generation is a good idea.

What would be the next step? To implement the same in C as a built in decorator?
I'm wondering if the effort of munging byte code isn't misplaced, and would 
create
a growing maintenance problem as more built-in decorators like that accumulated.

So, if we want alternate code generated, perhaps we need a way of talking to the
original code generation process? I'm thinking some kind of 
source-processing-time
decorator (maybe marked with double-@, like
@@auto_init_self_attributes
def __init__(self, _x, y, _z) : print 'self.y=%r not set'%y

The idea is for @@deco to be intercepted as part of the AST of the unit being 
compiled,
and be converted at that time to call with the AST and its own location in the 
tree being
passed to it so it can do mods to the AST  (and cut itself out), and then let 
the resulting
AST be compiled as normal. Multiple @@decorators would each get their chance to 
mod the AST
before compilation. This still would have some version dependency, but it 
wouldn't be
byte code hacking ;-) One of these days I'll think some more on @@. As an 
experiment, I think
the tokenizer could translate @@deco to _AT_AT_deco and let the AST be formed 
with that
apparent function call at that place in the code. Then the AST could be walked 
to find the _AT_AT_
calls and extract them and compile them and execute them (the _AT_AT_deco 
functions would
obviously have to be defined already, so they might be looked up in some 
standard place
like trying to do place = __import__(_AT_AT_MODULE_) wher _AT_AT_MODULE_ gets 
defined sort
of like __METACLASS__.), passing the AST and the _AT_AT_deco call location 
therein, and the rest
of the parameters.

AST decoration would introduce macro-like capabilities, but restricted to 
transforming valid ASTs,
so it isn't like source text rewriting macros.

Sorry for the run-on stream of consciousness ;-/

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


Re: ZipFile and file rigths

2005-07-10 Thread Robert Kern
perchef wrote:

[Sybren Stuvel:]
>>ZIP doesn't store file permissions.

Yes, the .zip file format does store file permissions appropriate to the 
platform that generates the file.

> ok, but in that case how could stuffit retrieve these permissions ?
> 
> Thanks for the link Robert.

When one makes a .zip file using ZipFile, the permissions are stored, 
but there is also a flag that tells unzip utilities what system the .zip 
file was made on. ZipFile always stores this flag as MS Windows no 
matter what system actually made it. StuffIt seems to ignore the flag 
and always propagate the permissions when it unzips. It assumes that the 
.zip file was made on a Mac. InfoZip's unzip(1) utility does look at the 
flag, and if it says "MS Windows", it does not propagate the 
permissions. If the .zip file actually *were* made on a Windows machine 
and unzipped on a UNIX-like filesystem, all of the files would be marked 
executable. I remember this used to happen quite often a few years ago. 
InfoZip made an arguably incorrect choice (but also a fairly convenient 
one), but ZipFile's behavior is definitely incorrect.

OTOH, I don't know if this has any relevance to the problem that you are 
seeing.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Codecs

2005-07-10 Thread Martin v. Löwis
Ivan Van Laningham wrote:
> Hi All--
> As far as I can tell, after looking only at the documentation (and not
> searching peps etc.), you cannot query the codecs to give you a list of
> registered codecs, or a list of possible codecs it could retrieve for
> you if you knew enough to ask for them by name.
> 
> Why not? 

There are several answers to that question. Which of them is true,
I don't know. In order of likelyhood:
1. When the API was designed, that functionality was forgotten.
   It was not possible to add it later on (because of 2)
2. Registration builds on the notion of lookup functions. The
   lookup function gets a codec name, and either succeeds in
   finding the codec, or raises an exception.
   Now, a lookup function, in principle, might not "know" in
   advance what codecs it supports, or the number of encoding
   it supports might not be finite. So asking such a lookup
   function for the complete list of codecs might not be
   implementable.

   As an example of a lookup function that doesn't know what
   encodings it supports, look at my iconv module. This module
   provides all codecs that iconv_open(3) supports, yet there
   is no standard way to query the iconv library in advance
   for a list of all supported codecs.

   As an example for a lookup function that supports an infinite
   number of codecs, consider the (theoretical) encrypt/password
   encoding, which encrypts a string with a password, and the
   password is part of the codec name. Each password defines
   a new encoding, and there is an infinite number of them.

Now, if 1) would have been considered, it might have been possible
to design the API in a way that didn't support all cases that
the current API supports. Alas, somebody must have misplaced
the time machine.

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


Re: computer algebra packages

2005-07-10 Thread Bengt Richter
On Sun, 10 Jul 2005 13:12:21 -0400, =?iso-8859-1?Q?Fran=E7ois?= Pinard <[EMAIL 
PROTECTED]> wrote:

>[Florian Diesch]
>
>> Probably this is usable for you (I never used any of them):
>
>>  This system MAXIMA is [...] based on the original implementation of
>>  Macsyma at MIT [...]
>
>Wow!  A derivative of Joel Moses' integrator!!  I was not aware this
>existed, so thanks for the pointer.  It worked out of the box for me!
>
>> Description: A user-friendly frontend for MAXIMA
>>  Mascyma is (trying to be) a user-friendly graphical frontend for the 
>> Computer
>>  Algebra System GNU MAXIMA.  It is written in Python and provides two GUIs,
>>  one of which based on PyGTK, the other based on wxPython.
>
>I was not successful googling for this one.  Would you have an URL handy?
>
I also found

http://packages.ubuntu.com/hoary/math/mascyma

by googling for "A user-friendly frontend for MAXIMA"

(I find that quoting a whole phrase that is likely to be repeated in
docs and in references often finds stuff)

Then googling for mascsyma [sic ;-)] got

http://home.arcor.de/mulk/projects/mascyma/index.xhtml.de
leading to screenshots at
http://home.arcor.de/mulk/projects/mascyma/screenshots.xhtml.de

No idea what the status of all that is, but looks nice.

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


Re: computer algebra packages

2005-07-10 Thread Robert Kern
Bengt Richter wrote:

> Then googling for mascsyma [sic ;-)] got

I doubt it.  ;-)

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Efficiency of using long integers to hold bitmaps

2005-07-10 Thread Martin v. Löwis
Bengt Richter wrote:
> Sounds like a possible^H^H^H^H^H^H^H^Hprobable premature optimization worry 
> ;-)

Right. OTOH, I notice a frequent game of Katze und Maus (cat and mouse?)
in questions around Python implementation details. The OP doesn't
provide details of his application, but instead asks a general question
"how is foo implemented in Python, I'm worried it might be bar?". Then,
instead of saying "yes, it is bar" or "no, it isn't bar", the response
is "we can't answer your real question because you didn't state it
well".

In this case, I really liked Raymond's answer (arrays are as efficient
as long ints, which are both more efficient than lists of integers). It
is close enough to the truth for the OP (*), and was stated with much
less text than this message (or the one I'm responding to).

I really should go to bed now,

Martin

(*) even closer to the truth is the observation that arrays are slightly
more space-efficient, because they can store 32 bits in 4 bytes, whereas
long ints only store 30 bits in 4 bytes. Time efficiency is more
difficult to compare, because it depends on the individual
implementation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Dan Sommers
On Sun, 10 Jul 2005 16:26:24 -0400,
"Terry Reedy" <[EMAIL PROTECTED]> wrote:

> "Ralf W. Grosse-Kunstleve" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]

> I have a suggestion I don't remember seeing for flagging which vars to 
> autoinit without new syntax: use '_' instead of '.'.  I have never seen 
> local vars with a leading '_'.  So, in combination with whatever other 
> mechanism (metaclass, __init__ decorator?)

>def __init__(self, _x, y, _z) :

> would automatically do self.x = _x, self.z = _z, but not self.y = y.

> Terry J. Reedy

That's a pretty big change; now all formal parameters beginning with an
underscore have a brand new meaning.

How about this:

def __init__(self, self.x, y, self.z):
# self.x, self.z from first and third explicit parameters
do_something_with_y()

where "self" in "self.x" and "self.y" would have to match the first
parameter (so that the pathological among us could write this:

def __init__(this, this.x, y, this.z):
do_something_with_y()

instead).

(Sorry if this posts multiple times; gnus and/or my news server were not
happy when I was composing this reply.)

Regards,
Dan

-- 
Dan Sommers

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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Paul Rubin
Dan Sommers <[EMAIL PROTECTED]> writes:
> def __init__(self, self.x, y, self.z):
> # self.x, self.z from first and third explicit parameters
> do_something_with_y()

Hey, I like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inheritance

2005-07-10 Thread J
just to follow up. I managed to get it working by having a closer look
at the xxmodules. However, the example does the following

typedef struct
{
PyStructBaseClass  mBase;
int mValue;
} PyStructDerivedClass;

Does anything speak agains doing this ?

typedef struct : public PyStructBaseClass
{
int mValue;
} PyStructDerivedClass;

It seems to work for me. The advantage is that access to the members in
that structure is easier. The .mBase is not needed 

Cheers
Jochen

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


Cat and Mouse (wes Re: Efficiency of using long integers to hold bitmaps)

2005-07-10 Thread Terry Reedy

""Martin v. Löwis"" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Right. OTOH, I notice a frequent game of Katze und Maus (cat and mouse?)

Yes, apparently with the same idiomatic meaning, as you decribe the game 
here perfectly.

TJR



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

Re: decorators as generalized pre-binding hooks

2005-07-10 Thread Terry Reedy

"George Sakkis" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>> This possibility was discussed on the py-dev list about a year or so 
>> ago.
>> The twice monthly summaries should include this topic.  As I remember, 
>> the
>> reason for limiting to functions included:
>>
>> 1. classes have metaclasses, functions don't have metafunctions.  No one
>> gave an example for classes not handled at least as well with a 
>> metaclass.
>
> Would something like the following count ?
[snip]
Not qualified to comment.

>> 2. certain applications require long-function_names_like_this, for which
>> triple typing is substantially annoying and error-prone.
>
> I'm not sure what you mean here; where is the 'triple typing' ?

def long-function_names_like_this(arg1, b, xx , sklfjsl, ):
  'body of fuction here'
  pass
long-function_names_like_this = \
  some_decorator(long-function_names_like_this)

And for the example I am thinking of (integrating Python with Objective-C, 
I believe), the above name is apparently not an exaggeration.

> And how is this an argument against class decorators ?

It is an argument for function decos that does not apply to classes.  The 
does not seem to be a similar need for long, convoluted, class names.  (And 
there is the metaclass option for classes that there is not for functions.) 
So, in relative terms, it is an argument that function decos are relatively 
more needed than class decos.  Given that the decision to add them all was 
a fairly closely balanced one, relative differences can tip the balance one 
way one time and the other way the other.

Guido did not permanently rule out class decos, that I know of, but he 
noted that it would be easier to add them later if really needed than to 
remove them later is not really needed.

Terry J. Reedy



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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Terry Reedy

"Dan Sommers" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Sun, 10 Jul 2005 16:26:24 -0400,
> "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>> I have a suggestion I don't remember seeing for flagging which vars to
>> autoinit without new syntax: use '_' instead of '.'.  I have never seen
>> local vars with a leading '_'.  So, in combination with whatever other
>> mechanism (metaclass, __init__ decorator?)
>
>>def __init__(self, _x, y, _z) :
>
>> would automatically do self.x = _x, self.z = _z, but not self.y = y.
>
>> Terry J. Reedy
>
> That's a pretty big change; now all formal parameters beginning with an
> underscore have a brand new meaning.

As I said, 'in combination with whatever other mechanism', meaning one that 
one has to intentionally invoke.  So there would be no code breaking: the 
suggestion is for a convention used with currently available mechanism 
(assuming that such is possible) that would give the fine-grained control 
not so easily possible with the current update_dict_with_locals idiom.

It would be easier to write the decorator if it were passed the (quoted) 
names of the parameters to be 'attributed'.  But then the user would have 
to write and keep in synchrony two lists, one a (quoted) subset of the 
other.  So I thought it better to have the decorator writer and decorator 
function work a little harder to introspect and interpret one list with 
some items marked somehow in a currently legal but unusual manner.

> How about this:
>
>def __init__(self, self.x, y, self.z):
># self.x, self.z from first and third explicit parameters

This is new syntax that is not currently legal.  My suggestion was for a 
solution that avoided that difficulty and that could, I believe, be 
implemented now, in less time that this thread has been going on, rather 
than maybe some years from now.

Terry J. Reedy



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


Re: Codecs

2005-07-10 Thread John Machin
Ivan Van Laningham wrote:
> 
> It seems to me that if I want to try to read an unknown file
> using an exhaustive list of possible encodings ...


Supposing such a list existed:

What do you mean by "unknown file"? That the encoding is unknown?

Possibility 1:
You are going to try to decode the file from "legacy" to Unicode -- 
until the first 'success' (defined how?)? But the file could be decoded 
by *several* codecs into Unicode without an exception being raised. Just 
a simple example: the encodings ['iso-8859-' + x for x in '12459'] 
define *all* possible 256 characters.

There are various language-guessing algorithms based on e.g. frequency 
of ngrams ... try Google.

Possibility 2:
You "know" the file is in a Unicode-encoding e.g. utf-8, have 
successfully decoded it to Unicode, and are going to try to encode the 
file in a "legacy" encoding but you don't know which one is appropriate?
Sorry, same "But".



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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Dan Sommers
On Sun, 10 Jul 2005 20:11:38 -0400,
"Terry Reedy" <[EMAIL PROTECTED]> wrote:

> "Dan Sommers" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]

>> That's a pretty big change; now all formal parameters beginning with
>> an underscore have a brand new meaning.

> As I said, 'in combination with whatever other mechanism', meaning one
> that one has to intentionally invoke ...

My mistake; I didn't read carefully enough.

Regards,
Dan

-- 
Dan Sommers

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


Re: removing list comprehensions in Python 3.0

2005-07-10 Thread EP

> Well, I want to offer a more radical proposal: why not free squared
> braces from the burden of representing lists at all? It should be
> sufficient to write
> 
> >>> list()
> list()
> 



>From a visual comprehenison point of view, I would assert that the square form 
>[] is much easier on the eyes than the subtler curved forms (e.g. "{" and "(").

Burdened with old eyes, small fonts, and an old, inflexible mind (;-), one of 
Python features near and dear to me are lists, [], and list comprehensions, but 
perhaps a more important point for 3.0 would be that there is a seamless 
consistency across the language (e.g.  [list(), dict(), tuple()] or [ [], {}, 
() ] rather than [list(), {}, ()]) thus reflecting a cohesiveness both in 
underlying approach and symbology.  

Even old guys can adjust to something new that is good and clean.

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Casey Hawthorne
It is easier to write code a computer can understand than others can
understand!

It is harder to read code than to write code!

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Ramon F Herrera
[Peter Barret wrote:]
> It may just be me, but I tend to think of a computer language as a
> tool for directing computers to perform specific actions. Do we talk
> about the expressiveness of a spade?

yes, it is just you.  :-)

Your comparison is a very poor match.  How can you even begin to
compare a hammer or a screwdriver with a computer language?

A more apt comparison would be a Roman general with his spade directing
his troops to attack.  Some generals have more expresiveness than
others.  The barbar generals will just grunt while the French generals
will inspire with some poetic invocation.

-Ramon

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


Re: decorators as generalized pre-binding hooks

2005-07-10 Thread Ron Adam
Bengt Richter wrote:
> On Sun, 10 Jul 2005 05:35:01 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:

>>So far they are fairly equivalent.  So there's not really any advantage 
>>over the equivalent inline function.  But I think I see what you are 
>>going towards.  Decorators currently must be used when a function is 
>>defined.  This option attempts to makes them more dynamic so that they 
>>can be used where and when they are needed.
> 
> IMO part of the decorator benefit is clearer code, and also IMO the
> @range_check and @default_value decorators succeed in that. The code
> generated would presumably be the same, unless the exception capture
> discussed further down were implemented.

If you take the decorator at face value, it's clear. (In a sort of 
because I said so way.) But if you look in the decorator, it may be 
quite unclear.  Ie.. it sort of sweeps the dirt under the rug. (IMO) 
The thing is, defining a decorator can be fairly complex compared to a 
regular function depending on what one is trying to do.


>>How about if you make it optional too?

>>@@keeplog log_of_interesting_values # if keeplog decorate.
>>b = get_value(c,d)
>>
>>Just a thought.
> 
> Yes, but that is too easy to do another way. Plus I want to reserve
> '@@' for an AST-time decoration idea I have ;-)

The @@ could be whatever, but a single @ could probably be used just as 
well.

How about any line that begins with an @ is preparsed as sugar.  And 
then create a simple sugar language to go along with it?

But that would be compile time macros wouldn't it. ;-)


>>When it comes to decorators, and now the with statements, I can't help 
>>but feel that there's some sort of underlying concept that would work 
>>better.  It has to do with generalizing flow control in a dynamic way 
>>relative to an associated block.
>>
>>One thought is to be able to use a place holder in an expression list to 
>>tell a statement when to do the following block of code.
> 
> it depends on scope and control aspects of what you mean by "block".

By block I meant the indented following suite.  No special scope rules 
that don't already currently exist in any 'if', 'while', or 'for' suite.


> But I doubt if we have much chance of introducing something is one
> more bf in the storm of "with" ideas that have already been
> discussed.

I'd like to think until 2.5 is released that there's still a chance that 
something better could come along.  But it would have to be pretty darn 
good I expect.


> They strike me as a kind of macro idea where the only substitution argument
> is the block suite that follows, which IMO is a severe limitation on both
> the macro idea and the use of blocks ;-)

I'm not sure it's macro or not.  Maybe it's a flow control parser 
statement?

  Does that sound any better than macro?  ;-)


>>I like the place holders because I think they make the code much more 
>>explicit and they are more flexible because you can put them where you 
>>need them.
> 
> Yes, but if you want to go that way, I'd want to have named place holders
> and be able to refer to arbitrary things that make sense in the context.

 From what I've seen so far, there's a lot of resistance to real run 
time macro's.  So I don't expect them any time soon.

The mechanism I suggested doesn't store code or name it. So it's not a 
macro, it's closer to a while that conditionally runs the body, but in 
this case the condition is when instead of if.  It's a different concept 
that I think can compliment the language without being too complex.


Named macros make it even more useful.

Here I used 'this' as the keyword to indicate when the suite is to be 
done.  So it's a do-this-suite statement.


do f = opening(filename); try this; finally f.close():
suite


Now using "Sugar" language!;-)

 # Create sugar
@with_opened = "opening(%s); try this; finally f.close()"


do f = $with_opened%('filename'):# $ indicates sugar
suite



I used Pythons % operator as it already exists and works fine in this 
situation.  Easy to implement as well.

Hmm.. not sure how to apply this to a decorator. Lets see... Working it 
out...

 # function to use
 def check_range(x):
if x in range(10,25):
   return
raise RangeError# or what ever is suitable

 # Make the decorator with sugar
 @checkrange = "%s %s check_range(%s)"

Parses on spaces as default?

 $checkrange%   # Use the following line here
 x = 24 # since nothing given after the %


Which will results in...

 x = check_range(24)


There should be a way to specify an additional argument I think.

The exact rules would need to be worked out.  It also might be a good 
way to test sugar ideas before they become part of the language.


>>>orthogonal-musing-ly ;-)
>>
>>"Orthogonal is an unusual computer language in which your program flow 
>>can go sideways. In actuality in can go in just abo

Re: Read-only class properties

2005-07-10 Thread Bengt Richter
On 10 Jul 2005 13:38:22 -0700, "George Sakkis" <[EMAIL PROTECTED]> wrote:

>I'm trying to write a decorator similar to property, with the
>difference that it applies to the defining class (and its subclasses)
>instead of its instances. This would provide, among others, a way to
>define the equivalent of class-level constants:
>
>class Foo(object):
>@classproperty
>def TheAnswer(cls):
>return "The Answer according to %s is 42" % cls.__name__
>
 Foo.TheAnswer
>The Answer according to Foo is 42
>>> Foo.TheAnswer = 0
>exceptions.AttributeError
>...
>AttributeError: can't set class attribute
>
>I read the 'How-To Guide for Descriptors'
>(http://users.rcn.com/python/download/Descriptor.htm) that describes
>the equivalent python implementation of property() and classmethod()
>and I came up with this:
>
>def classproperty(function):
>class Descriptor(object):
>def __get__(self, obj, objtype):
>   return function(objtype)
>def __set__(self, obj, value):
>raise AttributeError, "can't set class attribute"
>return Descriptor()
>
>Accessing Foo.TheAnswer works as expected, however __set__ is
>apparently not called because no exception is thrown when setting
>Foo.TheAnswer. What am I missing here ?
>
I suspect type(Foo).TheAnswer is not found and therefore TheAnswer.__set__ is 
not
looked for, and therefore it becomes an ordinary attribute setting. I suspect 
this
is implemented in object.__setattr__ or type.__setattr__ as the case may be, 
when
they are inherited. So I introduced a __setattr__ in type(Foo) by giving Foo
a metaclass as its type(Foo). First I checked whether the attribute type name 
was
'Descriptor' (not very general ;-) and raised an attribute error if so.
Then I made a class Bar version of Foo and checked for __set__ and called that
as if a property of type(Bar) instances. See below.


< classprop.py >
def classproperty(function):
class Descriptor(object):
def __get__(self, obj, objtype):
   return function(objtype)
def __set__(self, obj, value):
raise AttributeError, "can't set class attribute"
return Descriptor()

class Foo(object):
class __metaclass__(type):
def __setattr__(cls, name, value):
if type(cls.__dict__.get(name)).__name__ == 'Descriptor':
raise AttributeError, 'setting Foo.%s to %r is not allowed' 
%(name, value) 
type.__setattr__(cls, name, value)
@classproperty
def TheAnswer(cls):
return "The Answer according to %s is 42" % cls.__name__
@classproperty
def AnotherAnswer(cls):
return "Another Answer according to %s is 43" % cls.__name__

class Bar(object):
class __metaclass__(type):
def __setattr__(cls, name, value):
attr = cls.__dict__.get(name)
if hasattr(attr, '__set__'):
attr.__set__(cls, value) # like an instance attr setting
else:
type.__setattr__(cls, name, value)
@classproperty
def TheAnswer(cls):
return "The Answer according to %s is 42" % cls.__name__
@classproperty
def AnotherAnswer(cls):
return "Another Answer according to %s is 43" % cls.__name__


if __name__ == '__main__':
print Foo.TheAnswer
Foo.notTheAnswer = 'ok'
print 'Foo.notTheAnswer is %r' % Foo.notTheAnswer
print Foo.AnotherAnswer
try: Foo.TheAnswer = 123
except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e)
try: Foo.AnotherAnswer = 456
except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e)
print Bar.TheAnswer
Bar.notTheAnswer = 'ok'
print 'Bar.notTheAnswer is %r' % Bar.notTheAnswer
print Bar.AnotherAnswer
try: Bar.TheAnswer = 123
except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e)
try: Bar.AnotherAnswer = 456
except AttributeError, e: print '%s: %s' %(e.__class__.__name__, e)

Result:

[18:17] C:\pywk\clp>py24 classprop.py
The Answer according to Foo is 42
Foo.notTheAnswer is 'ok'
Another Answer according to Foo is 43
AttributeError: setting Foo.TheAnswer to 123 is not allowed
AttributeError: setting Foo.AnotherAnswer to 456 is not allowed
The Answer according to Bar is 42
Bar.notTheAnswer is 'ok'
Another Answer according to Bar is 43
AttributeError: can't set class attribute
AttributeError: can't set class attribute

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


Re: computer algebra packages

2005-07-10 Thread Bengt Richter
On Sun, 10 Jul 2005 15:53:22 -0700, Robert Kern <[EMAIL PROTECTED]> wrote:

>Bengt Richter wrote:
>
>> Then googling for mascsyma [sic ;-)] got
Dang, and I put "[sic]" too. IOW, 'macsyma'.replace('cs','sc')
>
>I doubt it.  ;-)
>
Rightly ;-/ Fingers think they know spelling better than I do ;-/

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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Bengt Richter
On 10 Jul 2005 16:07:40 -0700, Paul Rubin  wrote:

>Dan Sommers <[EMAIL PROTECTED]> writes:
>> def __init__(self, self.x, y, self.z):
>> # self.x, self.z from first and third explicit parameters
>> do_something_with_y()
>
>Hey, I like that.

Me too. I liked the leading _, but on second thought it is a weird language 
change
re names in a special context. Probably not so good.

OTOH, I see in the above a generalizable principle of formal parameter 
expressions as
automatic assignment targets at the beginning of function execution that could 
allow
anything normally allowed locally on the left of an assignment. This is 
contrived,
but illustrates:

def setem(key, adict[key]): pass # note that assignment is left-right,
 # so key is available for adict[key]
 # and adict is global here
adict = {}
setem('k', 'value')
adict -> {'k':'value'}

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Randy Howard
Keith Thompson wrote
(in article <[EMAIL PROTECTED]>):


>\/|  |\|   __\,,\ /,,/__
> \||/ |  | |  jgs (__Y__)
> /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
> ==

Out of curiosity, does anyone remember who 'jgs' refers to 
above?


-- 
Randy Howard (2reply remove FOOBAR)

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


Re: Efficiency of using long integers to hold bitmaps

2005-07-10 Thread jepler
You'll find that using Python Longs unsuitable if you *change* the
bitmaps---All numeric types are immutable, so you'll copy the bitmap
each time you perform an operation like "set bit".

numarray has a 'bit' typecode, though I'm not sure how such an array is
actually stored---from a quick look, it appears it's stored one bit per
byte:
>>> numarray.ones((3,3), 'Bool').tostring()
'\x01\x01\x01\x01\x01\x01\x01\x01\x01'

A Python object layer around array.array('B') would not necessarily be
fast, but it would at least avoid the copying problem, and be memory
efficient.
import array

class BitArray2D:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
nbytes = (rows * cols + 7) / 8
self._data = array.array('B', [0]) * nbytes

def __getitem__(self, (r,c)):
# TODO: check r, c in bounds
idx = r + c * self.rows
byte = idx / 8
bit = 1 << (idx%8)
return bool(self._data[byte] & bit)

def __setitem__(self, (r, c), v):
# TODO: check r, c in bounds
idx = r + c * self.rows
byte = idx / 8
bit = 1 << (idx%8)
if v:
self._data[byte] |= bit
else:
self._data[byte] &= ~bit

b = BitArray2D(10, 10)
print b._data
for x in range(10):
b[x,x] = b[9-x,x] = 1
print b._data
print
for x in range(10):
for y in range(10):
print " *"[b[x,y]],
print

Jeff


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

  1   2   >