Re: Attributes and built-in types

2005-04-01 Thread "Martin v. Löwis"
Dave Opstad wrote:
Is it just an implementation limitation that attributes cannot be 
assigned to instances of internal types?
No, not "just". Some types have a fixed set of attributes by design,
whereas others allow addition of attributes. There are several reasons
for this design. Performance is one of them; backwards compatibility
another.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


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

2005-04-01 Thread Javier Bezos
"Steve Holden" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]

  [Discussion on Python slices and the off-by-one issue
   deleted]

> While this may be an interesting philosophical (or should that be
> philological) discussion, since Python has worked this way for donkey's
> years, and since a change would break 30% of the existing codebase, you
> clearly can't be advocating change.
>
> So, what's the point of this thread now?

None. In fact, I sent my last post a couple
of days ago, so I don't see the point of your
message. This thread began when some people
thought that I had to be convinced about how
wonderful slices are, after I said _incidentally_
I didn't like Python slices (and then I had to
explain in turn why I don't like them). Perhaps
you should ask those people, not me.

Javier
___
Javier Bezos | Mem. A multilingual system for LaTeX
jbezos at wanadoo dot es | http://mem-latex.sourceforge.net
.|




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


Re: Simple thread-safe counter?

2005-04-01 Thread Artie Gold
Skip Montanaro wrote:
Paul> I'd like to have a function (or other callable object) that
Paul> returns 0, 1, 2, etc. on repeated calls.
...
Paul> There should never be any possibility of any number getting
Paul> returned twice, or getting skipped over, even if f is being called
Paul> from multiple threads.
How about (untested):
import Queue
counter = Queue.Queue()
counter.put(0)
def f():
i = counter.get()
I think you need:
  i = counter.get(True)
for this to work; otherwise a race condition would raise an exception.
counter.put(i+1)
return i
[snip]
This is, of course dependent upon counter.get() being guaranteed to be 
thread safe. (I haven't found anything in the docs specifically relating 
to that. Perhaps it's implicit?)

Thanks,
--ag
--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
--
http://mail.python.org/mailman/listinfo/python-list


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

2005-04-01 Thread Paul Rubin
Nick Craig-Wood <[EMAIL PROTECTED]> writes:
> I believe futex is the thing you want for a modern linux.  Not
> very portable though.

That's really cool, but I don't see how it can be a pure userspace
operation if the futex has a timeout.  The kernel must need to keep
track of the timeouts.  However, since futexes can be woken by any
thread, the whole thing can be done with just one futex.  In fact the
doc mentions something about using a file descriptor to support
asynchronous wakeups, but it's confusing whether that applies here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How To Do It Faster?!?

2005-04-01 Thread Simo Melenius
[EMAIL PROTECTED] writes:

> Every user of thsi big directory works on big studies regarding oil
> fields. Knowing the amount of data (and number of files) we have to
> deal with (produced by simulators, visualization tools, and so on)
> and knowing that users are usually lazy in doing clean up of
> unused/old files, this is a way for one of us to "fast" scan all the
> directories and identify which files belong to him. Having them in
> an organized, size-sorted wxPython list, the user can decide if he
> want to delete some files (that almost surely he forgot even that
> they exist...) or not. It is easy as a button click (retrieve the
> data-->delete the files).

Correct me if I'm wrong but since it _seems_ that the listing doesn't
need to be up-to-date each minute/hour as the users will be looking
primarily for old/unused files, why not have a daily cronjob on the
Unix server to produce an appropriate file list on e.g. the root
directory of your file server?

Your Python client would then load that (possibly compressed) text
file from the network share and find the needed bits in there.

Note that if some "old/unneeded" files are missing today, they'll show
right up the following day.

For example, running the GNU find command like this:

$ find . -type f -printf "%T@ %u %s %p\n" > /yourserverroot/files.txt

produces a file where each line contains the last modified time,
username, size and path for one file. Dead easy to parse with Python,
and you'll only have to set up the cronjob _once_ on the Unix server.

(If the file becomes too big, grep can be additionally used to split
the file e.g. per each user.)


br,
S

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


Re: Translation review?

2005-04-01 Thread Michele Simionato
This is spectacular! :)
Is there a way to make it to work from environments (such as emacs)
where stdin is special?

  Michele Simionato

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


Re: Installing Python on a Windows 2000 Server

2005-04-01 Thread Steve Holden
Mike Moum wrote:
Hi,
I'm a civil engineer who also doubles as chief programmer for technical 
applications at my company. Most of our software is written in Visual 
Basic because our VP in charge of I.T. likes to have "consistency", and 
at the moment we're a Microsoft shop. He has assigned me the task of 
developing an new application, the exact nature of which is not 
important for my question. I told him that, in my opinion, that Visual 
Basic was not the best choice for developing this application, and that 
I wanted to use Python. After a bit of discussion of the pros and cons, 
he said to go ahead. I managed to keep my jaw from hitting the floor. :>)

We have a central server array running Windows Server 2000 (I think 
that's the right name; networking is not my specialty, but it's 
definately Windows). Some of our workstations run Windows 2000; others 
run Windows XP Pro. I would like to install Python on the server, and 
run the application that I'll be developing from the workstations, 
without having to install any Python components on the workstations 
themselves. In other words, the Python executable, and the various 
libraries, dll's, and what have you, as well as the application that I'm 
developing, should all reside on the server. The only thing on the 
workstations would be a shortcut to myapplication.py.

Does anyone know whether it is possible to do this? I've done some 
Google searching, with no conclusive results, and poked about on 
python.org, but haven't really been able to find anything. Normally I'd 
be happy to just try it out and see what happens, but we're breaking new 
ground here (this is an amazingly big step for our hide-bound IS 
department!), so I'd like everything to go as smoothly as possible.

TIA,
Mike
Mike:
Well done, sounds like you are in for a big success!
What you describe sounds like a pretty normal setup, assuming that there 
is a network share accessible to all desktops that the Python binaries 
can be located on.

Windows XP and 2000 run the same Python binaries, so there shouldn't be 
any problems. If I'm wrong this message will bring Tim Peters into the 
conversation, and his opinion can safely be regarded as authoritative 
(right, Tim?).

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


Re: that is it is not it (logic in Python)

2005-04-01 Thread Steve Holden
F. Petitjean wrote:
[...]
*I* wrote the original post.  and am pretty sure it is not faked. And I
run it before posting to be sure not to say anything wrong. it is a kind
of relief to learn that computers in 2005 (even Python powered) are
humor-impaired and follow the « ref manual » every time even on first
April.
But you also wrote in your original post:
Seriously on an April fool's day.
which would seem to be falsely denying that your post was an April 
Fool's prank. Rather bad form, old chap ;-)

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


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

2005-04-01 Thread Nick Craig-Wood
Paul Rubin  wrote:
>  Antoon Pardon <[EMAIL PROTECTED]> writes:
> > I'm not sure that this would be an acceptable approach. I did the man
> > semop and it indicates this is part of system V IPC. This makes me
> > fear that semaphores will use file descriptors or other resources
> > that are only available in a limited amount. Not usefull if you are
> > talking about thousands of threads.
> 
>  That would be terrible, if semaphores are as heavy as file descriptors.
>  I'd like to hope the OS's are better designed than that.

I believe futex is the thing you want for a modern linux.  Not
very portable though.

>From futex(4)

   The  Linux  kernel  provides  futexes  ('Fast  Userspace muTexes') as a
   building block for fast userspace locking and semaphores.  Futexes  are
   very  basic  and lend themselves well for building higher level locking
   abstractions such as POSIX mutexes.

   This page does not  set  out  to  document  all  design  decisions  but
   restricts  itself to issues relevant for application and library devel-
   opment. Most programmers will in fact not be using futexes directly but
   instead  rely  on  system  libraries  built  on  them, such as the NPTL
   pthreads implementation.

   A futex is identified by a piece of memory which can be shared  between
   different  processes.  In  these  different processes, it need not have
   identical addresses. In its bare form, a futex has semaphore semantics;
   it  is  a  counter  that can be incremented and decremented atomically;
   processes can wait for the value to become positive.

   Futex operation is entirely userspace for the non-contended  case.  The
   kernel  is  only  involved to arbitrate the contended case. As any sane
   design will strive for non-contension, futexes are also  optimised  for
   this situation.

   In  its  bare form, a futex is an aligned integer which is only touched
   by atomic assembler instructions. Processes can share this integer over
   mmap,  via shared segments or because they share memory space, in which
   case the application is commonly called multithreaded.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Steve Holden
alex goldman wrote:
Daniel Silva wrote:

At any rate, FOLD must fold.

I personally think GOTO was unduly criticized by Dijkstra. With the benefit
of hindsight, we can see that giving up GOTO in favor of other primitives
failed to solve the decades-old software crisis.
What software crisis? Knuth (among others) has demonstrated that it's 
possible to do structured programming in assembly language (though I 
have to say that not all his MIX was particularly well-structured).

The danger in GOTO is that it allows the undisciplined programmer to 
develop a badly-structured solution to a programming problem. A 
disciplined programmer will write well-structured code with whatever 
tools come to hand.

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


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Steve Holden
Aahz wrote:
In article <[EMAIL PROTECTED]>,
=?iso-8859-1?Q?Fran=E7ois?= Pinard  <[EMAIL PROTECTED]> wrote:
[Sunnan]
[...] for Pythons ideal of having one canonical, explicit way to
program.
No doubt it once was true, but I guess this ideal has been abandoned a
few years ago.
My honest feeling is that it would be a mis-representation of Python,
assertng today that this is still one of the Python's ideals.

Mind providing evidence rather than simply citing your feelings?  Yes,
there's certainly redundancy in Python right now, but a large portion of
that will go away in Python 3.0.  So where's the abandonment of the
ideal?
Mind providing evidence rather than citing your opinions? I don't see 
any evidence that Python 3.0 will adopt Turing-machine-like canonical 
algorithms, and anything more complex is (at least from a theoretical 
point of view) merely syntactic sugar.

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


Re: Simple thread-safe counter?

2005-04-01 Thread Paul Rubin
Tim Peters <[EMAIL PROTECTED]> writes:
> The GIL is your friend here:
> 
> import itertools
> f = itertools.count().next

Thanks, I was hoping something like this would work but was not sure I
could rely on it.

> A similar thing can be done with xrange.  But either way sucks if you
> call it often enough to exceed the size of a Python short int
> (platform C long).  The obvious way with an explicit mutex doesn't
> have that problem.

Xrange, of course :).  I don't need to exceed the size of a short int,
so either of these should work fine.  I wonder what measures the Pypy
implementers will take (if any) to make sure these things keep
working, but for now I won't worry about it.

Out of interest, are the above guaranteed to work under Jython?  What
I'm doing right now is a short-term thing that will only have to run
under CPython, but I like to do things the right way when I can.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple thread-safe counter?

2005-04-01 Thread Skip Montanaro

Paul> I'd like to have a function (or other callable object) that
Paul> returns 0, 1, 2, etc. on repeated calls.
...
Paul> There should never be any possibility of any number getting
Paul> returned twice, or getting skipped over, even if f is being called
Paul> from multiple threads.

How about (untested):

import Queue

counter = Queue.Queue()
counter.put(0)
def f():
i = counter.get()
counter.put(i+1)
return i

Obviously, if you want multiple counters for some reason a little
information hiding with a class would help (also untested):

import Queue

class Counter:
def __init__(self, start=0):
self.counter = Queue.Queue()
self.counter.put(start)

def __call__(self):
i = self.counter.get()
self.counter.put(i+1)
return i

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


Re: property and virtuality

2005-04-01 Thread Michele Simionato
Diez B. Roggisch:

> On second thoughts, a metaclass _might_ help here - but it would be
rather
> elaborate: look in the baseclasses for properties that have getters
and
> setters of the same name as some methods in the current class, and
replace
> them, or  create a new property with them (I'm not sure if
descriptors
> allow changing their get/set/del methods). I'm not 100% sure if and
how
> good that works (a quick hack would be easy, but to ship around the
cliffs
> of multiple inheritance requires more careful navigation I fear...)

Maybe you are worrying to much. Here is a quick metaclass solution
which
magically generates properties from methods which name starts with
"get"
or "set":

class MagicProperties(type):
def __init__(cls, name, bases, dic):
prop_names = set(name[3:] for name in dic
 if name.startswith("get")
 or name.startswith("set"))
for name in prop_names:
getter = getattr(cls, "get" + name, None)
setter = getattr(cls, "set" + name, None)
setattr(cls, name, property(getter, setter))

class Base(object):
__metaclass__ = MagicProperties
def getx(self):
return self._x
def setx(self, value):
self._x = value

class Child(Base):
def getx(self):
print "getting x"
return super(Child, self).getx()
def setx(self, value):
print "setting x"
super(Child, self).setx(value)

c = Child()
c.x = 1
print c.x

This should work well for multiple inheritance too (modulo metaclass
conflicts).

I must say, however, that I never use this idiom (i.e. polluting my
classes
with tons of getters and setters and making properties from them).
I typically use a property factory function, or a custom descriptor.


Michele Simionato

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


Re: Simple thread-safe counter?

2005-04-01 Thread Tim Peters
[Paul Rubin]
> I'd like to have a function (or other callable object) that returns
> 0, 1, 2, etc. on repeated calls.  That is:
>
>print f()   # prints 0
>print f()   # prints 1
>print f()   # prints 2
># etc.
>
> There should never be any possibility of any number getting returned
> twice, or getting skipped over, even if f is being called from
> multiple threads.
> 
> What's the simplest and most natural way to do this?  I can think of a
> few but am not sure that they work.  And I can think of some ways that
> are sure to work, but are messier than I'd like.

The GIL is your friend here:

import itertools
f = itertools.count().next

A similar thing can be done with xrange.  But either way sucks if you
call it often enough to exceed the size of a Python short int
(platform C long).  The obvious way with an explicit mutex doesn't
have that problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to programming question

2005-04-01 Thread Joal Heagney
Joal Heagney wrote:
Steve Holden wrote:
I suppose this would be far too easy to understand, then:
pr =['Guess my name', 'Wrong, try again', 'Last chance']
for p in pr:
  name = raw_input(p+": ")
  if name == "Ben":
print "You're right!"
break
else:
  print "Loser: no more tries for you"
regards
 Steve

THIS is why I like python! There's always a simple, easy to understand 
way to do something. If it looks complex, then there must me something 
wrong.

Joal
And now that I've looked at the documentation of the for loop, I 
understand it as well! :)

The following explaination is for Ben, so he knows what's going on.
From the documentation, with a little rewriting.
"The for statement is used to iterate over the elements of a sequence 
(such as a string, tuple or list) or other iterable object:

for target_list "in" expression_list:

else:

The expression list is evaluated once and should yield a sequence(such 
as a string, tuple, list or iterator object).
Each item in the sequence is assigned to the target_list variable in 
turn. Then the "do this first" instructions are then executed once for 
each item in the sequence.
When the items are exhausted (which is immediately when the sequence is 
empty), the "now do this last" instructions in the else statement, if 
present, are executed, and the loop terminates.

A break statement executed in the first section terminates the WHOLE 
loop without executing the else clause. A continue statement executed in 
the first stage skips the rest of these instructions for that loop and 
continues with the next item, or with the else clause if there was no 
next item."

So copying Steve's example:
>> pr =['Guess my name', 'Wrong, try again', 'Last chance']
>> for p in pr:
>>   name = raw_input(p+": ")
>>   if name == "Ben":
>> print "You're right!"
>> break
>> else:
>>   print "Loser: no more tries for you"
This allows us to execute the else clause if the name is guessed 
incorrectly three times.
However, if the name is guessed correctly, then the break statement 
pulls us completely out of the loop without executing the else clause.

My original example attempted to do this by splitting the loop up into a 
series of different cases because I was unaware of this additional 
behaviour with the for loop expression. Steve's method = much better.

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


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread François Pinard
[Aahz]
> =?iso-8859-1?Q?Fran=E7ois?= Pinard  <[EMAIL PROTECTED]> wrote:

> >No doubt it once was true, but I guess this ideal has been
> >abandoned a few years ago.  My honest feeling is that it would be a
> >mis-representation of Python, assertng today that this is still one
> >of the Python's ideals.

> Mind providing evidence rather than simply citing your feelings?

The important word was "honest", not "feeling". :-)

> Yes, there's certainly redundancy in Python right now, [...]

See here, I'm not asking you for proofs. :-)

> but a large portion of that will go away in Python 3.0.

And when will that be?  The principle of "there is only way to do it"
was observable in Python 1.5.2, and started to disappear at that time.
How many years between 1.5.2 and 3.0?

> So where's the abandonment of the ideal?

Many of us are using Python today, week after week, year long.  So let's
be pragmatic.  Python is what it became and now is.  Let's not define it
as a memory from the past nor as a futuristic dream.

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


Simple thread-safe counter?

2005-04-01 Thread Paul Rubin
I'd like to have a function (or other callable object) that returns
0, 1, 2, etc. on repeated calls.  That is:

print f()   # prints 0
print f()   # prints 1
print f()   # prints 2
# etc.

There should never be any possibility of any number getting returned
twice, or getting skipped over, even if f is being called from
multiple threads.

What's the simplest and most natural way to do this?  I can think of a
few but am not sure that they work.  And I can think of some ways that
are sure to work, but are messier than I'd like.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: boring the reader to death (wasRe: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Tim Peters
[Aahz]
>> "The joy of coding Python should be in seeing short, concise, readable
>> classes that express a lot of action in a small amount of clear code --
>> not in reams of trivial code that bores the reader to death."  --GvR

[Sunnan]
> Can anyone please point me to the text that quote was taken from? I
> tried to use a search engine but I only found quotations, not the source.

That's because it was originally in email to a company-internal
mailing list.  If you're willing to move to Fredericksburg, VA and
work for Zope Corp, perhaps they'll let you in to the PythonLabs list
archives.  Fair warning:  I work for Zope Corp, and I'm not sure I can
get into those archives.  So don't switch jobs _just_ for that.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2005-04-01 Thread Paul Rubin
Have you looked at this?  A paper about adding asynchronous exceptions
to Python.

http://www.cs.williams.edu/~freund/papers/02-lwl2.ps
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python plug-in Frameworks like Eclipse RCP...

2005-04-01 Thread Jim Hargrave
Hum, maybe my question was too specific. What I would really like to 
know is what is the best way to implement a Python application with a 
pluggable architecture. In particular, I would like to use wxPython and 
have plug ins automatically register themselves with the GUI by adding 
themselves to the mean or adding a tab. Again this is much like Eclipse 
RCP - but forget that part :-)

J

Jim Hargrave wrote:
Eclipse provides a very nice application framework which supports 
plug-ins. It's easy to dynamically add new functionality, menu items, 
property editors, options etc.. using a combination of XML and Java code.

Is there a similar framework for Python? If not any hints on how such a 
framework would be implemented?

I'm building a client side tool using Python/wxPython for our 
translators and would like to have a pluggable architecture similar to 
Eclipse RCP

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


Re: New to programming question

2005-04-01 Thread Joal Heagney
Steve Holden wrote:
Joal Heagney wrote:
Bengt Richter wrote:
On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney <[EMAIL PROTECTED]> 
wrote:


Oh goddammmni. I seem to be doing this a lot today. Look below 
for the extra addition to the code I posted.

Joal Heagney wrote:
Here's my contribution anycase:
count = 0
# Get first input
name = raw_input("Guess my name: ")
# Give the sucker two extra goes
while count < 2:
   # Check the value of name
   if name == 'Ben':
   print "You're right!"
   break
   else:
   name = raw_input("Try again: ")

  # Here's the bit I missed out.
  count += 1
# Of course, we haven't checked the sucker's last guess
# so we have to do that now.
if count == 2:
   if name == 'Ben':
   print "You're right!"
   else:
   print "No more tries for you!!!"
Hope this helps.
Joal

G.

Need something more straightforward, e.g., a wrapped one-liner:
 >>> def guess(n=3): print ("You're right!", 'No more tries for 
you!!!')[n-1 in
 ...(x for x in xrange(n) for t in [raw_input('Guess my name: 
')=='Ben']
 ...if not t or iter([]).next())]

Okay, now in my opinion, that's just too complex to give to a newbie 
as a suggested implementation. :)

Joal

I suppose this would be far too easy to understand, then:
pr =['Guess my name', 'Wrong, try again', 'Last chance']
for p in pr:
  name = raw_input(p+": ")
  if name == "Ben":
print "You're right!"
break
else:
  print "Loser: no more tries for you"
regards
 Steve
THIS is why I like python! There's always a simple, easy to understand 
way to do something. If it looks complex, then there must me something 
wrong.

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


Re: New to programming question

2005-04-01 Thread Ben
Joal was right.  It is a bit beyond me.  But I appreciate your response.

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


Re: New to programming question

2005-04-01 Thread Ben
Thanks for your reply.

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


Re: New to programming question

2005-04-01 Thread Ben
Thanks for your input.

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


Re: New to programming question

2005-04-01 Thread Ben
Thanks for your help.  

It is much appreciated.

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


Re: [Newbie] Search-and-delete text processing problem...

2005-04-01 Thread Bengt Richter
On Fri, 1 Apr 2005 17:33:59 -0800, "Todd_Calhoun" <[EMAIL PROTECTED]> wrote:

>I'm trying to learn about text processing in Python, and I'm trying to 
>tackle what should be a simple task.
>
>I have long text files of books with a citation between each paragraph,
Most text files aren't long enough to worry about, but you can avoid
reading in the whole file by just iterating, one line at a time. That is
the way a file object iterates by default, so there's not much to that.

>which might be like "Bill D. Smith, History through the Ages, p.5".
>
>So, I need to search for every line that starts with a certain string (in 
>this example, "Bill D. Smith"), and delete the whole line.
If you want to test what a string starts with, there's a string method for that.
E.g., if line is the string representing one line, line.startswith('Bill') would
return True or False.
>
>I've tried a couple of different things, but none seem to work.  Here's my 
>latest try.  I apologize in advance for being so clueless.
>
>##
>#Text search and delete line tool
>
>theInFile = open("test_f.txt", "r")
>theOutFile = open("test_f_out.txt", "w")
>
>allLines = theInFile.readlines()
This will create a list of lines, all (except perhaps the last, if
the file had no end-of-line character(s) at the very end) with '\n'
as the last character. There are various ways to strip the line ends,
but your use case doesn't appear to require it.

>
>for line in allLines:
 # line at this point contains each line successively as the loop proceeds,
 # but you don't know where in the sequence you are unless you provide for 
it,
 # e.g. by using
 for i, line in enumerate(allLines):
>if line[3] == 'Bill':
The above line is comparing the 4th character of the line (indexing from 0) 
with 'Bill'
which is never going to be true, and will raise an IndexError if the line is 
shorter than
4 characters. Not what you want to do.
 if line.startswith('Bill'):  # note that this is case sensitive. Otherwise 
use line.lower().startswith('bill')

>line == ' '
 the enumerate will give you an index you can use for this, but I doubt 
if you want and invisible space
 without a line ending in place of 'Bill ... \n'
 line[i] = '\n'  # makes an actual blank line , but you want to delete 
it, so this is not going to work
>

>
>theOutFile.writelines(allLines)

UIAM (untested) you should be able to do the entire job removing lines that 
start with 'Bill' thus:

 theInFile = open("test_f.txt", "r")
 theOutFile = open("test_f_out.txt", "w")
 theOutFile.writelines(line for line in theInfile if not 
line.startswith('Bill'))

Or just the line

 open("test_f_out.txt", "w").writelines(L for L in open("test_f.txt") if not 
L.startswith('Bill'))

If you need to remove lines starting with any name in a certain list, you can 
do that too, e.g.,

 delStarts = ['Bill', 'Bob', 'Sue']
 theInFile = open("test_f.txt", "r")
 theOutFile = open("test_f_out.txt", "w")
 for line in theInFile:
 for name in delStarts:
 if line.startswith(name): break
 else: # will happen if there is NO break, so line does not start with any 
delStarts name
 theOutFile.write(line) # write line out if not starting badly
 
(You could do that with a oneliner too, but it gets silly ;-)

If you have a LOT of names to check for, it could pay you to figure a way to 
split off the name
from the fron of a lines, and check if that is in a set instead using a 
delStart list.
If you do use delStart, put the most popular names at the front.

>#
>
>I know I could do it in Word fairly easily, but I'd like to learn the Python 
>way to do things.
Have fun.
>
>Thanks for any advice. 
>
HTH (nothing tested, sorry ;-)

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


Re: Pseudocode in the wikipedia

2005-04-01 Thread Sunnan
James Stroud wrote:
bob == (carol = 2):
  if bob = (bob or carol):
bob == 4
But no one could figure out what bob was supposed to equal anyway.
Wouldn't bob equal the boolean result of the expression (carol = 2)?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator in Python

2005-04-01 Thread Robert Kern
Sunnan wrote:
Terry Reedy wrote:
Gee, what about 0.0 < a < 1.0 < b < 2.0?  I see both as synthesized 
multinary operators, but your are right in that this combination does 
act differently than a+b+c.

Is < really multinary in python? It looks binary to me, just like +.
(a+b)+c
(((0.0 < a) < 1.0) < b ) < 2.0
Go on. Try it with a bunch of different values.
--
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: Ternary Operator in Python

2005-04-01 Thread Sunnan
Terry Reedy wrote:
Gee, what about 0.0 < a < 1.0 < b < 2.0?  I see both as synthesized 
multinary operators, but your are right in that this combination does act 
differently than a+b+c.
Is < really multinary in python? It looks binary to me, just like +.
(a+b)+c
(((0.0 < a) < 1.0) < b ) < 2.0
Sunnan
--
http://mail.python.org/mailman/listinfo/python-list


boring the reader to death (wasRe: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Sunnan
Aahz wrote:
"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code -- 
not in reams of trivial code that bores the reader to death."  --GvR
Can anyone please point me to the text that quote was taken from? I 
tried to use a search engine but I only found quotations, not the source.
Sunnan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Search-and-delete text processing problem...

2005-04-01 Thread M.E.Farmer
My apologies you did indeed use writelines correctly ;)
dohhh!
I had a gut reaction to this.
Py>f = ['hij\n','efg\n','abc\n']
Py> for i in f:
... if i.startswith('a'):
... i == ''
Py> f
['hij\n', 'efg\n', 'abc\n']
Notice that it does not modify the list in any way.
You are trying to loop thru the list and modify the items in place, it
just won't work.
When you rebind the item name to a new value ' ' it does not rebind the
element in the list just the current item.
It is also bug prone to modify a list you are looping over.
M.E.Farmer

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


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Bengt Richter
On 1 Apr 2005 20:00:13 -0500, [EMAIL PROTECTED] (Aahz) wrote:

>In article <[EMAIL PROTECTED]>,
>=?iso-8859-1?Q?Fran=E7ois?= Pinard  <[EMAIL PROTECTED]> wrote:
>>[Sunnan]
>>>
>>> [...] for Pythons ideal of having one canonical, explicit way to
>>> program.
>>
>>No doubt it once was true, but I guess this ideal has been abandoned a
>>few years ago.
>>
>>My honest feeling is that it would be a mis-representation of Python,
>>assertng today that this is still one of the Python's ideals.
   ^--in particular?? That makes for a complex sentence ;-)
>
>Mind providing evidence rather than simply citing your feelings?  Yes,
>there's certainly redundancy in Python right now, but a large portion of
>that will go away in Python 3.0.  So where's the abandonment of the
>ideal?
>-- 
>Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/
>
>"The joy of coding Python should be in seeing short, concise, readable
>classes that express a lot of action in a small amount of clear code -- 
>not in reams of trivial code that bores the reader to death."  --GvR

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


(win32) speedfan api control

2005-04-01 Thread tlviewer
hello,

If you run the Mainboard monitor, speedfan, here is
an ActivePython script to force automatic fan control.
http://www.almico.com/speedfan.php

It's a great example of how clean the WinApi interface is
in ActivePython. The script sets focus to the checkbox of
interest and toggles the checkbox. AFAIK, speedfan will only
start without fan control, requiring the user to manually
check the checkbox to turn it on. 

hope someone finds it useful,
tlviewer

#!/usr/bin/python
# author: [EMAIL PROTECTED] 
# date: April 1, 2005
# description: turn on SpeedFan automatic fan speed
# keywords: speedfan readings
#import win32api as ap 

import win32gui as wi
import win32ui as ui
import win32con as wc

# dialog class name
cl = "TJvXPCheckbox"

try:
hWndÂ=Âwi.FindWindowEx(Â0,Â0,Â"TForm1",Â"SpeedFanÂ4.20")Â
printÂhWndÂ
hWndÂ=Âwi.FindWindowEx(ÂhWnd,Â0,Â"TPageControl",Â"")ÂÂ
printÂhWnd
hWndÂ=Âwi.FindWindowEx(ÂhWnd,Â0,Â"TTabSheet",Â"Readings")
printÂhWnd
hWndÂ=Âwi.FindWindowEx(ÂhWnd,Â0,Âcl,Â"AutomaticÂfanÂspeed")

printÂhWnd
resÂ=Âwi.SetForegroundWindow(hWnd)
res=wi.SendMessageTimeout(hWnd,wc.WM_LBUTTONDOWN,wc.MK_LBUTTON,0,2,75)ÂÂ
resÂ=Âwi.SendMessageTimeout(ÂhWnd,wc.WM_LBUTTONUP,Â0,Â0,Â2,Â75Â)Â
printÂres
except:
pass
#end code
-- 
http://mail.python.org/mailman/listinfo/python-list


Module subprocess: How to "communicate" more than once?

2005-04-01 Thread Edward C. Jones
I have a program named "octave" (a Matlab clone). It runs in a terminal, 
types a prompt and waits for the user to type something. If I try

# Run octave.
oct = subprocess.Popen("octave", stdin=subprocess.PIPE)
# Run an octave called "startup".
oct.communicate("startup")
# Change directory inside octave.
oct.communicate("cd /home/path/to/my/dir")
I get:
Traceback (most recent call last):
  File "./popen.py", line 29, in ?
oct.communicate("cd /home/path/to/my/dir")
  File "/usr/local/lib/python2.4/subprocess.py", line 1044, in communicate
self.stdin.flush()
ValueError: I/O operation on closed file
How do I set up a subprocess so I can send it a command and get the 
answer, then send it another command and get an answer, etc.?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Search-and-delete text processing problem...

2005-04-01 Thread M.E.Farmer
Strings have many methods that are worth learning.
If you haven't already discovered dir(str) try it.
Also I am not sure if you were just typing in some pseudocode, but your
use of writelines is incorrect.
help(file.writelines)
Help on built-in function writelines:

writelines(...)
writelines(sequence_of_strings) -> None.  Write the strings to the
file.

Note that newlines are not added.  The sequence can be any iterable
object
producing strings. This is equivalent to calling write() for each
string.

Todd_Calhoun wrote:
> I'm trying to learn about text processing in Python, and I'm trying
to
> tackle what should be a simple task.
>
> I have long text files of books with a citation between each
paragraph,
> which might be like "Bill D. Smith, History through the Ages, p.5".
>
> So, I need to search for every line that starts with a certain string
(in
> this example, "Bill D. Smith"), and delete the whole line.
>
> I've tried a couple of different things, but none seem to work.
Here's my
> latest try.  I apologize in advance for being so clueless.
>

##
#Text search and delete line tool
theInFile = open("test_f.txt", "r")
theOutFile = open("test_f_out.txt", "w")
allLines = theInFile.readlines()
theInFile.close()

for line in allLines:
if not line.startswith('Bill'):
theOutFile.write(line)

theOutFile.close()
#

# You can also accumulate lines
# in a list then write them all at once
##
#Text search and delete line tool
theInFile = open("test_f.txt", "r")
theOutFile = open("test_f_out.txt", "w")
allLines = theInFile.readlines()
theInFile.close()

outLines = []

for line in allLines:
if not line.startswith('Bill'):
outLines.append(line)

theOutFile.writelines(outLines)
theOutFile.close()
#

hth,
M.E.Farmer

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


Re: Decorater inside a function? Is there a way?

2005-04-01 Thread Ron_Adam
On Fri, 01 Apr 2005 16:46:14 -0500, Jeremy Bowers <[EMAIL PROTECTED]>
wrote:

>On Fri, 01 Apr 2005 19:56:55 +, Ron_Adam wrote:
>
>> On Fri, 01 Apr 2005 13:47:06 -0500, Jeremy Bowers <[EMAIL PROTECTED]>
>> wrote:
>>>Is this an April Fools gag? If so, it's not a very good one as it's quite
>>>in line with the sort of question I've seen many times before. "I have
>>>a hammer, how do I use it to inflate my tire?"
>> 
>> Not an April fools gag, I'm just new to decorators and google brings
>> up lots of discussions from the past on how they may be implemented in
>> the future, but not much in actually how they work or how to use them.
>
>OK, just checking :-)
>
>A decorator is completely equivalent in principle to
>
>def function():
>   pass
>function = decorator(function)

This helped some.  Thanks.

>That's a simplified form; decorators can themselves be an expression which
>returns a callable that can be applied to a function and the rule for
>applying several in sequence work as you'd expect (pipelining earlier
>results into later ones, making for a great Obfuscated Python entry or
>two based on the "function name misdirection" trick), but this simplified
>form captures the essense, which is what I think you're looking for. In
>particular, it's just "syntax sugar", not a "special feature".

Are you sure?  There appears to be some magic involved with these,
things happening under the hood with argument passing.  

def decorate(function):
def wrapper(args):
print 'args' = args
return function(args)
return wrapper

@decorate
def func(s):
print s

func('hello')

In this example, how does wrapper get the correct arguments? This
leads me to believe what I'm looking for is possible, yet in this case
there isn't any way to pass, new arguments to the wrapper without
loosing the original ones.

Wait a min, hold the phone.. Eureka!  :)  I just figured how to do it.

(after trying it in idle)

def append_arg(n_args):
def get_function(function):
def wrapper(args):
return function(args+'-'+n_args)
return wrapper
return get_function

@append_arg('goodbye')
def func(s):
print s

func('hello')

prints:

hello-goodbye

Ok, this isn't a very useful example, but it demonstrates something
important. That, there seems to be a stack involved in the argument
passing of nested defined functions.  Any arguments passed in the
decorators get puts on top of the stack. And nested functions pull
them back off.  Does this sound right?

I still feel it can be simplified a bit. These aren't easy to
understand, and having to nest functions like this adds to the
confusion. possibly being able to get the argument "stack", as it
appears to be, directly in the first level could make things a lot
easier.


>
>Feeling-like-I-owed-you-an-answer-after-the-april-fool-accusation-ly yrs,
>Jeremy Bowers
>:-)

Thanks, it helped. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Terry Reedy

"Raymond Hettinger" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> More important than the percentage is the clarity of the resulting code 
> and the
> avoidance of continous reinvention of workarounds.
>
> Separating tool features into a basic and an advanced version is common 
> solution
> to managing option/customization complexity.

A super bells & whistles dict would certainly pre-answer a lot of queries 
and save much newsgroup/list response time.

tjr



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


Installing Python on a Windows 2000 Server

2005-04-01 Thread Mike Moum
Hi,
I'm a civil engineer who also doubles as chief programmer for technical 
applications at my company. Most of our software is written in Visual 
Basic because our VP in charge of I.T. likes to have "consistency", and 
at the moment we're a Microsoft shop. He has assigned me the task of 
developing an new application, the exact nature of which is not 
important for my question. I told him that, in my opinion, that Visual 
Basic was not the best choice for developing this application, and that 
I wanted to use Python. After a bit of discussion of the pros and cons, 
he said to go ahead. I managed to keep my jaw from hitting the floor. :>)

We have a central server array running Windows Server 2000 (I think 
that's the right name; networking is not my specialty, but it's 
definately Windows). Some of our workstations run Windows 2000; others 
run Windows XP Pro. I would like to install Python on the server, and 
run the application that I'll be developing from the workstations, 
without having to install any Python components on the workstations 
themselves. In other words, the Python executable, and the various 
libraries, dll's, and what have you, as well as the application that I'm 
developing, should all reside on the server. The only thing on the 
workstations would be a shortcut to myapplication.py.

Does anyone know whether it is possible to do this? I've done some 
Google searching, with no conclusive results, and poked about on 
python.org, but haven't really been able to find anything. Normally I'd 
be happy to just try it out and see what happens, but we're breaking new 
ground here (this is an amazingly big step for our hide-bound IS 
department!), so I'd like everything to go as smoothly as possible.

TIA,
Mike
--
http://mail.python.org/mailman/listinfo/python-list


FAM and Python? (was Re: How To Do It Faster?!?)

2005-04-01 Thread Jeremy Bowers
On Sat, 02 Apr 2005 02:02:31 +0200, andrea_gavana wrote:

> Hello Jeremy & NG,
> Every user of thsi big directory works on big studies regarding oil fields.
> Knowing the amount of data (and number of files) we have to deal with 
> (produced
> by simulators, visualization tools, and so on) and knowing that users are
> usually lazy in doing clean up of unused/old files, this is a way for one
> of us to "fast" scan all the directories and identify which files belong
> to him. Having them in an organized, size-sorted wxPython list, the user
> can decide if he want to delete some files (that almost surely he forgot
> even that they exist...) or not. It is easy as a button click (retrieve
> the data-->delete the files).

Got it. A good idea!

>>Here's an idea to sort of come at the problem from a different angle. Can
>>you run something on the file server itself, and use RPC to access it?
> 
> I don't even know what is RPC... I have to look at it.

RPC stands for "remote procedure call". The idea is that you do something
that looks like a normal function call, except it happens on a remote
server. Complexity varies widely.

Given your situation, and if running something on the UNIX server is a
possibility, I'd recommend downloading and playing with Pyro; it is Python
specific, so I think it would be the best thing for you, being powerful,
well integrated with Python, and easy to use.

Then, on your client machine in Windows, ultimately you'd make some sort
of call to your server like

fileList = server.getFileList(user)

and you'd get the file list for that user, returning whatever you want for
your app; a list of tuples, objects, whatever you want. Pyro will add no
constraints to your app.

> I am not sure if my new explanation fits with your last information... as
> above, I didn't even know about fam... I've read a little, but probably
> I am too newbie to see a link between it and my scope. Do you think it exists?
> It would be nice to have something that tracks the file status on all the
> file system, but probably is a LOT of work wrt what my app should be able
> to do.

Maybe, maybe not. I've never used FAM. Perhaps someone who has can chime
in about the ease of use; I've changed the subject to try to attract such
a person. It also depends on if FAM works on your UNIX.

My point is that you can do one scan at startup (can't avoid this), but
then as the file system monitor tells you that a change has occurred, you
update your data structures to account for the change. That way, your data
is always in sync. (For safety's sake, you might set the server to
terminate itself and re-start every night.) Since it's always in sync, you
can send this data back instead of scanning the file system.

At this point, my suggestion would be to consider whether you want to
spend the effort to speed it up like this, which is something only you
(and presumably your managers) are in a position to know, given that you
have an existing tool (at least, you seem to speak like you have a
functional tool). If you do, then I'd take some time and work a bit with
Pyro and FAM, and *then* re-evaluate where you stand. By then you'll
probably be able to ask better questions, too, and like I said above,
perhaps someone will share their experiences with FAM.

Good luck, and have fun; seriously, that's important here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Search-and-delete text processing problem...

2005-04-01 Thread lostboard2001
Close:

> if line[:4] == 'Bill':
. ^^
> line == ' '
>

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


Re: Ternary Operator in Python

2005-04-01 Thread gene . tani
The good ol' DiveInto says:

http://diveintopython.org/power_of_introspection/and_or.html#d0e9975

http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52310

Diez B. Roggisch wrote:
> praba kar wrote:
>
> > Dear All,
> > I am new to Python.  I want to know how to
> > work with ternary operator in Python.  I cannot
> > find any ternary operator in Python.  So Kindly
> > clear my doubt regarding this
>
> There is no ternary operator in python. There are several idioms that
can be
> used to emulate one to a certain degree - but they are scolwed on by
quite
> a few people. So better to not use them and just do it in a if: else:
> clause. 
> 
> -- 
> Regards,
> 
> Diez B. Roggisch

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


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Tom Breton
Daniel Silva <[EMAIL PROTECTED]> writes:

[...]

> So now FOLD.  This is actually the one we've always hated most,
> because, apart from a few examples involving + or *, almost every time
> we see a FOLD call with a non-trivial function argument, we have to
> grab pen and paper and imagine the *result* of a function flowing back
> in as the *argument* to a function.  Plus, there are *more* arguments
> coming in on the side!  This is all absurdly complicated.  Because
> almost all the examples of FOLD we found in practice could be written
> as a simple loop with an accumulator, this style should be preferred,
> perhaps with us providing a simple helper function to abstract away
> the boilerplate code.  At any rate, FOLD must fold.

Couldn't you leave it in for just another month?  And during the
remaining month, we'll just call it the "APRIL FOLD".

-- 
Tom Breton, the calm-eyed visionary
-- 
http://mail.python.org/mailman/listinfo/python-list


[Newbie] Search-and-delete text processing problem...

2005-04-01 Thread Todd_Calhoun
I'm trying to learn about text processing in Python, and I'm trying to 
tackle what should be a simple task.

I have long text files of books with a citation between each paragraph, 
which might be like "Bill D. Smith, History through the Ages, p.5".

So, I need to search for every line that starts with a certain string (in 
this example, "Bill D. Smith"), and delete the whole line.

I've tried a couple of different things, but none seem to work.  Here's my 
latest try.  I apologize in advance for being so clueless.

##
#Text search and delete line tool

theInFile = open("test_f.txt", "r")
theOutFile = open("test_f_out.txt", "w")

allLines = theInFile.readlines()

for line in allLines:
if line[3] == 'Bill':
line == ' '


theOutFile.writelines(allLines)
#

I know I could do it in Word fairly easily, but I'd like to learn the Python 
way to do things.

Thanks for any advice. 


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


Re: unittest vs py.test?

2005-04-01 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Peter Hansen <[EMAIL PROTECTED]> wrote:

> As for Roy's comments: I use a small internally
> developed driver script which uses os.walk to find
> all the files matching tests/*_unit.py or tests/story*.py
> in all subfolders of the project, and which runs them
> in separate processes to ensure none can pollute
> the environment in which other tests run.  I can
> dispense with the unittest.main() call, but I like
> to be able to run the tests standalone.  I guess
> with py.test I couldn't do that...

Actually, I believe it does.  I'm just starting to play with this, but it 
looks like you can do:

py.test test_sample.py

and it'll run a single test file.  I imagine you could use your os.walk 
fixture in combination with this to run each test in its own process if you 
wanted to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator in Python

2005-04-01 Thread Carl Banks

Terry Reedy wrote:
> "Carl Banks" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> >> A unary operator has one operand; a binary operator has two
operands;
> >> ternary operator has three operands.  Python has none built-in,
> >
> > Not so fast, my friend.  What about the expression "0.0 < a < 1.0"?
>
> Gee, what about 0.0 < a < 1.0 < b < 2.0?  I see both as synthesized
> multinary operators, but your are right in that this combination does
act
> differently than a+b+c.

It seems that Python has an infinite number of operators.


-- 
CARL BANKS

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


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Aahz
In article <[EMAIL PROTECTED]>,
=?iso-8859-1?Q?Fran=E7ois?= Pinard  <[EMAIL PROTECTED]> wrote:
>[Sunnan]
>>
>> [...] for Pythons ideal of having one canonical, explicit way to
>> program.
>
>No doubt it once was true, but I guess this ideal has been abandoned a
>few years ago.
>
>My honest feeling is that it would be a mis-representation of Python,
>assertng today that this is still one of the Python's ideals.

Mind providing evidence rather than simply citing your feelings?  Yes,
there's certainly redundancy in Python right now, but a large portion of
that will go away in Python 3.0.  So where's the abandonment of the
ideal?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code -- 
not in reams of trivial code that bores the reader to death."  --GvR
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with splitting

2005-04-01 Thread RickMuller
Thanks to everyone who responded!! I guess I have to study my regular
expressions a little more closely.

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


Re: Looking for Benchmarklets to improve pyvm

2005-04-01 Thread Skip Montanaro

Stelios> I'm collecting small testlets to benchmark it, discover
Stelios> bottlenecks and improve it.  They should be small and not use
Stelios> any crazy modules.  Only [sys, os, itertools, thread,
Stelios> threading, math, random] for now.

Take a look around for Marc Andre Lemburg's pybench suite. 

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


Re: unittest vs py.test?

2005-04-01 Thread Peter Hansen
Raymond Hettinger wrote:
BTW, the above code simplifies to:
from py.test import raises
assert a == b
raises(Error, func, args)
This is pretty, but I *want* my tests to be contained
in separate functions or methods.  The trivial amount
of extra overhead that unittest requires fits with
the way I want to write my tests, so it basically
represents zero overhead for me.
The above doesn't look like it would scale very
well to many tests in terms of maintaining some
semblance of structure and readability.
And once you add some functions or whatever to do
that, I'm still unclear on how the one or two lines
of extra code that unittest requires represents
an amount of code that really merits the label "heavy".
As for Roy's comments: I use a small internally
developed driver script which uses os.walk to find
all the files matching tests/*_unit.py or tests/story*.py
in all subfolders of the project, and which runs them
in separate processes to ensure none can pollute
the environment in which other tests run.  I can
dispense with the unittest.main() call, but I like
to be able to run the tests standalone.  I guess
with py.test I couldn't do that...
If py.test provides a driver utility that does
effectively this, well, that's nice for users.  If
it doesn't run them as separate processes, it wouldn't
suit me anyway.
Still, it sounds like it does have a strong following
of smart people: enough to make me want to take a
closer look at it to see what the fuss is about. :-)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest vs py.test?

2005-04-01 Thread Raymond Hettinger
[Peter Hansen]
> unittest can really be rather light.  Most of our
> test cases are variations on the following, with
> primarily application-specific code added rather than
> boilerplate or other unittest-related stuff:
>
> import unittest
>
> class TestCase(unittest.TestCase):
>  def test01(self):
>  '''some test'''
>  self.assertEquals(a, b)
>
>  def test02(self):
>  '''another test'''
>  self.assertRaises(Error, func, args)
 . . .
> I'm a little puzzled why folks so often consider this
> particularly "heavy".

unittest never felt heavy to me until I used py.test.  Only then do you realize
how much boilerplate is needed with unittest.  Also, the whole py.test approach
has a much simpler object model.

BTW, the above code simplifies to:

from py.test import raises
assert a == b
raises(Error, func, args)


Raymond Hettinger


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


Re: StopIteration in the if clause of a generator expression

2005-04-01 Thread Raymond Hettinger
> I assumed that all standard sequence consumers (including list, of course)
would intercept
> the StopIteration of a sequence given them in the form of a generator
expression, so your
> lyst example would have an analogue for other sequence consumers as well,
right?
> I.e., there's not a hidden list(genex) in those others I would hope ;-)

Right.



> E.g., "in" in my toy exposed more clearly, using Peter's stop:
>
>  >>> def show(x): print x,; return x
>  ...
>  >>> def stop(): raise StopIteration
>  ...
>  >>> 2 in (x for x in xrange(5) if show(x)<4 or stop())
>  0 1 2
>  True
>  >>> 7 in (x for x in xrange(5) if show(x)<4 or stop())
>  0 1 2 3 4
>  False
>
> BTW I notice that this also nicely shortcuts when the 2 is found.

That's a fact.


Raymond


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


Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Raymond Hettinger
> >Taken together, these six attributes/methods could cover many wished for
> >features for the 10% of the cases where a regular dictionary doesn't provide
the
> >best solution.

> You think as much as 10% ?

Rounded up from 9.6 ;-)

More important than the percentage is the clarity of the resulting code and the
avoidance of continous reinvention of workarounds.

Separating tool features into a basic and an advanced version is common solution
to managing option/customization complexity.


Raymond


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


Re: New to programming question

2005-04-01 Thread Steve Holden
Joal Heagney wrote:
Bengt Richter wrote:
On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney <[EMAIL PROTECTED]> 
wrote:


Oh goddammmni. I seem to be doing this a lot today. Look below 
for the extra addition to the code I posted.

Joal Heagney wrote:
Here's my contribution anycase:
count = 0
# Get first input
name = raw_input("Guess my name: ")
# Give the sucker two extra goes
while count < 2:
   # Check the value of name
   if name == 'Ben':
   print "You're right!"
   break
   else:
   name = raw_input("Try again: ")

  # Here's the bit I missed out.
  count += 1
# Of course, we haven't checked the sucker's last guess
# so we have to do that now.
if count == 2:
   if name == 'Ben':
   print "You're right!"
   else:
   print "No more tries for you!!!"
Hope this helps.
Joal

G.

Need something more straightforward, e.g., a wrapped one-liner:
 >>> def guess(n=3): print ("You're right!", 'No more tries for 
you!!!')[n-1 in
 ...(x for x in xrange(n) for t in [raw_input('Guess my name: 
')=='Ben']
 ...if not t or iter([]).next())]

Okay, now in my opinion, that's just too complex to give to a newbie as 
a suggested implementation. :)

Joal
I suppose this would be far too easy to understand, then:
pr =['Guess my name', 'Wrong, try again', 'Last chance']
for p in pr:
  name = raw_input(p+": ")
  if name == "Ben":
print "You're right!"
break
else:
  print "Loser: no more tries for you"
regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: [python-perl] Translation review?

2005-04-01 Thread Steve Holden
Traceback (most recent call last):
  File "", line 19, in ?
IOError: [Errno 2] No such file or directory: ''
(in both Windows 2.4 and Cygwin 2.4)
regards
 Steve
TSO wrote:
Hi there,

I've recently tried to translate some Perl code into Python - code is below.
Is there a more Pythonic form?
Also, is there a good reason why there are plans to remove lambda from the 
language?
yrs complements-of-the-season-ly...


 START OF CODE



## 2005-04-01 - TSO
## with apologies to Erudil
import sys,math;[
   vars()
   .__setitem__(
   "ham",  lambda(spam):("").
   join([chr((   spam/144**i)%(02*72))
  for(i)in  xrange( int(math.log(spam**0.5,
12)+1))])),[(lambda*   spam:globals().update({}
.__class__([spam])))(ham(spam),eval(ham(__spam))
 )for(spam,__spam)in[  (47631497714,0x3A305499C7D37),
(47159984399,2337674),(327499859,2336509),(8901
   +34553*1,   2402179),(6303405375459,2295612),(11+
  7540504603011,  303839094),(95,2295612),(7540504603011,
 303839094),(95,0x16241495E6D60314676F55F45E4D3F906),(216*
 10529,0x1053924DE35309345),(0x6DB401B64DC,0x262efd)]]and(_)
 (ham(231280211),[bacon(spam,ham(0x65936781522))()for(spam)in
  crispy(bacon(bacon((bacon(eggs,ham(0x1051936D9600B6F4F)))(0)
  ,ham(6296985467094)),ham(390129778476214073077203)))]+[bacon(
   ham(32),ham(48473858995))()]),_(ham(110),(lovely)(Spam(cheese
,SPAM))),_(ham(231280211),[[int((lambda spam:bacon(bacon(ham
 (32),ham(48473858995))(),ham(330651610))([ham(6961)[bacon((
   spam),ham(+906698009388057))()]for(spam)in(spam)]))(spam+
 spam_),2)for(spam,spam_)in(lambda(spam):[(spam)for(spam)
   in(_spam)(spam[::2],spam[1::2])])(list(_spam(*spam)))]
  for(spam)  in(lambda(spam):list(_spam(spam[::2],spam
[1::2])))([(spam+ham   (32)*n)[:n]for(
   spam)in(SPAM)])])or(Spam)((
  bacon)(   bacon(eggs,ham
(7233055643059
 )),ham(224343
 +   11402701*10**
 6+  30804988*10**
  14) ),[(spam)for
  spam   in(_spam)(*[
 (ham(   668732698837
  )%(spam_  ,_spam),ham(
   668732698   *1000+837)%(
_spam,spam_   ))for(_spam,
 spam_)in(_spam)(*Spam(lambda
   (spam_,_spam):   [bacon(bacon
 (ham(32),ham( 0xB494463B3)
   )(),ham(610+   330651000))(
[_spam[spam]for(spam)in(spam)[::spam_
 *-2+1]])for(spam)in(SPAM)],Ham([ham
  (0x40BA541813CECF0323A994C40AA00)
 ,ham(412853488783846916352+
20980637114201*10**21
  )])))])])]
== END OF CODE

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


How To Do It Faster?!?

2005-04-01 Thread andrea_gavana
Hello Jeremy & NG,

>Yes, clearer, though I still don't know what you're *doing* with that data
:-)

Every user of thsi big directory works on big studies regarding oil fields.
Knowing the amount of data (and number of files) we have to deal with (produced
by simulators, visualization tools, and so on) and knowing that users are
usually lazy in doing clean up of unused/old files, this is a way for one
of us to "fast" scan all the directories and identify which files belong
to him. Having them in an organized, size-sorted wxPython list, the user
can decide if he want to delete some files (that almost surely he forgot
even that they exist...) or not. It is easy as a button click (retrieve
the data-->delete the files).

>Here's an idea to sort of come at the problem from a different angle. Can
>you run something on the file server itself, and use RPC to access it?

I don't even know what is RPC... I have to look at it.


>The reason I mention this is a lot of UNIXes have an API to detect file
>changes live; for instance, google "python fam". It would be easy to hook
>something up to scan the files at startup and maintain your totals live,
>and then use one of the many extremely easy Python RPC mechanisms to
>request the data as the user wants it, which would most likely come back
>at network speeds (fast).

I am not sure if my new explanation fits with your last information... as
above, I didn't even know about fam... I've read a little, but probably
I am too newbie to see a link between it and my scope. Do you think it exists?
It would be nice to have something that tracks the file status on all the
file system, but probably is a LOT of work wrt what my app should be able
to do.
Anyway, thanks for the hints! If my new explanation changed something, can
anyone post some more comments?

Thanks to you all.

Andrea.

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


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

2005-04-01 Thread Steve Holden
Javier Bezos wrote:
"Myles Strous" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]
satisfy some handy properties, the first of which being:
 l[:n] + l[n:] = l
I don't think l[:5] + l[5:] = l is a handy property
and to me is clearly counterintuitive. Further,
It can be quite useful for inserting something into a list (or string),
after finding the position where you wish to insert it.
improvedList = l[:n] + [new stuff] + l[n:]

As I answered in another post this is not more
useful than writing l[:n-1]. Of course, I'm aware
of the case where n=0, but this would require only
a bit of extra code (and, after all, I'm just saying
that half-open ranges are not a panacea and that I
don't like their side effects).

I vaguely remember hearing at one stage that the
sequence[position:position+length] notation is also potentially useful
for indexing into large strings or buffers.

Right, to some extent it's useful, but at the cost
of introducing tricky syntaxes for very specific
cases, like this one, and unexpected off-by-one
errors in other cases, which is my point. For
example, recently I had to get a value from a
list preceded by the two previous values:
lst[n-2:n+1] and not the more logical (at last
to my eyes) lst[n-2:n].
Instead of giving further examples I would like
to cite three cases:
1) You have a starting point (s) and a
   length (t): lst[s:s+t].
2) You have an ending point (e) and a
   length: lst[e-t+1:e+1].
3) You have a starting point and an ending
   point: lst[s:e+1].
What's odd is that Python applies the syntax of
case 3 to the logic of case 1. While something
like lst[s:s+t-1] for the first case could be
explained in simple mathematical terms (in other
words, it's an integral part of the algorithms),
I cannot find a way to explain the e+1 in cases
2 and 3 (and the inconsistency with e-t+1 in case
2 vs. s+t in case 1) except the Python syntax.
While this may be an interesting philosophical (or should that be 
philological) discussion, since Python has worked this way for donkey's 
years, and since a change would break 30% of the existing codebase, you 
clearly can't be advocating change.

So, what's the point of this thread now?
regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator in Python

2005-04-01 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Carl Banks" <[EMAIL PROTECTED]> wrote:

> Terry Reedy wrote:
> > "praba kar" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> > > Dear All,
> > >I am new to Python.  I want to know how to
> > > work with ternary operator in Python.  I cannot
> > > find any ternary operator in Python.  So Kindly
> > > clear my doubt regarding this
> >
> > A unary operator has one operand; a binary operator has two operands;
> a
> > ternary operator has three operands.  Python has none built-in,
> 
> Not so fast, my friend.  What about the expression "0.0 < a < 1.0"?

I still remember one of the earliest bugs I ever wrote (I've long since 
forgotten most of the zillions I've written since).  It must have been 
around 1975, and my high school had an ASR-33 connected to a HP-3000 
running Time Shared Basic at another school a few towns away.

I wrote something like "1 < X < 10" and got an error.  I was puzzled by 
this, since we were using this notation in math class.  The answer of 
course was that I needed to write "1 < X AND X < 10", which I found really 
annoying and strange looking.  Or is my long-term memory returning 
corrupted data?  Maybe BASIC let you do 1 < X < 10, but I ran into this 
when I moved onto FORTRAN the next year?

In any case, I've gotten so used to writing 1 < x && x < 10 (or variations 
on the theme) that now I've got a language which lets me write it the 
normal math way, 1 < x < 10, and *that* looks strange.  Wierd, huh?  How 
our tools warp our thinking.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: that is it is not it (logic in Python)

2005-04-01 Thread Terry Reedy

"F. Petitjean" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a écrit :
>> Reread the ref manual on chained comparison operators.

>And see the date of the post :-)

Ditto for the reply ;-)

TJR





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


Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Bengt Richter
On Fri, 01 Apr 2005 23:04:42 GMT, "Raymond Hettinger" <[EMAIL PROTECTED]> wrote:

>[Bengt Richter]
>> I wonder if a dict with a general override hook for hashing all keys would be
>useful.
>> E.g.,  a dict.__keyhash__ that would take key as arg and default as now
>returning key.__hash__()
>> but that you could override. Seems like this could potentially be more
>efficient than key wrappers,
>> and would also make it so you wouldn't have to chase all the affected methods
>in doing an idict
>> like the above (e.g., get, setdefault, update etc. etc.)
>
>There has also been a discussion of adding a seqdict that maintains a keys in
>insertion order.  Another idea was to have a defaultdict that could be
>instructed to create values as necessary (either zero for counting or [] for
>list building).  Putting the three ideas together, perhaps we should write an
>extension module with a custom dictionary type with methods/attributes
>implementing those ideas.  Essentially, the thought is to put all the bells and
>whistles in one place.  If the extension became popular, it could ultimately
>wend its way into the collections module.
>
>A facetious naming idea would be to call it TrickyDict, a relative to DictMixin
>and no relation to a former U.S. president ;-)
>
>t = TrickyDict()
>t.keytransform(str.lower)
>t['abC'] = 1  # case insensitive dictionary
>assert t['Abc'] == 1
 assert t.keys() == ['abC']# actual keys unchanged (but transformed for 
hash and cmp)
[...]
>
>Taken together, these six attributes/methods could cover many wished for
>features for the 10% of the cases where a regular dictionary doesn't provide 
>the
>best solution.
You think as much as 10% ?

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


Re: System bell

2005-04-01 Thread Trent Mick
[Mr6 wrote]
> It's a weird thing. But if I run print "\a" from idle it does not work. 
> But if I save as a file, say, sound.py. Then run that with python 
> sound.py it does.
> 
> Why is that?

The IDLE stdout/stderr handling is not invoking a system bell when it
sees '\a'. I suppose that one could consider that a bug. If I were an
IDLE developer/maintainer, I don't think I'd rate that as a very high
prioirty bug though. :)

Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How To Do It Faster?!?

2005-04-01 Thread Jeremy Bowers
On Sat, 02 Apr 2005 01:00:34 +0200, andrea_gavana wrote:

> Hello Jeremy & NG,
> ...
> I hope to have been clearer this time...
> 
> I really welcome all your suggestions.

Yes, clearer, though I still don't know what you're *doing* with that data :-)

Here's an idea to sort of come at the problem from a different angle. Can
you run something on the file server itself, and use RPC to access it?

The reason I mention this is a lot of UNIXes have an API to detect file
changes live; for instance, google "python fam". It would be easy to hook
something up to scan the files at startup and maintain your totals live,
and then use one of the many extremely easy Python RPC mechanisms to
request the data as the user wants it, which would most likely come back
at network speeds (fast).

This would be orders of magnitude faster, and no scanning system could
compete with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unittest vs py.test?

2005-04-01 Thread Roy Smith
Peter Hansen <[EMAIL PROTECTED]> wrote:
> unittest can really be rather light.  Most of our
> test cases are variations on the following, with
> primarily application-specific code added rather than
> boilerplate or other unittest-related stuff:
> 
> import unittest
> 
> class TestCase(unittest.TestCase):
>  def test01(self):
>  '''some test'''
>  self.assertEquals(a, b)

Well, right there the "extra" stuff you needed to do (vs. py.test) was 
import unittest, inherit from it, and do "self.assertEquals" instead of 
just plain assert.  But (see below), that's not the big thing that attracts 
me to py.test.

> I'm a little puzzled why folks so often consider this
> particularly "heavy".  No need to deal with suites,
> TestResult objects, etc, as others have suggested,
> unless you are trying to extend it in some special
> way.

In all but the most trivial project, you're going to have lots of tests.  
Typically, each class (or small set of closely related classes) will go in 
one source file, with a corresponding test file.  You'll probably have 
stuff scattered about a number of different directories too.  That means 
you need to build some infrastructure to find and run all those various 
tests.

One way would be futzing with suites (which I still haven't completely 
figured out).  Another way would be building a hierarchical series of 
dependencies in Make (or whatever build tool you use) to run your tests.  
The latter is what I usually do.  The idea that I can just type "python 
py.test" at the top level and have it find and run everything for me just 
blows me away convenience-wise.

I also like the idea that I just stick print statements into my tests and 
the output automagically goes away unless the test fails.  I'm a firm 
believer that unit tests should NOT PRODUCE ANY OUTPUT unless they fail.  
I'm working with a system now where the unit tests not only produce reams 
of output, but it's also rigged to keep going in the face of failure.  
Trying to find the actual error in the output is a nightmare.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator in Python

2005-04-01 Thread Terry Reedy

"Carl Banks" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> A unary operator has one operand; a binary operator has two operands;
>> ternary operator has three operands.  Python has none built-in,
>
> Not so fast, my friend.  What about the expression "0.0 < a < 1.0"?

Gee, what about 0.0 < a < 1.0 < b < 2.0?  I see both as synthesized 
multinary operators, but your are right in that this combination does act 
differently than a+b+c.

Terry J. Reedy




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


Re: Help with splitting

2005-04-01 Thread Jeremy Bowers
On Fri, 01 Apr 2005 18:01:49 -0500, Brian Beck wrote:
> py> from itertools import groupby
> py> [''.join(g) for k, g in groupby('  test ing ', lambda x: x.isspace())]
> ['  ', 'test', ' ', 'ing', ' ']
> 
> I tried replacing the lambda thing with an attrgetter, but apparently my 
> understanding of that isn't perfect... it groups by the identify of the 
> bound method instead of calling it...

Unfortunately, as you pointed out, it is slower:

python timeit.py -s 
"import re; x = 'a ab c' * 1000; whitespaceSplitter = re.compile('(\w+)')"

"whitespaceSplitter.split(x)" 

100 loops, best of 3: 9.47 msec per loop

python timeit.py -s
"from itertools import groupby; x = 'a ab c' * 1000;" 

"[''.join(g) for k, g in groupby(x, lambda y: y.isspace())]"

10 loops, best of 3: 65.8 msec per loop

(tried to break it up to be easier to read)

But I like yours much better theoretically. It's also a pretty good demo
of "groupby".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with splitting

2005-04-01 Thread Raymond Hettinger
[Brian Beck]>
> py> from itertools import groupby
> py> [''.join(g) for k, g in groupby('  test ing ', lambda x: x.isspace())]
> ['  ', 'test', ' ', 'ing', ' ']

Brilliant solution!

That leads to a better understanding of groupby as a tool for identifying
transitions without consuming them.


> I tried replacing the lambda thing with an attrgetter, but apparently my
> understanding of that isn't perfect... it groups by the identify of the
> bound method instead of calling it...

Right.
attrgetter gets but does not call.

If unicode isn't an issue, then the lambda can be removed:

>>> [''.join(g) for k, g in groupby('  test ing ', str.isspace)]
['  ', 'test', ' ', 'ing', ' ']



Raymond Hettinger


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


Re: unittest vs py.test?

2005-04-01 Thread Peter Hansen
Colin J. Williams wrote:
unittest seems rather heavy.  I don't like mixing tests with 
documentation, it gives the whole thing a cluttered look.
unittest can really be rather light.  Most of our
test cases are variations on the following, with
primarily application-specific code added rather than
boilerplate or other unittest-related stuff:
import unittest
class TestCase(unittest.TestCase):
def test01(self):
'''some test'''
self.assertEquals(a, b)
def test02(self):
'''another test'''
self.assertRaises(Error, func, args)
if __name__ == '__main__':
unittest.main()
That's it... add testXX() methods as required and
they will be executed in sorted order (alphabetically)
automatically when you run from the command line.
The above might look excessive in comparison to the
test code, but add some real code and the overhead
quickly dwindles to negligible.
I'm a little puzzled why folks so often consider this
particularly "heavy".  No need to deal with suites,
TestResult objects, etc, as others have suggested,
unless you are trying to extend it in some special
way.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: that is it is not it (logic in Python)

2005-04-01 Thread F. Petitjean
Le Fri, 01 Apr 2005 17:42:30 -0500, Jeremy Bowers a écrit :
> On Fri, 01 Apr 2005 22:01:25 +, F. Petitjean wrote:
> 
>> Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a écrit :
>>> This is equivalent to '(that is it) and (it is not it)' which is clearly 
>>> false.
>>> 
 False   # What ?
>>> 
>>> Reread the ref manual on chained comparison operators.
>>
>> And see the date of the post :-)
>> that is it  isn't it ?
> 
> Nope, nothing to do with it. Read the ref manual on chained comparision
> operators.
> 
> http://www.python.org/doc/2.4/ref/comparisons.html#l2h-430
> 
> For proof, run the given code in the original post. It's not faked in the
> slightest, and the manual holds the key to understanding.
*I* wrote the original post.  and am pretty sure it is not faked. And I
run it before posting to be sure not to say anything wrong. it is a kind
of relief to learn that computers in 2005 (even Python powered) are
humor-impaired and follow the « ref manual » every time even on first
April.

>>> There = True
>>> Python = map(bool, range(5))
>>> logic = True
>>> There is logic in Python
True   # naturally
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2005-04-01 Thread David Bolen
"Paul L. Du Bois" <[EMAIL PROTECTED]> writes:

> Has anyone written a Queue.Queue replacement that avoids busy-waiting?
> It doesn't matter if it uses os-specific APIs (eg
> WaitForMultipleObjects).  I did some googling around and haven't found
> anything so far.

This isn't a Queue.Queue replacement, but it implements a buffer
intended for inter-thread transmission, so it could be adjusted to
mimic Queue semantics fairly easily.  In fact, internally it actually
keeps write chunks in a list until read for better performance, so
just removing the coalesce process would be the first step.

It was written specifically to minimize latency (which is a
significant issue with the polling loop in the normal Python Queue
implementation) and CPU usage in support of a higher level
Win32-specific serial I/O class, so it uses Win32 events to handle the
signaling for the key events when waiting.

The fundamental issue with the native Python lock is that to be
minimalistic in what it requires from each OS, it doesn't impose a
model of being able to wait on an event signal - that's the key thing
you need to have (a timed blocking wait on some signalable construct)
to be most efficient for these operations - which is what I use the
Win32 Event for.

-- David

  - - - - - - - - - - - - - - - - - - - - - - - - -

import thread
import win32event as we

class Buffer:
"""A thread safe unidirectional data buffer used to represent data
traveling to or from the application and serial port handling threads.

This class is used as an underlying implementation mechanism by SerialIO.
Application code should not typically need to access this directly, but
can handle I/O through SerialIO.

Note that we use Windows event objects rather than Python's because
Python's OS-independent versions are not very efficient with timed waits,
imposing internal latencies and CPU usage due to looping around a basic
non-blocking construct.  We also use the lower layer thread lock rather
than threading's to minimize overhead.
"""

def __init__(self, notify=None):
self.lock = thread.allocate_lock()
self.has_data = we.CreateEvent(None,1,0,None)
self.clear()
self.notify = notify

def _coalesce(self):
if self.buflist:
self.buffer += ''.join(self.buflist)
self.buflist = []

def __len__(self):
self.lock.acquire()
self._coalesce()
result = len(self.buffer)
self.lock.release()
return result

def clear(self):
self.lock.acquire()
self.buffer = ''
self.buflist = []
self.lock.release()

def get(self, size=0, timeout=None):
"""Retrieve data from the buffer, up to 'size' bytes (unlimited if
0), but potentially less based on what is available.  If no
data is currently available, it will wait up to 'timeout' seconds
(forever if None, no blocking if 0) for some data to arrive"""

self.lock.acquire()
self._coalesce()

if not self.buffer:
# Nothing buffered, wait until something shows up (timeout
# rules match that of threading.Event)
self.lock.release()
if timeout is None:
win_timeout = we.INFINITE
else:
win_timeout = int(timeout * 1000)
rc = we.WaitForSingleObject(self.has_data, win_timeout)
self.lock.acquire()
self._coalesce()

if not size:
size = len(self.buffer)

result_len = min(size,len(self.buffer))
result = self.buffer[:result_len]
self.buffer = self.buffer[result_len:]
we.ResetEvent(self.has_data)
self.lock.release()
return result

def put_back(self,data):
self.lock.acquire()
self.buffer = data + self.buffer
self.lock.release()
we.SetEvent(self.has_data)
if self.notify:
self.notify()

def put(self, data):
self.lock.acquire()
self.buflist.append(data)
self.lock.release()
we.SetEvent(self.has_data)
if self.notify:
self.notify()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Raymond Hettinger
[Bengt Richter]
> I wonder if a dict with a general override hook for hashing all keys would be
useful.
> E.g.,  a dict.__keyhash__ that would take key as arg and default as now
returning key.__hash__()
> but that you could override. Seems like this could potentially be more
efficient than key wrappers,
> and would also make it so you wouldn't have to chase all the affected methods
in doing an idict
> like the above (e.g., get, setdefault, update etc. etc.)

There has also been a discussion of adding a seqdict that maintains a keys in
insertion order.  Another idea was to have a defaultdict that could be
instructed to create values as necessary (either zero for counting or [] for
list building).  Putting the three ideas together, perhaps we should write an
extension module with a custom dictionary type with methods/attributes
implementing those ideas.  Essentially, the thought is to put all the bells and
whistles in one place.  If the extension became popular, it could ultimately
wend its way into the collections module.

A facetious naming idea would be to call it TrickyDict, a relative to DictMixin
and no relation to a former U.S. president ;-)

t = TrickyDict()
t.keytransform(str.lower)
t['abC'] = 1  # case insensitive dictionary
assert t['Abc'] == 1

t = TrickyDict()
t.setdefaultvalue(0)
t['x'] += 1 # very bag like
assert t['x'] == 1

t = TrickyDict()
t.setdefaultfunction(list)
t['x'] += ['first']  # rather like: t.setdefault('x',
[]).append('first')
t['x'] += ['second']
assert t == {'x': ['first', 'second']}

t = TrickyDict()
t.sortedkeys = True
t['x'] = 1
t['y'] = 2
assert t.keys() == ['x', 'y']   # order is guaranteed

This universal dictionary type could also incorporate some methods for other
recurrent themes such as a inverting a dictionary:

def invdict(self)
return self: dict((v,k) for k,v in self.iteritems()).

For the performance minded, there could also be a control for dictionary
speed/space efficiency:

t = TrickyDict()
t.maxkeydensity = 40  # resize whenever the dictionary is more than 40%
full

Taken together, these six attributes/methods could cover many wished for
features for the 10% of the cases where a regular dictionary doesn't provide the
best solution.


Raymond


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


Re: Help with splitting

2005-04-01 Thread Brian Beck
RickMuller wrote:
There's a chance I was instead thinking of something in the re module,
but I also spent some time there without luck. Could someone point me
to the right function, if it exists?
The re solution Jeremy Bowers is what you want. Here's another (probably 
much slower) way for fun (with no surrounding empty strings):

py> from itertools import groupby
py> [''.join(g) for k, g in groupby('  test ing ', lambda x: x.isspace())]
['  ', 'test', ' ', 'ing', ' ']
I tried replacing the lambda thing with an attrgetter, but apparently my 
understanding of that isn't perfect... it groups by the identify of the 
bound method instead of calling it...

--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


How To Do It Faster?!?

2005-04-01 Thread andrea_gavana
Hello Jeremy & NG,

>* Poke around in the Windows API for a function that does what you want,
>and hope it can do it faster due to being in the kernel.

I could try it, but I think I have to explain a little bit more my problem.

>If you post more information about how you are using this data, I can try
to help you.

Basically, I have to scan a really BIG directory: essentially, is a UNIX
file system where all our projects resides, with thousand and thousand of
files and more than 1 TB of information. However, we are about 200-300 users
of this space. This is what I do now and I would like to improve:

1) For a particular user (1 and only 1 at a time), I would like to scan
all directories and subdirectories in order to find which FILES are owned
by this user (I am NOT interested in directory owner, only files). Noting
that I am searching only for 1 user, its disc quota is around 20-30 GB,
or something like this;
2) My application is a GUI designed with wxPython. It run on Windows, at
the moment (this is why I am asking for Windows user IDs and similar, on
Unix is much simpler);
3) While scanning the directories (using os.walk), I process the results
of my command "dir /q /-c /a-d MyDirectory" and I display this results on
a wxListCtrl (a list viewer) of wxPython in my GUI;
4) I would not use the suggested command "dir /S" on a DOS shell because,
even if it scans recursively all directories, I am NOT able to process 
intermediate
results because this command never returns until it has finished to scan
ALL directories (and for 1 TB of files, it can take a LOT of time);
5) For all the files in each directory scanned, I do:
- IF a file belongs to that particular user THEN:
  Get the file name;
  Get the file size;
  Get the last modification date;
  Display the result on my wxListCtrl
- ELSE:
  Disregard the information;
- END

I get the file owner using the /Q switch of the DIR command, and I exclude
a priori the subdirectories using the /a-d switch. That because I am using
os.walk().
6) All of our users can see this big unix directory on their PC, labeled
as E:\ or F:\ or whatever. I can not anyway use UNIX command on dos (and
I can not use rsh to communicate with the unix machine and then use something
like "find . -name etc".

I hope to have been clearer this time...

I really welcome all your suggestions.

Andrea.

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


Re: System bell

2005-04-01 Thread Mr6
Bengt Richter wrote:
On Fri, 01 Apr 2005 02:06:07 -0500, Steve Holden <[EMAIL PROTECTED]> wrote:

Trent Mick wrote:
[Baza wrote]

Am I right in thinking that >>>print "\a" should sound the system, 'bell'?

It works on the shell on Windows for me (WinXP).
Trent
Interesting. From a Cygwin bash shell I got an elegant little dingish 
sort of a beep (my volume control was set kind of low). I then ran the 
same code in a Windows shell and nearly deafened myself. It appears that 
the volume control doesn't affect the Windows XP commans shell beep - 
even muting the Windows audio output doesn't stop it (though it does 
stop the Cygwin beep). This could cause heart attacks!


It's a weird thing. But if I run print "\a" from idle it does not work. 
But if I save as a file, say, sound.py. Then run that with python 
sound.py it does.

Why is that?
B
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest vs py.test?

2005-04-01 Thread Colin J. Williams
Grig Gheorghiu wrote:
In my mind, practicing TDD is what matters most. Which framework you
choose is a function of your actual needs. The fact that there are 3 of
them doesn't really bother me. I think it's better to have a choice
from a small number of frameworks rather than have no choice or have a
single choice that might not be the best for your specific environment
-- provided of course that this doesn't evolve into a PyWebOff-like
nightmare :-) 

Grig
Grig,
Many thanks for your helpful essays.
unittest seems rather heavy.  I don't like mixing tests with 
documentation, it gives the whole thing a cluttered look.
Py.test is the more appealing but it doesn't appear to be
ready for packaging yet.

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


Re: that is it is not it (logic in Python)

2005-04-01 Thread Jeremy Bowers
On Fri, 01 Apr 2005 22:01:25 +, F. Petitjean wrote:

> Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a Ãcrit :
>> This is equivalent to '(that is it) and (it is not it)' which is clearly 
>> false.
>> 
>>> False   # What ?
>> 
>> Reread the ref manual on chained comparison operators.
>
> And see the date of the post :-)
> that is it  isn't it ?

Nope, nothing to do with it. Read the ref manual on chained comparision
operators.

http://www.python.org/doc/2.4/ref/comparisons.html#l2h-430

For proof, run the given code in the original post. It's not faked in the
slightest, and the manual holds the key to understanding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with splitting

2005-04-01 Thread Jeremy Bowers
On Fri, 01 Apr 2005 14:20:51 -0800, RickMuller wrote:

> I'm trying to split a string into pieces on whitespace, but I want to
> save the whitespace characters rather than discarding them.
> 
> For example, I want to split the string '12' into ['1','','2'].
> I was certain that there was a way to do this using the standard string
> functions, but I just spent some time poring over the documentation
> without finding anything.

importPython 2.3.5 (#1, Mar  3 2005, 17:32:12) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> whitespaceSplitter = re.compile("(\w+)")
>>> whitespaceSplitter.split("1 2  3   \t\n5")
['', '1', ' ', '2', '  ', '3', '   \t\n', '5', '']
>>> whitespaceSplitter.split(" 1 2  3   \t\n5 ")
[' ', '1', ' ', '2', '  ', '3', '   \t\n', '5', ' ']

Note the null strings at the beginning and end if there are no instances
of the split RE at the beginning or end. Pondering the second invocation
should show why they are there, though darned if I can think of a good way
to put it into words.
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with splitting

2005-04-01 Thread RickMuller
I'm trying to split a string into pieces on whitespace, but I want to
save the whitespace characters rather than discarding them.

For example, I want to split the string '12' into ['1','','2'].
I was certain that there was a way to do this using the standard string
functions, but I just spent some time poring over the documentation
without finding anything.

There's a chance I was instead thinking of something in the re module,
but I also spent some time there without luck. Could someone point me
to the right function, if it exists?

Thanks in advance.

R.

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


Re: Pseudocode in the wikipedia

2005-04-01 Thread Ivan Van Laningham
Hi All--

Jeremy Bowers wrote:

> Your ass is your identity function.
> 
> Python 2.3.5 (#1, Mar  3 2005, 17:32:12)
> [GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 25
> 25
> >>> (_ | _)
> 25
> >>>
> 
> There's clearly some interesting biometrics research to be done here,
> although there is a well-known ass-capturing attack based on readily
> commercially available machines from Xerox that might make it hard to make
> an ass-based identity system resistant to attacks.

http://www.jacquelinestallone.com/rumps.html

Metta,
Ivan

PS:  I don't think this is an 0401 page; it's been there a while.
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Bengt Richter
On Fri, 01 Apr 2005 18:52:00 GMT, "Raymond Hettinger" <[EMAIL PROTECTED]> wrote:

>[Ville Vainio]
>> I need a dict (well, it would be optimal anyway) class that stores the
>> keys as strings without coercing the case to upper or lower, but still
>> provides fast lookup (i.e. uses hash table).
>
>
 class S(str):
>def __hash__(self):
>return hash(self.lower())
>def __eq__(self, other):
>return self.lower() == other.lower()
>
>
 d = {}
 d[S('ThE')] = 'quick'
 d[S('the')]
>'quick'
 d
>{'ThE': 'quick'}
>
Building on your S to sneak in a generalized idea ;-)

 >>> class idict(dict):
 ... def __setitem__(self, key, value):
 ... dict.__setitem__(self, S(key), value)
 ... def __getitem__(self, key):
 ... return dict.__getitem__(self, S(key))
 ...
 >>> d = idict()
 >>> d['ThE'] = 'quick'
 >>> d['the']
 'quick'
 >>> d
 {'ThE': 'quick'}

Ok, the idea:
I wonder if a dict with a general override hook for hashing all keys would be 
useful.
E.g.,  a dict.__keyhash__ that would take key as arg and default as now 
returning key.__hash__()
but that you could override. Seems like this could potentially be more 
efficient than key wrappers,
and would also make it so you wouldn't have to chase all the affected methods 
in doing an idict
like the above (e.g., get, setdefault, update etc. etc.)

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


Re: that is it is not it (logic in Python)

2005-04-01 Thread F. Petitjean
Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a écrit :
> 
> "F. Petitjean" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
> iterable = range(10)
> it = iter(iterable)
> that = iter(it)
> that is it
>> True# Good!
> that is it is not it
> 
> This is equivalent to '(that is it) and (it is not it)' which is clearly 
> false.
> 
>> False   # What ?
> 
> Reread the ref manual on chained comparison operators.
And see the date of the post :-)
that is it  isn't it ?
> 
> Terry J. Reedy
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Ulrich Hobelmann
alex goldman wrote:
Daniel Silva wrote:

At any rate, FOLD must fold.

I personally think GOTO was unduly criticized by Dijkstra. With the benefit
of hindsight, we can see that giving up GOTO in favor of other primitives
failed to solve the decades-old software crisis.
The fault of goto in imperative languages is that it has no 
arguments, thus creating spaghetti of gotos and assignments.

Continuations rule!
--
http://mail.python.org/mailman/listinfo/python-list


Re: decorator syntax polling suggestion

2005-04-01 Thread D H
Jeremy Bowers wrote:
On Fri, 01 Apr 2005 16:52:52 -0500, Jeremy Bowers wrote:
Oops, sorry, some "send later" messages I thought were gone got sent.
Sorry. Didn't mean to revive dead threads.
At least it happened on April Fool's.  Or should I say:
@aprilfools
def happened:
   at least
--
http://mail.python.org/mailman/listinfo/python-list


Re: decorator syntax polling suggestion

2005-04-01 Thread Jeremy Bowers
On Fri, 01 Apr 2005 16:52:52 -0500, Jeremy Bowers wrote:
Oops, sorry, some "send later" messages I thought were gone got sent.
Sorry. Didn't mean to revive dead threads.

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


Re: decorator syntax polling suggestion

2005-04-01 Thread Jeremy Bowers
On Fri, 13 Aug 2004 16:49:53 +1000, Anthony Baxter wrote:
> The
> people who hate pie-decorators post a _lot_ - most people seem to either
> not care, or else post once or twice and then disappear.

I just posted on another mailing list about how posting the same message,
over and over, is fundamentally offensive; it implies the belief, from
whatever the source, that the poster needs to "show you the light" and if
they just keep pounding on it, they'll eventually blast through your
ignorance. People who internalize this will not look loud in a debate, so
it is important to not just look at volume. 

(My call: Hated it at first, waded through the arguments and alternatives,
now agree with the syntax as is.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How To Do It Faster?!?

2005-04-01 Thread Jeremy Bowers
On Thu, 31 Mar 2005 13:38:34 +0200, andrea.gavana wrote:

> Hello NG,
> 
>   in my application, I use os.walk() to walk on a BIG directory. I
>   need
> to retrieve the files, in each sub-directory, that are owned by a
> particular user. Noting that I am on Windows (2000 or XP), this is what I
> do:

You should *try* directly retrieving the relevant information from the OS,
instead of spawning a "dir" process. I have no idea how to do that and it
will probably require the win32 extensions for Python.

After that, you're done. Odds are you'll be disk bound. In fact, you may
get no gain if Windows is optimized enough that the process you describe
below is *still* disk-bound.

Your only hope then is two things:

* Poke around in the Windows API for a function that does what you want,
and hope it can do it faster due to being in the kernel.

* Somehow work this out to be lazy so it tries to grab what the user is
looking at, instead of absolutely everything. Whether or not this will
work depends on your application. If you post more information about how
you are using this data, I can try to help you. (I've had some experience
in this domain, but what is good heavily depends on what you are doing.
For instance, if you're batch processing a whole bunch of records after
the user gave a bulk command, there's not much you can do. But if they're
looking at something in a Windows Explorer-like tree view, there's a lot
you can do to improve responsiveness, even if you can't speed up the
process overall.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pseudocode in the wikipedia

2005-04-01 Thread Jeremy Bowers
On Fri, 01 Apr 2005 16:02:53 -0500, Gabriel Cooper wrote:
> Ron_Adam wrote:
> 
>>To me ":=" could mean to create a copy of an object...  or should it
>>be "=:" ?
>>
>>Or how about ":=)" to mean is equal and ":=(" to mean it's not.
>>
>>Then there is ";=)", to indicate 'True', and ':=O' to indicate 'False'
>>  
>>
> Not to mention "(_ | _)" for asserts!

Your ass is your identity function.

Python 2.3.5 (#1, Mar  3 2005, 17:32:12) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 25
25
>>> (_ | _)
25
>>> 

There's clearly some interesting biometrics research to be done here,
although there is a well-known ass-capturing attack based on readily
commercially available machines from Xerox that might make it hard to make
an ass-based identity system resistant to attacks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try / except not worknig correctly

2005-04-01 Thread Jeremy Bowers
On Sat, 12 Mar 2005 17:06:17 -0800,
'@'.join([..join(['fred','dixon']),..join(['gmail','com'])]) wrote:

I'd also suggest

validInput = "ABCDEFGHIJKL" # and there are more clever ways to do this,
# but this will do

myInput = raw_input(" ".join(validInput) + "?")
if len(myInput) != 1:
# do whatever
pass
if myInput not in validInput:
raise ValueError("Input not in legal input: " + validInput)


Obviously not a drop-in replacement for your code, but ought to clean it
up a little. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorater inside a function? Is there a way?

2005-04-01 Thread Jeremy Bowers
On Fri, 01 Apr 2005 19:56:55 +, Ron_Adam wrote:

> On Fri, 01 Apr 2005 13:47:06 -0500, Jeremy Bowers <[EMAIL PROTECTED]>
> wrote:
>>Is this an April Fools gag? If so, it's not a very good one as it's quite
>>in line with the sort of question I've seen many times before. "I have
>>a hammer, how do I use it to inflate my tire?"
> 
> Not an April fools gag, I'm just new to decorators and google brings
> up lots of discussions from the past on how they may be implemented in
> the future, but not much in actually how they work or how to use them.

OK, just checking :-)

A decorator is completely equivalent in principle to

def function():
pass
function = decorator(function)

That's a simplified form; decorators can themselves be an expression which
returns a callable that can be applied to a function and the rule for
applying several in sequence work as you'd expect (pipelining earlier
results into later ones, making for a great Obfuscated Python entry or
two based on the "function name misdirection" trick), but this simplified
form captures the essense, which is what I think you're looking for. In
particular, it's just "syntax sugar", not a "special feature".

> I'm trying to understand the use's, limits, and possibilities of
> decorators.
> 
> It just occurred to me that wrapping the contents of a function vs
> wrapping the function it's self, could be useful.

Decorators, literally, can only wrap functions. You can write a wrapper
then that does something to the arguments, which people sometimes do, but
you can't directly "wrap" the arguments. 

Note, having shown you how decorators work, you can "manually" apply the
decorator yourself:

Python 2.3.5 (#1, Mar  3 2005, 17:32:12) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import string
>>> string._join = string.join
>>> def joinWrap(*args, **kwargs):
... print args, kwargs
... return "My Wrapper", string._join(*args, **kwargs)
... 
>>> string.join = joinWrap
>>> string.join(["1","2","3"], "|")
My Wrapper (['1', '2', '3'], '|') {}
'1|2|3'
>>> 

So, whatever it is you are trying can do can still be done without the
decorator syntax, and *this* is not unheard of, though managing the
references correctly can be tricky the first few times if you're not used
to it. (Note the replaced function (join in this example) can go anywhere
the wrapper can get at it, I just stick it back in the original module for
simplicity.) It's not the first thing I reach for, in fact in all my
testing code I don't think I ever do this, but it is in the toolbox.

Do this instead of abusing the decorator syntax; you could write a
decorator that tries to figure out if it's being run in a testing
environment and conditionally affects the function, but that's probably a
bad idea.

Feeling-like-I-owed-you-an-answer-after-the-april-fool-accusation-ly yrs,
Jeremy Bowers
:-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator in Python

2005-04-01 Thread Carl Banks

Terry Reedy wrote:
> "praba kar" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Dear All,
> >I am new to Python.  I want to know how to
> > work with ternary operator in Python.  I cannot
> > find any ternary operator in Python.  So Kindly
> > clear my doubt regarding this
>
> A unary operator has one operand; a binary operator has two operands;
a
> ternary operator has three operands.  Python has none built-in,

Not so fast, my friend.  What about the expression "0.0 < a < 1.0"?


-- 
CARL BANKS

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


Re: redundant importr

2005-04-01 Thread Peter Hansen
max(01)* wrote:
Peter Hansen wrote:
Not required except for performance reasons.  If the .pyc
files don't exist, the .py files are recompiled and the
resulting bytecode is simply held in memory and not cached
and the next startup will recompile all over again.
but the other files *are* compiled, right? 
Yes, definitely.  I did say that.
so the initial question remains unanswered: 
No it doesn't.  I thought I was clear, but I can reword
it for you: the files are compiled *in-memory* and the
results are never written to disk.
> *if* they are compiled, where are they put, if the
corresponding *.py files are on a non-writeable directory?
They are not put anywhere.  Compilation is a process
by which the source is converted to executable bytecodes.
This says nothing about where either the source or the
compiled result resides.  The actual compilation works
on a long series of bytes in memory, and the result is
just another long series of bytes.  Nothing requires that
either of these things are even stored in a file.
Not sure what else I could say to make it clearer...
(I'm not misunderstanding you am I?  I get the feeling
we're not quite on the same page here.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: numeric module

2005-04-01 Thread David M. Cooke
"coffeebug" <[EMAIL PROTECTED]> writes:

> I cannot import "numarray" and I cannot import "numeric" using python
> 2.3.3

numarray and Numeric are separate modules available at 
http://numpy.sourceforge.net/

If you're doing anything numerical in Python, you'll want them :-)

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numeric module

2005-04-01 Thread David M. Cooke
[EMAIL PROTECTED] writes:

> Hello,
> What's the problem with this code? I get the following error message:
>
>  File "test.py", line 26, in test
> print tbl[wi][bi]
> IndexError: index must be either an int or a sequence
>
> ---code snippet
>
> from Numeric import *
> tbl = zeros((32, 16))
>
> def test():
>
> val = testme()
> wi = val >> 4
> bi = val & 0xFL
[above changed to use val instead of crc, as you mentioned in another post]
> print wi
> print bi
> print tbl[wi][bi]

tbl[wi][bi] would be indexing the bi'th element of whatever tbl[wi]
returns. For Numeric arrays, you need

tbl[wi,bi]

Now, you'll have another problem as Terry Reedy mentioned: the indices
(in Numeric) need to be Python ints, not longs. You could rewrite your
test() function as

def test():
val = testme()
wi = int(val >> 4)
bi = int(val & 0xF)
print wi
print bi
print tbl[wi,bi]

and that'll work.

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Who said that? (was Re: string goes away)

2005-04-01 Thread Peter Hansen
Ivan Van Laningham wrote:
Tim Peters sayeth, "Premature Optimization is the Root of All Evil." 
And he is not kidding.
And just to forestall another long thread about who
actually said that originally, it was really Mark
Twain, quoting Churchill.  Tim just added a .
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator in Python

2005-04-01 Thread Erik Max Francis
Ron_Adam wrote:
I've used boolean opperations to do it.
result = (v == value) * first + (v != value) * second
Same as:
	if v == value: result = first else: result = second
No, it isn't, because it isn't short circuiting.  If first or second had 
side effects, then the two would not be equivalent.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  If the sun comes up / And you're not home / I'll be strong
  -- India Arie
--
http://mail.python.org/mailman/listinfo/python-list


Re: StopIteration in the if clause of a generator expression

2005-04-01 Thread Bengt Richter
On Fri, 01 Apr 2005 16:34:32 GMT, "Raymond Hettinger" <[EMAIL PROTECTED]> wrote:

>[Peter Otten]
>> a StopIteration raised in a generator expression
>> silently terminates that generator:
>>
>> >>> def stop(): raise StopIteration
>> ...
>> >>> list(i for i in range(10) if i < 5 or stop())
>> [0, 1, 2, 3, 4]
>>
>> In a list comprehension, on the other hand, it is propagated:
>>
>> >>> [i for i in range(10) if i < 5 or stop()]
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>>   File "", line 1, in stop
>> StopIteration
>>
>> Is that an intentional difference?
>
>I would call it an unfortunate assymmetry -- one the never comes up unless
>you're up to no good ;-)
;-)
>
>In a way, both behave identically.  They both raise StopIteration.  In the case
>of the generator expression, that StopIteration is intercepted by the enclosing
>list() call.  That becomes obvious if you write a pure python equivalent for
>list:
>
>def lyst(s):
>it = iter(s)
>result = []
>try:
>while 1:
>result.append(it.next())
>except StopIteration:# guess who trapped StopIter
>return result
>
>
I assumed that all standard sequence consumers (including list, of course) 
would intercept
the StopIteration of a sequence given them in the form of a generator 
expression, so your
lyst example would have an analogue for other sequence consumers as well, right?
I.e., there's not a hidden list(genex) in those others I would hope ;-)

E.g., "in" in my toy exposed more clearly, using Peter's stop:

 >>> def show(x): print x,; return x
 ...
 >>> def stop(): raise StopIteration
 ...
 >>> 2 in (x for x in xrange(5) if show(x)<4 or stop())
 0 1 2
 True
 >>> 7 in (x for x in xrange(5) if show(x)<4 or stop())
 0 1 2 3 4
 False

BTW I notice that this also nicely shortcuts when the 2 is found.

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


Re: Attributes and built-in types

2005-04-01 Thread Sidharth
You might find this usefull specifically the stuff on subclassing
built-in types.
http://www.python.org/2.2/descrintro.html

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


Re: Pseudocode in the wikipedia

2005-04-01 Thread Gabriel Cooper

Ron_Adam wrote:
To me ":=" could mean to create a copy of an object...  or should it
be "=:" ?
Or how about ":=)" to mean is equal and ":=(" to mean it's not.
Then there is ";=)", to indicate 'True', and ':=O' to indicate 'False'
 

Not to mention "(_ | _)" for asserts!
--
http://mail.python.org/mailman/listinfo/python-list


Attributes and built-in types

2005-04-01 Thread Dave Opstad
Is it just an implementation limitation that attributes cannot be 
assigned to instances of internal types?

---
>>> x = 4
>>> type(x)

>>> class Test(int):
...   pass
... 
>>> y = Test(4)
>>> type(y)

>>> y.someattr = 10
>>> x.someattr = 10
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'int' object has no attribute 'someattr'
---

When I did a dir(int) there was no __dict__ entry, but a dir(Test) 
showed a __dict__entry, which is why (presumably) the attribute 
assignment worked for Test but not for int.

Just curious...

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


Re: how to close a gzip.GzipFile?

2005-04-01 Thread Sidharth
GzipFile has a parameter 'fileobj' which you could use.
GzipFile( [filename[, mode[, compresslevel[, fileobj)

For iteratng over the file
how about :
line =  oldfileobj.readline()
while line !="":
   oldmd5.update(line)
   line = oldfileobj.readline()

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


Re: Pseudocode in the wikipedia

2005-04-01 Thread Ron_Adam
On Fri, 1 Apr 2005 12:15:35 -0800, James Stroud <[EMAIL PROTECTED]>
wrote:

>Is anybody else bothered by those stupid pascal-like ":=" assignment 
>operators?
>
>Maybe, for the sake of adding more variety to the world, wiki should come up 
>with a new assignment operator, like "==". I like that one because then it 
>could really be original:
>
>if (bob = 4):
>  bob == bob + 2

To me ":=" could mean to create a copy of an object...  or should it
be "=:" ?

Or how about ":=)" to mean is equal and ":=(" to mean it's not.

Then there is ";=)", to indicate 'True', and ':=O' to indicate 'False'


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


  1   2   3   >