iterator clone

2008-07-12 Thread Yosifov Pavel
Whats is the way to clone "independent" iterator? I can't use tee(),
because I don't know how many "independent" iterators I need. copy and
deepcopy doesn't work...

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


Re: Weird lambda rebinding/reassignment without me doing it

2008-07-12 Thread Steven D'Aprano
On Sat, 12 Jul 2008 16:32:25 -0400, Terry Reedy wrote:

> Steven D'Aprano wrote:
>> On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote:
>> 
 g = lambda x:validate(x)
>>> This is doubly diseased.
>>>
>>> First, never write a 'name = lambda...' statement since it is
>>> equivalent to a def statement except that the resulting function
>>> object lacks a proper .funcname attribute.
>> 
>> Using lambda in this way is no more "diseased" than aliasing any other
>> object.
> 
> In the context of giving advice to a confused beginner, I disagree. He
> must learn def statements.  Lambda expressions are optional.

Lots of things are optional. sets and frozen sets and decorators and 
classes and all sorts of things are optional, *and* capable of being 
misused and/or abused. Would you describe properties as "diseased" 
because some people might fill their classes with useless getters and 
setters?


>  > It's a matter of personal preference not to bind a lambda to a
>> name. Functions, whether created by lambda or def, are first class
>> objects, and as such there's nothing wrong with binding them to names.
> 
> When I brought this up on pydev, in the context of a style guide
> addition, about 9 of 10 respondants agreed that this should be
> discouraged.  Alex Martelli reported his experience that this
> construction more often leads people to the useless wrapping of function
> calls, such as the OP posted, than the def statement equivalent does.

I have great respect for Alex, but anecdotes of that nature aren't proof. 
Such anecdotal evidence is subject to confirmation bias. I'm sure that 
Alex remembers the stupid pieces of code where people make such mistakes 
but I doubt very much he remembers the cases where they don't.

But as a style guide... fine. Tell people it is discouraged. Tell them 
that other Python developers will laugh at them if they do it, apart from 
the ten percent who don't mind named lambdas. Point out that, like 
factory functions, there's a debugging cost to having functions with a 
unhelpful func_name attribute.

But don't cross that line from discouragement to telling people that it 
is wrong to use named lambdas. That's what I object to.

 
> One of the major reasons people give for wanting lambda expressions kept
> in Python and for using them is that they do not want to have to think
> up a name for short expressions.  If such a person then turns around and
>   binds the resulting function object to a name, then that rationale
> disappears.

That does not follow. The fact that I might choose to occasionally bind a 
lambda to a name doesn't mean I never use unbound functions. Your 
argument is like saying that the rationale for air conditioners ("cooling 
in the hot weather") disappears because we can also use reverse-cycle air 
conditioners for heating in the cold weather.

Lambdas are *necessary* if you want anonymous functions, just as we have 
anonymous strings, anonymous integers and so forth. It would be a poor 
language that forced people to write this:

x = 1
s = 'two'
def f(arg):
return arg+3

mylist = [x, s, f]

instead of the more sensible:

mylist = [1, 'two', lambda arg: arg+3]


That's why we need lambda. But once we have lambda, there is absolutely 
no reason why we must prohibit other uses of it. Given the above 
definition of mylist, would you then describe the following piece of code 
as "diseased"?

def foo(mylist):
g = mylist[2]
for i in xrange(1):
print g(i)

That's a perfectly good micro-optimization technique, and I would hope 
you would not reject it merely because the function was anonymous. That 
would be irrational.

I'm not defending the Original Poster's use of lambda in that specific 
piece of code. You are right to criticize it *specifically*. What I 
object to is that you generalize that criticism, and treat a personal 
preference as an absolute rule. By all means think my code is ugly for 
using named lambdas, and by all means tell me you think it is ugly, but 
don't tell me I'm corrupting the youth of today with my filthy disease-
ridden code.


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


Re: spam <...googlegroups.com> <...googlegroups.com>

2008-07-12 Thread JeffM
>WDC wrote:
>>BTW I reported it, yo should too.
>>
Lew wrote:
>To whom did you report it, so that we may also report it there?

Reports made to Google Groups are a complete waste of time.
Google will only cancel *that* account (without blocking the IP
address).
It takes the spammer 30 seconds to enable *another* account.
That is, ZERO real effect.
It should also be noted that each time this is done
plonk files could grow by one item.

For Blogspot/Googlepages spam, report those to
mailto:[EMAIL PROTECTED]adsense-abuse@ google.com
That puts his site into Google Hell (screws up his GoogleRank).

The most effective effort you can make
is to do a reverse-DNS on the NNTP-Posting-Host
http://private.dnsstuff.com/tools/whois.ch?ip=122.164.105.235&email=on
and report abusers to their providers.
This assumes their ISPs aren't complete rogues.
--
http://mail.python.org/mailman/listinfo/python-list


Re: filtering keyword arguments

2008-07-12 Thread bukzor
On Jul 12, 8:44 pm, Amir <[EMAIL PROTECTED]> wrote:
> How do you filter keyword arguments before passing them to a function?
>
> For example:
>
> def f(x=1): return x
>
> def g(a, **kwargs): print a, f(**kwargs)
>
> In [5]: g(1, x=3)
> 1 3
>
> In [6]: g(1, x=3, y=4)
> TypeError: f() got an unexpected keyword argument 'y'
>
> Is there a way to do something like:
>
> def g(a, **kwargs): print a, f(filter_rules(f, **kwargs))
>
> so only {'x': 3} is passed to f?
>
> I was hoping for a pythonic way of doing what in Mathematica is done
> by FilterRules:
>
> http://reference.wolfram.com/mathematica/ref/FilterRules.html

Here it is as a decorator:


def filter_arguments(func):
def func2(*args, **kwargs):
import inspect
arglist, vararg, kwarg, defaults = inspect.getargspec(func)
for k in kwargs.copy():
if k not in arglist: del kwargs[k]
return func(*args, **kwargs)
return func2


@filter_arguments
def func(a=1, b=2): return a+b


print func()
print func(c=3)
print func(a=3,b=4)
--
http://mail.python.org/mailman/listinfo/python-list


Re: filtering keyword arguments

2008-07-12 Thread Peter Otten
Amir wrote:

> How do you filter keyword arguments before passing them to a function?
> 
> For example:
> 
> def f(x=1): return x
> 
> def g(a, **kwargs): print a, f(**kwargs)
> 
> In [5]: g(1, x=3)
> 1 3
> 
> In [6]: g(1, x=3, y=4)
> TypeError: f() got an unexpected keyword argument 'y'
> 
> Is there a way to do something like:
> 
> def g(a, **kwargs): print a, f(filter_rules(f, **kwargs))
> 
> so only {'x': 3} is passed to f?

I think you have to come up with something yourself. Here's a start:

import inspect

def filter_kw(f, **kw):
names = inspect.getargspec(f)[0]
return dict((n, kw[n]) for n in names if n in kw)

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


Re: filtering keyword arguments

2008-07-12 Thread [EMAIL PROTECTED]
On Jul 12, 10:44 pm, Amir <[EMAIL PROTECTED]> wrote:
> How do you filter keyword arguments before passing them to a function?
>
> For example:
>
> def f(x=1): return x
>
> def g(a, **kwargs): print a, f(**kwargs)
>
> In [5]: g(1, x=3)
> 1 3
>
> In [6]: g(1, x=3, y=4)
> TypeError: f() got an unexpected keyword argument 'y'
>
> Is there a way to do something like:
>
> def g(a, **kwargs): print a, f(filter_rules(f, **kwargs))
>
> so only {'x': 3} is passed to f?
>
> I was hoping for a pythonic way of doing what in Mathematica is done
> by FilterRules:
>
> http://reference.wolfram.com/mathematica/ref/FilterRules.html

Sure, you could do:

def call_with_relevant_args(func, kwargs):
kwargs = dict([(k, v) for k, v in kwargs.iteritems() if k in
func.func_code.co_varnames])
return func(**kwargs)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determining when a file has finished copying

2008-07-12 Thread Larry Bates

Sean DiZazzo wrote:

On Jul 9, 5:34 pm, keith <[EMAIL PROTECTED]> wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1



Ethan Furman wrote:

writeson wrote:

Guys,
Thanks for your replies, they are helpful. I should have included in
my initial question that I don't have as much control over the program
that writes (pgm-W) as I'd like. Otherwise, the write to a different
filename and then rename solution would work great. There's no way to
tell from the os.stat() methods to tell when the file is finished
being copied? I ran some test programs, one of which continously
copies big files from one directory to another, and another that
continously does a glob.glob("*.pdf") on those files and looks at the
st_atime and st_mtime parts of the return value of os.stat(filename).

From that experiment it looks like st_atime and st_mtime equal each

other until the file has finished being copied. Nothing in the
documentation about st_atime or st_mtime leads me to think this is
true, it's just my observations about the two test programs I've
described.
Any thoughts? Thanks!
Doug

The solution my team has used is to monitor the file size.  If the file
has stopped growing for x amount of time (we use 45 seconds) the file is
done copying.  Not elegant, but it works.
--
Ethan

Also I think that matching the md5sums may work.  Just set up so that it
checks the copy's md5sum every couple of seconds (or whatever time
interval you want) and matches against the original's.  When they match
copying's done. I haven't actually tried this but think it may work.
Any more experienced programmers out there let me know if this is
unworkable please.
K
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org

iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM
qTFBfyIEGhu/dNSQzeRrwYQ=
=Xvjq
-END PGP SIGNATURE-


I use a combination of both the os.stat() on filesize, and md5.
Checking md5s works, but it can take a long time on big files.  To fix
that, I wrote a simple  sparse md5 sum generator.  It takes a small
number bytes from various areas of the file, and creates an md5 by
combining all the sections. This is, in fact, the only solution I have
come up with for watching a folder for windows copys.

The filesize solution doesn't work when a user copies into the watch
folder using drag and drop on Windows because it allocates all the
attributes of the file before any data is written.  The filesize will
always show the full size of the file.

~Sean


While a lot depends on HOW the copying program does its copy, I've recently been 
able to get pyinotify to watch folders.  By watching for IN_CLOSE_WRITE events I 
can see when files are closed by the writer and then process them instantly 
after they have been written.  Now if the writer does something like:


open
write
close
open append
write
close
.
.
.

This won't work as well.

FYI,
Larry
--
http://mail.python.org/mailman/listinfo/python-list


Re: spam <[EMAIL PROTECTED]> <[EMAIL PROTECTED]>

2008-07-12 Thread Lew

WDC wrote:

BTW I reported it, yo should too.


To whom did you report it, so that we may also report it there?

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


filtering keyword arguments

2008-07-12 Thread Amir
How do you filter keyword arguments before passing them to a function?

For example:

def f(x=1): return x

def g(a, **kwargs): print a, f(**kwargs)

In [5]: g(1, x=3)
1 3

In [6]: g(1, x=3, y=4)
TypeError: f() got an unexpected keyword argument 'y'

Is there a way to do something like:

def g(a, **kwargs): print a, f(filter_rules(f, **kwargs))

so only {'x': 3} is passed to f?

I was hoping for a pythonic way of doing what in Mathematica is done
by FilterRules:

http://reference.wolfram.com/mathematica/ref/FilterRules.html

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


socket.connect() hangs in SYN_SENT state.

2008-07-12 Thread bukzor
I'm having an issue where my program hangs while doing
socket.connect() for a couple minutes, then times out the connection
and crashes. I'm connecting to an apache2 process on the same machine,
for testing. When looking at netstat, the socket is in the SYN_SENT
state, like this:

$netstat -a -tcp
tcp0  0 *:www   *:*
LISTEN  7635/apache2
tcp0  1 bukzor:38234adsl-75-61-84-249.d:www
SYN_SENT9139/python

Anyone know a general reason this might happen? Even better, a way to
fix it?


Doing a minimal amount of research, I found this in the netstat
manual:
The state SYN_SENT means that an application has made arequest for a
TCP session, but has not yet received the return SYN+ACK packet.

This would indicate it's a server issue, but it seems very stable when
I look at it via a browser.


Here's the server. If you browse to it, it documents the exported
functions:
http://bukzor.hopto.org/modpython/xmlrpc.py

Here's my test client that's hanging. Turn 'verbose' to True to get
more debugging info.

[code]
#!/usr/bin/env python
from xmlrpclib import ServerProxy

s = ServerProxy("http://bukzor.hopto.org/modpython/xmlrpc.py";,
verbose=False)

print s.helloworld()
print s.add(1,2)
print s.subtract(1,2)
[/code]


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


Re: How to create a timer/scheduler in Python?

2008-07-12 Thread MrJean1
There is a module called sched in the standard Python library

  

/Jean Brouwers



John Dann wrote:
> I need what I'd call (in .Net) a timer, ie I need to run a function eg
> every 2 seconds - it doesn't need to be millisec accurate but it would
> be nice if it wasn't eg every 4 seconds or something.
>
> Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer'
> or 'scheduler', which leaves me wondering whether this is an aspect of
> Python that isn't perhaps widely used?
>
> Looking around on the net I can see references to a thread timer, but
> I'm not really looking to start any new threads (I just want part of
> the GUI to update every 2 secs) and don't want to get into that sort
> of complication while still just learning Python.
>
> Is there really no simple timer/scheduler function available in
> Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Someone enlightened me

2008-07-12 Thread bukzor
On Jul 12, 7:08 pm, Marcus Low <[EMAIL PROTECTED]> wrote:
> Can someone explain to me, why the behaviour below is different when u
> remark "lister" and unremark "self.lister"?
>
> #--
> class abc :
> # remark this later and unremark "self.lister"
> lister = []
>
> def __init__ (self, val):
> #self.lister = []
> self.lister.append(val)
>
> #--
> globallist = []
> #--
> def test () :
> global l
> for x in range(10) :
> o = abc(x)
> globallist.append(o)
> o = ""
>
> for i in globallist :
> print i.lister
>
> #--
> test()
> #--

The way it's written, you're appending to a list associated with the
class itself, which is created only once, then printing out that list
10 times. After you uncomment and comment the specified lines (this is
the usual term, rather than "remark"), you are using a list that is
associated with the actual object, then printing out the 10 different
lists.

Hope that's clear enough.
--Buck
--
http://mail.python.org/mailman/listinfo/python-list


New TTF fonts in IDLE on Linux question

2008-07-12 Thread [EMAIL PROTECTED]
So I'm using this Akbar font, a truetype, related to Simpsons, for
coding in Python, just for kicks (looks pretty good actually).

No prob on Windows, but when I sudo cp akbar.ttf to /usr/share/fonts/
truetype/ttf-misc, a directory I made myself (root root), then
OpenOffice and WingWare find it right away, but IDLEs in Python 2.5
and 3.0 don't seem to see it.  Is there some special place IDLE looks
for fonts that I'm missing?

http://worldgame.blogspot.com/2008/07/idle-language-games.html
http://www.flickr.com/photos/[EMAIL PROTECTED]/2662994560/

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


Re: Why is there no GUI-tools like this for Windows?

2008-07-12 Thread Marcus.CM

Hi,

Coming from a windows world i could understand this. For GUI, there is 
nothing near the power of the Visual Studio, this is especially true 
since C#.
So python for me is for anything except GUI. It becomes self rejecting 
notion to do GUI in python when you type in those stuff that could have 
been handled by an IDE,
thus for linux project i just do the web interface + php and let python 
do all the other hard core work.


But looking at the video, i think if they could do this for ruby, then 
the python community should be able to come out with a similar one. 
There is something called BOA i read somewhere but its having

some kind of compatibility problem with newer versions of wxpyhon.

(;-) i didnt really manage to see that video it took forever to load, 
but the comments gave enuf hints).


Marcus.

maestro wrote:

http://www.youtube.com/watch?v=PXpwC1o5AcI

I have done some GUI-programming for windows with Python but the
Tkinter interface sucked and while it is the only one I tried I got
the impression they are all the same.

It's amazing how retarded a lot of the stuff programmers do is.
Watcing that video, that is how it should be.

I can just do the layout with my mouse and then there is a program
that writes the code for me.
GUI-programming is hard for no reason. One good program then forever
easy...

Is there not something like this for Python/Windows? Is the Linux one
only for ruby or for any language?

Oh well im switching to Linux anyway and mostly write webapps but
still...
--
http://mail.python.org/mailman/listinfo/python-list

  



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


Re: Correct use of try,except and raise?

2008-07-12 Thread Ben Finney
ssecorp <[EMAIL PROTECTED]> writes:

> Is this correct use of exceptions? to raise an indexerror and add my
> own string insetad of just letting it raise a IndexError by itself
> and "blaming" it on list.pop?
> 
> class Stack(object):
> def __init__(self, *items):
> self.stack = list(items)

If you are passing a sequence conceptually, then it's more Pythonic to
pass it as a sequence explicitly::

def __init__(self, items):
""" Call with e.g. Stack(["foo", "bar"]) """
self.stack = list(items)

> def pop(self):
> try:
> return self.stack.pop()
> except:
> raise IndexError, "pop from empty stack"

Don't use this form of 'raise', it's deprecated. Instead, create the
exception instance with the arguments::

raise IndexError("pop from empty stack")

Don't use a bare 'except'; you will thereby catch *all* exceptions in
the 'try' block, masking errors you did not expect to handle, making
debugging unnecessarily difficult. Instead, always be explicit about
*which* exceptions you're handling here.

Don't catch the exception only to raise a new one; the context of the
original exception is lost. If all you want to do is have a different
message, modify the existing exception instance's args and re-raise
it.

try:
return self.stack.pop()
except IndexError, exc:
exc.args = ["pop from empty stack"]
raise

-- 
 \ “Experience is that marvelous thing that enables you to |
  `\   recognize a mistake when you make it again.” —Franklin P. Jones |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Someone enlightened me

2008-07-12 Thread Marcus Low
Can someone explain to me, why the behaviour below is different when u 
remark "lister" and unremark "self.lister"?


#--
class abc :
   # remark this later and unremark "self.lister"
   lister = []

   def __init__ (self, val):
   #self.lister = []
   self.lister.append(val)   


#--
globallist = []
#--
def test () :

   global l
   for x in range(10) :
   o = abc(x)
   globallist.append(o)   
   o = ""
 
   for i in globallist :
   print i.lister  


#--
test()
#--



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


Someone enlightened me

2008-07-12 Thread Marcus Low
Opps here is the mail again, incase my formatting is lost, can someone 
explain to me why this code behaves differently when "lister" and 
"self.lister" is swap remarked.



class abc :
   # remark this later and unremark "self.lister"
   lister = []
   def __init__ (self, val):
   #self.lister = []
   self.lister.append(val)  


globallist = []
  


def test () :

   global l
   for x in range(10) :
   o = abc(x)   
   globallist.append(o)  
   o = ""
  
   for i in globallist :
   print i.lister 

test()   



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


Re: Someone enlightened me

2008-07-12 Thread Marcus Low

Duh,

Ok here is the file again ...attached. I give up doing this via the 
email editor. Sorry! new to the mailing list.


Marcus

Marcus Low wrote:
Opps here is the mail again, incase my formatting is lost, can someone 
explain to me why this code behaves differently when "lister" and 
"self.lister" is swap remarked.



class abc :
   # remark this later and unremark "self.lister"
   lister = []
   def __init__ (self, val):
   #self.lister = []
   self.lister.append(val) 
globallist = []
 
def test () :


   global l
   for x in range(10) :
   o = abc(x)  globallist.append(o) o 
= ""

 for i in globallist :
   print i.lister
test()  



class abc :
# remark this later and unremark "self.lister"
lister = []
def __init__ (self, val):
#self.lister = []
self.lister.append(val)   

globallist = []

def test () :
global l
for x in range(10) :
o = abc(x)
globallist.append(o)   
o = ""

for i in globallist :
print i.lister  

test()
--
http://mail.python.org/mailman/listinfo/python-list

Re: palindrome function

2008-07-12 Thread Terry Reedy



Mensanator wrote:


It hasn't. and here's why:

IDLE 2.6b1

seq=['a','n','n','a']
seq.reversed()


Traceback (most recent call last):
  File "", line 1, in 
seq.reversed()
AttributeError: 'list' object has no attribute 'reversed'


My apologies.  reversed() is a builtin func, not a method, and it 
produces an iterator, not a seq.  SO, corrected,


>>> for s in ((1,2,3,2,1), [1,2,3,2,1]):
...   type(s)(reversed(s)) == s
...
True
True
>>> s = '12121'
>>> ''.join(reversed(s)) == s
True

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


Re: Correct use of try,except and raise?

2008-07-12 Thread Roy Smith
ssecorp <[EMAIL PROTECTED]> wrote:

> i dont get what you mean, if i dont do anything python will raise an
> indexerror so it is an indexerror.

You wrote:

> > >     def pop(self):
> > >         try:
> > >             return self.queue.pop(0)
> > >         except:
> > >             raise IndexError, "pop from empty queue"

You are assuming that the only possible exception that can be thrown by 
"return self.queue.pop(0)" is IndexError.  Maybe, maybe not.  I gave you 
one example of how something else could be thrown -- a typo in your code 
leading to a NameError.  Maybe even something more exotic like MemoryError?

The defensive thing to do is catch exactly the exception you expect to 
happen.  In this case, that means IndexError.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Correct use of try,except and raise?

2008-07-12 Thread ssecorp
On Jul 13, 2:32 am, Roy Smith <[EMAIL PROTECTED]> wrote:
> In article
> <[EMAIL PROTECTED]>,
>
>
>
>  ssecorp <[EMAIL PROTECTED]> wrote:
> > Is this correct use of exceptions? to raise an indexerror and add my
> > own string insetad of just letting it raise a IndexError by itself and
> > "blaming" it on list.pop?
>
> > class Stack(object):
> >     def __init__(self, *items):
> >         self.stack = list(items)
>
> >     def push(self, item):
> >         self.stack.append(item)
>
> >     def pop(self):
> >         try:
> >             return self.stack.pop()
> >         except:
> >             raise IndexError, "pop from empty stack"
>
> > class Queue(object):
> >     def __init__(self, *items):
> >         self.queue = list(items)
>
> >     def append(self, item):
> >         self.queue.append(item)
>
> >     def pop(self):
> >         try:
> >             return self.queue.pop(0)
> >         except:
> >             raise IndexError, "pop from empty queue"
>
> I think you would do better defining a new exception, PopError, or
> something like that.  Then you can write code which specifically catches
> that and do something with it.
>
> It's also not a good idea to catch all exceptions.  Catch the most specific
> thing you can.  Consider something like:
>
> try:
>     kew.pop(0)
> except:
>    raise IndexError, "pop from empty kew"
>
> When I run it, it prints, "IndexError: pop from empty kew".  The problem
> is, the *real* error is "NameError: name 'kew' is not defined".  By
> catching all exceptions, I've masked a programming error by turning the
> NameError into an IndexError.



i dont get what you mean, if i dont do anything python will raise an
indexerror so it is an indexerror.
--
http://mail.python.org/mailman/listinfo/python-list


Problems with curses

2008-07-12 Thread Clay Hobbs
I am making a text-based game similar to Zork with Python.  I have
decided to use the curses module, and have run into a problem.  I want
to scroll the commands and output up after a command is run instead of
clearing the screen.  But when I use std.scroll(), an exception is
raised.  Here is the program:

#!/usr/bin/env python
# text_adventure.py

import curses
import curses.wrapper

def main(stdscr):
curses.echo()
stdscr.setscrreg(1, 24)
score = 0
moves = 0
statusbar = stdscr.subwin(2, 80, 0, 0)
statusbar.addstr(0, 0, 'Dingo'+' '*(58-len('Dingo'))+'Score: %03d
Moves: %03d'%(score, moves), curses.A_REVERSE)
stdscr.addstr(24, 0, '> ')
x = stdscr.getstr(24, 2)
x = str(x)
stdscr.refresh()
#stdscr.erase()
stdscr.scroll(3)
statusbar.erase()
statusbar.addstr(0, 0, x+' '*(58-len(x))+'Score: %03d  Moves: %
03d'%(score, moves), curses.A_REVERSE)
stdscr.addstr(24, 0, '> ')
stdscr.getstr(24, 2)

curses.wrapper(main)

Unfortunately, the error message isn't very helpful.  I'm just hoping
somebody out there knows curses and has the answer.

-- Ratfink


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


Re: Correct use of try,except and raise?

2008-07-12 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 ssecorp <[EMAIL PROTECTED]> wrote:

> Is this correct use of exceptions? to raise an indexerror and add my
> own string insetad of just letting it raise a IndexError by itself and
> "blaming" it on list.pop?
> 
> class Stack(object):
> def __init__(self, *items):
> self.stack = list(items)
> 
> def push(self, item):
> self.stack.append(item)
> 
> def pop(self):
> try:
> return self.stack.pop()
> except:
> raise IndexError, "pop from empty stack"
> 
> class Queue(object):
> def __init__(self, *items):
> self.queue = list(items)
> 
> def append(self, item):
> self.queue.append(item)
> 
> def pop(self):
> try:
> return self.queue.pop(0)
> except:
> raise IndexError, "pop from empty queue"

I think you would do better defining a new exception, PopError, or 
something like that.  Then you can write code which specifically catches 
that and do something with it.

It's also not a good idea to catch all exceptions.  Catch the most specific 
thing you can.  Consider something like:

try:
kew.pop(0)
except:
   raise IndexError, "pop from empty kew"

When I run it, it prints, "IndexError: pop from empty kew".  The problem 
is, the *real* error is "NameError: name 'kew' is not defined".  By 
catching all exceptions, I've masked a programming error by turning the 
NameError into an IndexError.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-12 Thread Terry Reedy



[EMAIL PROTECTED] wrote:

Hi group,

I have a basic question on the zip built in function.

I am writing a simple text file comparison script, that compares line
by line and character by character. The output is the original file,
with an X in place of any characters that are different.

I have managed a solution for a fixed (3) number of files, but I want
a solution of any number of input files.

The outline of my solution:

for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
res = ''
for entry in zip(vec[0],vec[1],vec[2]):
if len(set(entry)) > 1:
res = res+'X'
else:
res = res+entry[0]
outfile.write(res)

So vec is a tuple containing a line from each file, and then entry is
a tuple containg a character from each line.

2 questions
1) What is the general solution. Using zip in this way looks wrong. Is
there another function that does what I want


zip(*vec_list) will zip together all entries in vec_list
Do be aware that zip stops on the shortest iterable.  So if vec[1] is 
shorter than vec[0] and matches otherwise, your output line will be 
truncated.  Or if vec[1] is longer and vec[0] matches as far as it goes, 
there will be no signal either.


res=rex+whatever can be written as res+=whatever


2) I am using set to remove any repeated characters. Is there a
"better" way ?


I might have written a third loop to compare vec[0] to vec[1]..., but 
your set solution is easier and prettier.


If speed is an issue, don't rebuild the output line char by char.  Just 
change what is needed in a mutable copy.  I like this better anyway.


res = list(vec[0]) # if all ascii, in 3.0 use bytearray
for n, entry in enumerate(zip(vec[0],vec[1],vec[2])):
  if len(set(entry)) > 1:
  res[n] = 'X'
  outfile.write(''.join(res)) # in 3.0, write(res)

tjr




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


Re: Why is there no GUI-tools like this for Windows?

2008-07-12 Thread Stef Mientki

maestro wrote:

http://www.youtube.com/watch?v=PXpwC1o5AcI

I have done some GUI-programming for windows with Python but the
Tkinter interface sucked and while it is the only one I tried I got
the impression they are all the same.

It's amazing how retarded a lot of the stuff programmers do is.
Watcing that video, that is how it should be.

I can just do the layout with my mouse and then there is a program
that writes the code for me.
GUI-programming is hard for no reason. One good program then forever
easy...
  

I asked this question about a year ago,
and for what I was used to (Delphi),
I can tell you, the link to the video looks terrible clumsy !!
And indeed there's nothing like that for Python,
there are a few (already forgot their names),
but unfortunately I couldn't get any of them working reliable.
I now work with a little procedure (much simpler than XRC),
and I'm even more satisfied with it than with Delphi.
Here an example:
   GUI = """
   NB,wx.Notebook   ,style = wx.NO_BORDER
 Panel1  ,PanelVer, 1   ,name  = "Hello"
   list1 ,wx.ListCtrl   ,style = wx.LC_REPORT
 Panel2  ,PanelVer, 11  ,name  = "Page2"
   window1   ,wx.Window
   window2   ,wx.Window
   """
   exec ( Create_wxGUI ( GUI ) )

cheers,
Stef


Is there not something like this for Python/Windows? Is the Linux one
only for ruby or for any language?

Oh well im switching to Linux anyway and mostly write webapps but
still...
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Correct use of try,except and raise?

2008-07-12 Thread ssecorp
Is this correct use of exceptions? to raise an indexerror and add my
own string insetad of just letting it raise a IndexError by itself and
"blaming" it on list.pop?

class Stack(object):
def __init__(self, *items):
self.stack = list(items)

def push(self, item):
self.stack.append(item)

def pop(self):
try:
return self.stack.pop()
except:
raise IndexError, "pop from empty stack"

class Queue(object):
def __init__(self, *items):
self.queue = list(items)

def append(self, item):
self.queue.append(item)

def pop(self):
try:
return self.queue.pop(0)
except:
raise IndexError, "pop from empty queue"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is this blowing the stack, thought it was tail-recursive...

2008-07-12 Thread Terry Reedy



ssecorp wrote:

def fib(n):
def fibt(a, b, n):
if n <= 1:
return b
else:
return fibt(b, a + b, n - 1)
if n == 0:
return 0
else:
return fibt(0, 1, n);

and can memoization speed up this even more? tesintg with memoization
doesnt really say anything because it is so fast it is instant anyway.


Except for the fact that a+b gets slower as a and b get bigger, this 
would already be linear time in n.  Memoization (here by means of a 
linear list) only helps if the list is preserved and one makes repeated 
requests for various fib values.


I am just curious what input you tried that blew the stack?  It had to 
be pretty large.


The stack problem, by the way, is one reason linear induction is usually 
written in Python with iteration syntax instead of recursion syntax. 
Another is the extra simplicity.


def fib(n):
  a,b = 1,0
  while n:
a,b,n = b, a+b, n-1
  return b

A third is the ease of conversion to a (space-efficient) generator function.

def fib_gen()
a,b = 1,0
while True:
yield b
a,b = b, a+b

The generator it produces can be used, for instance, to fill a list 
(linear memo) 'on demand'.


A model that leads to the linear algorithm (as opposed to the double 
recursion derived from Fibonacci's rabbit model) is as follows:
A population consists of juveniles and adults.  In one period, juveniles 
become adults (which never die) and adults birth (or bud off) one 
juvenile.  (Yeast are somewhat like this.)  At time 0, we start with 1 
juvenile and 0 adults.  How many adults are there at time n?


Terry Jan Reedy

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


Re: like py2exe, but on a mac

2008-07-12 Thread Alexnb



Python.Arno wrote:
> 
> 
> On 13 jul 2008, at 00:39, Alexnb wrote:
> 
>>
>> Hi All
>>
>> I am wondering what I can do to turn a python app (.py) into a mac OSX
>> applicaiton (.app). Just like py2exe does.
> 
> i use these:
> http://undefined.org/python/py2app.html
> http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm
> 
>> But I am also wondering since in
>> your applications folder on macs it usually doesn't have an actual  
>> folder
>> for each app. Rather an icon. so for firefox, you just see the icon.  
>> Unlike
>> windows where you have a folder with everything, and the actual  
>> program is
>> in it. where is all the application info stored? just in the .app?
> 
> apps on OSX are also folder, yet with the reserved .app extension
> the OS then presents this as an app (right click on an app and choose  
> 'Show package content')
> 
> py2app creates all that for you
> 
> 
>> Finally
>> whether or not there is an app like py2exe for mac, is there a way  
>> to skip
>> the middle man and turn it straight into a .dmg with the app inside?
>> --
> 
> a dmg is a disk image, similar to iso on windows
> you can create an empty one with Disk Utility then drop everything in
> it's NOT an installer
> 
>>
> cheers
> Arno
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 


Okay, well thank you very much for your help you answered all my questions
:)
-- 
View this message in context: 
http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424499.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: like py2exe, but on a mac

2008-07-12 Thread Python.Arno


On 13 jul 2008, at 00:39, Alexnb wrote:



Hi All

I am wondering what I can do to turn a python app (.py) into a mac OSX
applicaiton (.app). Just like py2exe does.


i use these:
http://undefined.org/python/py2app.html
http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm


But I am also wondering since in
your applications folder on macs it usually doesn't have an actual  
folder
for each app. Rather an icon. so for firefox, you just see the icon.  
Unlike
windows where you have a folder with everything, and the actual  
program is

in it. where is all the application info stored? just in the .app?


apps on OSX are also folder, yet with the reserved .app extension
the OS then presents this as an app (right click on an app and choose  
'Show package content')


py2app creates all that for you



Finally
whether or not there is an app like py2exe for mac, is there a way  
to skip

the middle man and turn it straight into a .dmg with the app inside?
--


a dmg is a disk image, similar to iso on windows
you can create an empty one with Disk Utility then drop everything in
it's NOT an installer




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


like py2exe, but on a mac

2008-07-12 Thread Alexnb

Hi All

I am wondering what I can do to turn a python app (.py) into a mac OSX
applicaiton (.app). Just like py2exe does. But I am also wondering since in
your applications folder on macs it usually doesn't have an actual folder
for each app. Rather an icon. so for firefox, you just see the icon. Unlike
windows where you have a folder with everything, and the actual program is
in it. where is all the application info stored? just in the .app? Finally
whether or not there is an app like py2exe for mac, is there a way to skip
the middle man and turn it straight into a .dmg with the app inside?
-- 
View this message in context: 
http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424336.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: heapq question

2008-07-12 Thread bearophileHUGS
Giampaolo Rodola':
> Even if I avoid to re-heapify() it seems that the first element
> returned by heappop() is always the smaller one.

Yes, the heappop() function keeps the heap invariant, so it will keep
giving you the smallest item.


> I'd like to understand if there are cases where
> deleting or moving an element of the heap, causes heappop() to return
> an element which is not the smallest one.

To be an heap it must keep its heap invariant true. The heap functions
keep that invariant. Generally any time you move/delete an item
yourself, you break the invariant, so you don't have an heap anymore
and you need to re-heapify to restore the heap invariant :-)

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


Re: Why is there no GUI-tools like this for Windows?

2008-07-12 Thread Guilherme Polo
On Sat, Jul 12, 2008 at 6:35 PM, maestro <[EMAIL PROTECTED]> wrote:
> http://www.youtube.com/watch?v=PXpwC1o5AcI
>
> I have done some GUI-programming for windows with Python but the
> Tkinter interface sucked and while it is the only one I tried I got
> the impression they are all the same.
>
> It's amazing how retarded a lot of the stuff programmers do is.
> Watcing that video, that is how it should be.
>
> I can just do the layout with my mouse and then there is a program
> that writes the code for me.

There are several programs that allow you to that, there is one not
really nice for tkinter, GUI Builder, there are glade and gazpacho for
gtk, Qt Designer for qt, wxglade and xrc (and others) for wxwidgets.
There are probably others for each of the toolkits I described on the
previous sentence, but those are the most well known (or not known at
all in case of GUI Builder for tkinter).

> GUI-programming is hard for no reason. One good program then forever
> easy...
>
> Is there not something like this for Python/Windows? Is the Linux one
> only for ruby or for any language?

All the examples I mentioned previously works both in Linux and
Windows. Also, they tend to not be language dependent either, they
tend to save the user interface description to some format like XML,
which you can then use independently of language (as long as your
language has a lib for reading its format and doing proper
processing).

>
> Oh well im switching to Linux anyway and mostly write webapps but
> still...
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Note: I didn't watch the video, if it presents something totally
unrelated to my answer, my bad then.

-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Why is there no GUI-tools like this for Windows?

2008-07-12 Thread maestro
http://www.youtube.com/watch?v=PXpwC1o5AcI

I have done some GUI-programming for windows with Python but the
Tkinter interface sucked and while it is the only one I tried I got
the impression they are all the same.

It's amazing how retarded a lot of the stuff programmers do is.
Watcing that video, that is how it should be.

I can just do the layout with my mouse and then there is a program
that writes the code for me.
GUI-programming is hard for no reason. One good program then forever
easy...

Is there not something like this for Python/Windows? Is the Linux one
only for ruby or for any language?

Oh well im switching to Linux anyway and mostly write webapps but
still...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Weird lambda rebinding/reassignment without me doing it

2008-07-12 Thread Terry Reedy



Steven D'Aprano wrote:

On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote:


g = lambda x:validate(x)

This is doubly diseased.

First, never write a 'name = lambda...' statement since it is equivalent
to a def statement except that the resulting function object lacks a
proper .funcname attribute.


Using lambda in this way is no more "diseased" than aliasing any other 
object.


In the context of giving advice to a confused beginner, I disagree.
He must learn def statements.  Lambda expressions are optional.

> It's a matter of personal preference not to bind a lambda to a
name. Functions, whether created by lambda or def, are first class 
objects, and as such there's nothing wrong with binding them to names.


When I brought this up on pydev, in the context of a style guide 
addition, about 9 of 10 respondants agreed that this should be 
discouraged.  Alex Martelli reported his experience that this 
construction more often leads people to the useless wrapping of function 
calls, such as the OP posted, than the def statement equivalent does.


One of the major reasons people give for wanting lambda expressions kept 
in Python and for using them is that they do not want to have to think 
up a name for short expressions.  If such a person then turns around and 
 binds the resulting function object to a name, then that rationale 
disappears.


Over the years, people have written on c.l.p about 'lambdas' as if they 
were a separate class of objects somehow different from def objects (and 
 not just an expression).  I believe writing and reading both 'name = 
lambda ...' and 'def name(...' engenders and reinforces this delusion, 
especially for beginners.


Admittedly, the lack of a func_name attribute can sometimes make 
tracebacks harder to understand, especially if you've got many bound 
lambdas.


Is saving two keystrokes worth that disadvantage, and the confusions 
mentioned above?  To me, no.  Hence my advice.


Terry Jan Reedy

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


Re: why is "self" used in OO-Python?

2008-07-12 Thread ssecorp
On Jul 12, 8:44 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Jul 12, 1:01 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
>
>
>
> > ssecorp <[EMAIL PROTECTED]> wrote:
> > > 1. Why do I have to pass self into every method in a class? Since I am
> > > always doing why cant this be automated or abstracted away?
> > > Are the instances where I won't pass self?
> > > I imagine there is some tradeoff involved otherwise it would have been
> > > done away with.
>
> > When you define a method in Java there is an implicit 'this' passed to the
> > method. Python cannot tell when you define a function whether the function
> > is going to be used as a function, an instance method, a class method, a
> > static method or something else (or all of the above). Consider this:
>
> > The dynamic nature of Python means you can lift a method out of a class and
> > re-use it in a different context or inject a function into a class as a
> > method. There are two ways to handle this sort of code: javascript has an
> > implied 'this' for everything whether a function or what passes for a
> > method, Python makes it explicit.
>
> > > 2. self.item instead of getters and setters. I thought one of the main
> > > purposes of OO was encapsulation. Doesn't messing with internal object-
> > > representations break this?
>
> > That is correct. Some languages (e.g. Java) don't allow you to encapsulate
> > attributes so you have to write getter and setter methods. If you expose an
> > attribute in Java then you cannot later insert some code into the lookup or
> > override the set without getting all users of your code to change the way
> > they access the value. This is bad.
>
> > Other languages (e.g. Python, C#) allow you to intercept the attribute
> > lookup so you can change a plain attribute into a property without
> > requiring the users of your class alter their source code. With C# I
> > think they would still need to recompile their code so it may be more
> > appropriate to avoid using public attributes if you are producing a class
> > library for widespread reuse, but with Python there is no difference to the
> > user of your class whether they are accessing an attribute or a property.
>
> > Sadly a lot of Java programmers mistake the limitations of their language
> > for rules of OO programming, and worse this has spread from Java into other
> > languages where these restrictions no longer need apply.
>
> > Your Stack class is a bad example: the stack attribute is purely internal
> > so you wouldn't want to expose it as part of the public interface. Consider
> > instead something like:
>
> > class AddressBookEntry(object):
> >     def __init__(self, name, phone):
> >         self.name = name
> >         self.phone = phone
>
> >     @property
> >     def phone(self):
> >         return self._phone
>
> >     @property.setter
> >     def phone(self, number)
> >         validatephonenumber(number) # may throw an exception
> >           self._phone = number
>
> > If later you want to add some processing to the name attribute it is easy,
> > but putting in dummy property getter/setter methods before you need them
> > would be pointless.
>
> Part of the value of accessor methods appears when you're changing
> class definitions, or changing classes, after you've already started
> to use them-- the same interface with a different implementation.
>
> In the AddressBookEntry example, if you changed a pickled dictionary
> to a shelf, you could reimplement the class and reprocess stored data
> files, all without changing the code that uses the class-- especially
> if there's a lot of it, or you don't know where it all is.
>
> Nothing stops you from using accessor methods to offer encapsulation,
> and permit back-end changes later.  But, nothing in Java stops you
> from declaring class members public.
>
> Depending on your development process, data hiding may enforce
> distribution of labor a little better, resulting in errors in Java
> where Python relies only on discipline.  If you're checking for value
> validation, you can write a custom setter, regardless of language.
>
> Python doesn't break encapsulation; you do.
>
> In the Stack example, you have more options than you've mentioned.
> Can you inherit from list directly?  Can you delegate using
> reflection?  Are you studying this example specifically, or the class
> model generally?  If you're choosing a language, be careful that
> stricter enforcement doesn't cause harder-to-find bugs.
>
> Useful link: Section 9.4 in the docs:http://docs.python.org/tut/node11.html




ty for all the answers. Im not saying either is better Im just trying
to fiugre out the philosophies behind each language and their
respective pros and cons.


and self is apparently not a reserved word so I could replace it with
"blahaba".
But basically Python trusts the programmer and relies on conventions
rather than enforcements like Java does.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Question : Iterators and zip

2008-07-12 Thread [EMAIL PROTECTED]
On 12 juil, 20:55, [EMAIL PROTECTED] wrote:
> Hi group,
>
> I have a basic question on the zip built in function.
>
> I am writing a simple text file comparison script, that compares line
> by line and character by character. The output is the original file,
> with an X in place of any characters that are different.
>
> I have managed a solution for a fixed (3) number of files, but I want
> a solution of any number of input files.
>
> The outline of my solution:
>
> for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
> res = ''
> for entry in zip(vec[0],vec[1],vec[2]):
> if len(set(entry)) > 1:
> res = res+'X'
> else:
> res = res+entry[0]
> outfile.write(res)
>
> So vec is a tuple containing a line from each file, and then entry is
> a tuple containg a character from each line.
>
> 2 questions
> 1) What is the general solution. Using zip in this way looks wrong. Is
> there another function that does what I want

zip is (mostly) ok. What you're missing is how to use it for any
arbitrary number of sequences. Try this instead:

>>> lists = [range(5), range(5,11), range(11, 16)]
>>> lists
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> for item in zip(*lists):
... print item
...
(0, 5, 11)
(1, 6, 12)
(2, 7, 13)
(3, 8, 14)
(4, 9, 15)
>>> lists = [range(5), range(5,11), range(11, 16), range(16, 20)]
>>> for item in zip(*lists):
... print item
...
(0, 5, 11, 16)
(1, 6, 12, 17)
(2, 7, 13, 18)
(3, 8, 14, 19)
>>>

The only caveat with zip() is that it will only use as many items as
there are in your shorter sequence, ie:

>>> zip(range(3), range(10))
[(0, 0), (1, 1), (2, 2)]
>>> zip(range(30), range(10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8,
8), (9, 9)]
>>>

So you'd better pad your sequences to make them as long as the longer
one. There are idioms for doing this using the itertools package's
chain and repeat iterators, but I'll leave concrete example as an
exercice to the reader !-)

> 2) I am using set to remove any repeated characters. Is there a
> "better" way ?

That's probably what I'd do too.

> Any other comments/suggestions appreciated.

There's a difflib package in the standard lib. Did you give it a try ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused

2008-07-12 Thread Terry Reedy



Michael Torrie wrote:

eric.butteriss wrote:

Please tell me why may mail is being returned. The message says I
have been blacklisted...for what reason? I never open mail that I
know is not expected and I never send junk or spam. I am trying to
send important info to my cousin.


Now I'm confused.  Is the python mailing list blacklisting you?  Unless
this is a python-related thing, I doubt you'll find anyone here who can
help.


I think the OP is another spammer.  Who would email a cousin via a 
language email list?  This was probably sent to multiple lists.


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


Re: Help with BeautifulSoup

2008-07-12 Thread Alexnb



Michiel Overtoom wrote:
> 
> Alex wrote...
>>
>>Okay, heres the general idea of the html I have to work with:
>>
>>
>>   noun
>>   
>>   
>>   
>>   
>>   verb
>>   
>>   
>>   
>>
>>
>>Okay, I left off some stuff. 
> 
> I wish you didn't, or at least provided an URL where I can get the page
> which you are trying to parse.  Now I don't have a valid testcase to
> tinker
> with.  And maybe you can also show your code which you already came up
> with.
> 
> 
>> I can easily get the tables but it is the span's than I am having trouble
> with. 
> 
> I can't see any SPAN tags in the example you provided.
> 
> Greetings,
> 
> -- 
> "The ability of the OSS process to collect and harness
> the collective IQ of thousands of individuals across
> the Internet is simply amazing." - Vinod Vallopillil
> http://www.catb.org/~esr/halloween/halloween4.html
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Oh, well sorry, I wrote the span tags, but they didn't show up. But it was
around the noun. Here is the code I have to get the definitions alone:

import urllib
from BeautifulSoup import BeautifulSoup

class defWord:
def __init__(self, word):
self.word = word

def get_defs(term):
soup =
BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' %
term))

for tabs in soup.findAll('table', {'class': 'luna-Ent'}):
yield tabs.findAll('td')[-1].contents[0].string

self.mainList = list(get_defs(self.word))

Theres a bit more to it, but it doesn't matter here, and so if you look I am
using dictionary.com as the website. If you look at the html, the "" tags
are where the type of the word is and that is what I need, in order. Or if I
can figure out how many  tags are inbetween each "" tag, that too
would work. 

If you need anything else, feel free to ask! 
-- 
View this message in context: 
http://www.nabble.com/Re%3A-Help-with-BeautifulSoup-tp18418004p18423003.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: why is "self" used in OO-Python?

2008-07-12 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Duncan Booth <[EMAIL PROTECTED]> wrote:

> Sadly a lot of Java programmers mistake the limitations of their language 
> for rules of OO programming, and worse this has spread from Java into other 
> languages where these restrictions no longer need apply.

You can generalize that to, "a lot of programmers assume that OO is defined 
by whatever happens to be the first OO language they learn".

In fact, it generalizes even further to the Law of Primacy 
(http://en.wikipedia.org/wiki/Principles_of_learning#Primacy).  I recognize 
this drivel from the crud the FAA publishes:

> Primacy, the state of being first, often creates a strong, almost unshakable, 
> impression. Things learned first create a strong impression in the mind that 
> is difficult to erase. For the instructor, this means that what is taught 
> must be right the first time. For the student, it means that learning must be 
> right. ³Unteaching² wrong first impressions is harder than teaching them 
> right the first time. If, for example, a student learns a faulty technique, 
> the instructor will have a difficult task correcting bad habits and 
> ³reteaching² correct ones.

but fundamentally, it's true.  If the first programming language (or the 
first OOPL) a person learns is Java, it should come as no surprise when 
they think they way Java does things is the only way to do things.  Having 
seen no other ways yet, what else *could* they think?

I have no objection to teaching Java in a CS curriculum.  Or even making it 
the first language you teach.  What I do object to is making it the ONLY 
language you teach.

My next door neighbor's kid just finished a MSCS program.  The curriculum 
did a pretty good job of covering most of the important topics, but they 
did it all in Java.  Web development in Java, graphics programming in Java, 
algorithms in Java, etc.  He's well prepared to get a job as a Java 
programmer (and, in fact, he did), but I don't think he's really trained to 
be a computer scientist.

A good CS program should include a survey of different programming 
languages.  Today, I would certainly want to give students exposure to C++, 
at least one of {Python,Ruby}, and a random sampling of some less main-line 
languages like Erlang, Lisp, PHP, Groovy, Smalltalk, or PostScript.   
Exactly which ones is not so important as getting to see a wide variety of 
different approaches.  Only after you've seen a bunch of different ways of 
doing something can you start to appreciate the choices different language 
designers made.

BTW, there's an interesting article in the July 2008 Computer Magazine: "In 
Priase of Scripting: Real Programming Pragmatism".  Ronald Loui argues 
(amongst other things) that Python would make a good first language to 
teach in a CS curriculum.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Changing self: if self is a tree how to set to a different self

2008-07-12 Thread Terry Reedy



Kay Schluehr wrote:



Since it is acting on a tree why doesn't the code substitute self in
its parent by SS? That's the natural perspective if one considers a
tree as a linked structure and inserts and deletes nodes within this
structure.


I think you are suggesting the same thing I did:

> If you examine nodes from their parent, I believe you can do the
> > substitution in one step. Something like:
> >
> > for slot,child in ( ('left',self.left), ('right',self.right) ):
> >   if child is not None:
> > if child.val == 'f':
> >   setattr(self, slot, F.copy().subst('x', child.left))
> > child.elimF
> >
> > where .subst returns the modified tree.

Where F.copy is what was called 'SS'.  If not, I don't understand.

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


Re: palindrome function

2008-07-12 Thread Mensanator
On Jul 12, 2:18�pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Peter Otten wrote:
> > Denis Kasak wrote:
>
> >> Basically, it reverses the list in place, so it modifies the list which
> >> called it. It does not return a /new/ list which is a reversed version
> >> of the original, as you expected it to. Since it doesn't return anything
> >> explicitly, Python makes it return None. Hence, the comparison you are
> >> doing is between the original list and a None, which is False, naturally.
> >> Try this:
>
> >> spam = ['a', 'n', 'n', 'a']
> >> eggs = spam[:]
> >> if spam.reverse() == eggs:
> >> � � print "Palindrome"
>
> > Your explanation is correct, but your example code compares None to
> > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either.
>
> I don't know if this was posted yet,

It hasn't. and here's why:

IDLE 2.6b1
>>> seq=['a','n','n','a']
>>> seq.reversed()

Traceback (most recent call last):
  File "", line 1, in 
seq.reversed()
AttributeError: 'list' object has no attribute 'reversed'


> but 'seq.reversed() == seq' is the
> simple way to test for 'palindomeness'.

Not in 2.x.

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

Re: Beginner Question : Iterators and zip

2008-07-12 Thread Larry Bates

[EMAIL PROTECTED] wrote:

Hi group,

I have a basic question on the zip built in function.

I am writing a simple text file comparison script, that compares line
by line and character by character. The output is the original file,
with an X in place of any characters that are different.

I have managed a solution for a fixed (3) number of files, but I want
a solution of any number of input files.

The outline of my solution:

for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
res = ''
for entry in zip(vec[0],vec[1],vec[2]):
if len(set(entry)) > 1:
res = res+'X'
else:
res = res+entry[0]
outfile.write(res)

So vec is a tuple containing a line from each file, and then entry is
a tuple containg a character from each line.

2 questions
1) What is the general solution. Using zip in this way looks wrong. Is
there another function that does what I want
2) I am using set to remove any repeated characters. Is there a
"better" way ?

Any other comments/suggestions appreciated.

Thanks,

Steven






You should take a look at Python's difflib library.  I probably already does
what you are attempting to "re-invent".

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


Re: Doubts about how implementing asynchronous timeouts through a heap

2008-07-12 Thread Josiah Carlson
On Jul 9, 4:13 am, "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm trying to implement an asynchronous scheduler for asyncore to call
> functions at a later time without blocking the main loop.
> The logic behind it consists in:
>
> - adding the scheduled functions into a heapified list
> - calling a "scheduler" function at every loop which checks the
> scheduled functions due to expire soonest
>
> Note that, by using a heap, the first element of the list is always
> supposed to be the one with the lower timeout.
> Here's the code I wrote:
>
> <--- snippet --->
> import heapq
> import time
> import sys
>
> delayed_map = []
>
> class delayed_call:
>     """Calls a function at a later time.
>
>     The instance returned is an object that can be used to cancel the
>     scheduled call, by calling its cancel() method.
>     It also may be rescheduled by calling delay() or reset()} methods.
>     """
>
>     def __init__(self, delay, target, *args, **kwargs):
>         """
>         - delay: the number of seconds to wait
>         - target: the callable object to call later
>         - args: the arguments to call it with
>         - kwargs: the keyword arguments to call it with
>         """
>         assert callable(target), "%s is not callable" %target
>         assert sys.maxint >= delay >= 0, "%s is not greater than or
> equal " \
>                                            "to 0 seconds" % (delay)
>         self.__delay = delay
>         self.__target = target
>         self.__args = args
>         self.__kwargs = kwargs
>         # seconds from the epoch at which to call the function
>         self.timeout = time.time() + self.__delay
>         self.cancelled = False
>         heapq.heappush(delayed_map, self)
>
>     def __le__(self, other):
>         return self.timeout <= other.timeout
>
>     def active(self):
>         """Return True if this scheduler has not been cancelled."""
>         return not self.cancelled
>
>     def call(self):
>         """Call this scheduled function."""
>         self.__target(*self.__args, **self.__kwargs)
>
>     def reset(self):
>         """Reschedule this call resetting the current countdown."""
>         assert not self.cancelled, "Already cancelled"
>         self.timeout = time.time() + self.__delay
>         if delayed_map[0] is self:
>             heapq.heapify(delayed_map)
>
>     def delay(self, seconds):
>         """Reschedule this call for a later time."""
>         assert not self.cancelled, "Already cancelled."
>         assert sys.maxint >= seconds >= 0, "%s is not greater than or
> equal " \
>                                            "to 0 seconds" %(seconds)
>         self.__delay = seconds
>         self.reset()
>
>     def cancel(self):
>         """Unschedule this call."""
>         assert not self.cancelled, "Already cancelled"
>         del self.__target, self.__args, self.__kwargs
>         if self in delayed_map:
>             if delayed_map[0] is self:
>                 delayed_map.remove(self)
>                 heapq.heapify(delayed_map)
>             else:
>                 delayed_map.remove(self)
>         self.cancelled = True
>
> def fun(arg):
>     print arg
>
> a = delayed_call(0.6, fun, '0.6')
> b = delayed_call(0.5, fun, '0.5')
> c = delayed_call(0.4, fun, '0.4')
> d = delayed_call(0.3, fun, '0.3')
> e = delayed_call(0.2, fun, '0.2')
> f = delayed_call(0.1, fun, '0.1')
>
> while delayed_map:
>     now = time.time()
>     while delayed_map and now >= delayed_map[0].timeout:
>         delayed = heapq.heappop(delayed_map)
>         try:
>             delayed.call()
>         finally:
>             if not delayed.cancelled:
>                 delayed.cancel()
>     time.sleep(0.01)
> 
>
> Here comes the questions.
> Since that the timeouts of the scheduled functions contained in the
> list can change when I reset() or cancel() them I don't know exactly
> *when* the list needs to be heapified().
> By doing some tests I came to the conclusion that I need the heapify()
> the list only when the function I reset() or cancel() is the *first of
> the list* but I'm not absolutely sure about it.
> When do you think it would be necessary calling heapify()?
> I wrote a short test suite which tests the code above and I didn't
> notice strange behaviors but since that I don't know much about the
> logic behind heaps I'd need some help.
> Thanks a lot in advance.
>
> --- Giampaolohttp://code.google.com/p/pyftpdlib/

I dug through my old pair heap implementation, did a little hacking on
heapq, and wrote a task scheduler system that plugs in to asyncore.

To schedule a task, you use:
task = asyncore.schedule_task(schedule, delay, callable, *args,
**kwargs)

Once you have that task object, you can then use:
asyncore.reschedule_task(schedule, delay, task)
asyncore.abs_reschedule_task(schedule, time, task)
... to reschedule the task into the future (or past).

You can also:
asyncore.delete_task(schedule, task)
... to completely remove the task 

Re: palindrome function

2008-07-12 Thread Terry Reedy



Peter Otten wrote:

Denis Kasak wrote:


Basically, it reverses the list in place, so it modifies the list which
called it. It does not return a /new/ list which is a reversed version
of the original, as you expected it to. Since it doesn't return anything
explicitly, Python makes it return None. Hence, the comparison you are
doing is between the original list and a None, which is False, naturally.
Try this:

spam = ['a', 'n', 'n', 'a']
eggs = spam[:]
if spam.reverse() == eggs:
print "Palindrome"


Your explanation is correct, but your example code compares None to
['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either.


I don't know if this was posted yet, but 'seq.reversed() == seq' is the 
simple way to test for 'palindomeness'.


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


how can I use exec with main module globals?

2008-07-12 Thread Akathorn Greyhat
Hello, this is my first message in the group.

I'm spanish so my english sometimes is really bad, sorry =(

I have a problem and I hope someone has the answer.

I'm trying to make an in-game python idle, it works great but the exec
statement can't access the main module globals but only the ones that are
inside the module in wich I defined the function.

def execute(self, string):
exec(string, globals(), globals())

I realized that if I move the code to the main module, It works, but I want
it to be inside another script.

So my question is, how can I make the exec statement access the main
globals?

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

Re: Why is this blowing the stack, thought it was tail-recursive...

2008-07-12 Thread Scott David Daniels

ssecorp wrote:
 used>

and can memoization speed up this even more? 


Generators get you to an even clearer Fibonacci expression.

def _Fibonacci_gen():
a, b = 1, 0
while True:
a += b
yield a
b += a
yield b

Here's how to use it to avoid redundant comutation:

_next_entry = _Fibonacci_gen().next
_sofar = []

def fib(n):
while len(_sofar) <= n:
_sofar.append(_next_entry())
return _sofar[n]


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


Re: heapq question

2008-07-12 Thread Giampaolo Rodola'
On 12 Lug, 20:15, Duncan Booth <[EMAIL PROTECTED]> wrote:
> "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:
>
> > My question is the following: is it safe to avoid to re-heapify() a
> > heap when I remove or move an element which is not the first one?
> > Example:
>
>  from heapq import *
>  heap = [2,4,6,7,1,2,3]
>  heapify(heap)
>  del heap[4]
>  # Am I forced to heapify() the heap here?
>
> > Thanks in advance.
>
> No, it is not safe to avoid re-heapifying.
>
> After you call heapify the list is ordered such that for any 'n' in the
> range 1..len(heap)//2 it is the case that heap[n-1] <= heap[2*n-1] and when
> heap[2*n] exists heap[n-1] <= heap[2*n].
>
> So:
>
> >>> heap = [0, 100, 1, 101, 102, 2, 3]
> >>> heapify(heap)
> >>> heap
>
> [0, 100, 1, 101, 102, 2, 3]>>> del(heap[4])
> >>> heap
>
> [0, 100, 1, 101, 2, 3]>>> heapify(heap)
> >>> heap
>
> [0, 2, 1, 101, 100, 3]
>
> after deleting heap[4] it is no longer the case that heap[1] >= heap[4] as
> the old heap[5] was a child of heap[2] not of heap[1].

Even if I avoid to re-heapify() it seems that the first element
returned by heappop() is always the smaller one.

>>> heap = [0, 100, 1, 101, 102, 2, 3]
>>> heapify(heap)
>>> heap
[0, 100, 1, 101, 102, 2, 3]
>>> del heap[4]
>>> heap
[0, 100, 1, 101, 2, 3]
>>> heappop(heap)
0
>>> heappop(heap)
1
>>> heappop(heap)
2
>>> heappop(heap)
3
>>> heappop(heap)
100
>>> heappop(heap)
101
>>> heappop(heap)
Traceback (most recent call last):
  File "", line 1, in 
IndexError: index out of range
>>>


That would be ok for me, as long as heappop() always returns the
smallest item.
Having said that I'd like to understand if there are cases where
deleting or moving an element of the heap, causes heappop() to return
an element which is not the smallest one.


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


SQLAlchmey - new data types for PostgreSQL

2008-07-12 Thread Kless
It would be very interesting if the python community could to access
since SQLAlchemy to more features of the PostgreSQL 8.3 RDBMS
powerful, as are any new data types as: enumerated (ENUM) [1],  XML
[2], Universally Unique Identifiers (UUID) [3], and monetary [4].

For if anybody is interested on add them, see here: [5]


[1] http://www.postgresql.org/docs/8.3/static/datatype-enum.html
[2] http://www.postgresql.org/docs/8.3/static/datatype-xml.html
[3] http://www.postgresql.org/docs/8.3/static/datatype-uuid.html
[4] http://www.postgresql.org/docs/8.3/static/datatype-money.html

[5]
http://www.sqlalchemy.org/docs/05/sqlalchemy_databases_postgres.html

http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/lib/sqlalchemy/databases/postgres.py
--
http://mail.python.org/mailman/listinfo/python-list


Beginner Question : Iterators and zip

2008-07-12 Thread moogyd
Hi group,

I have a basic question on the zip built in function.

I am writing a simple text file comparison script, that compares line
by line and character by character. The output is the original file,
with an X in place of any characters that are different.

I have managed a solution for a fixed (3) number of files, but I want
a solution of any number of input files.

The outline of my solution:

for vec in zip(vec_list[0],vec_list[1],vec_list[2]):
res = ''
for entry in zip(vec[0],vec[1],vec[2]):
if len(set(entry)) > 1:
res = res+'X'
else:
res = res+entry[0]
outfile.write(res)

So vec is a tuple containing a line from each file, and then entry is
a tuple containg a character from each line.

2 questions
1) What is the general solution. Using zip in this way looks wrong. Is
there another function that does what I want
2) I am using set to remove any repeated characters. Is there a
"better" way ?

Any other comments/suggestions appreciated.

Thanks,

Steven





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


Re: why is "self" used in OO-Python?

2008-07-12 Thread castironpi
On Jul 12, 1:01 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> ssecorp <[EMAIL PROTECTED]> wrote:
> > 1. Why do I have to pass self into every method in a class? Since I am
> > always doing why cant this be automated or abstracted away?
> > Are the instances where I won't pass self?
> > I imagine there is some tradeoff involved otherwise it would have been
> > done away with.
>
> When you define a method in Java there is an implicit 'this' passed to the
> method. Python cannot tell when you define a function whether the function
> is going to be used as a function, an instance method, a class method, a
> static method or something else (or all of the above). Consider this:
>
> The dynamic nature of Python means you can lift a method out of a class and
> re-use it in a different context or inject a function into a class as a
> method. There are two ways to handle this sort of code: javascript has an
> implied 'this' for everything whether a function or what passes for a
> method, Python makes it explicit.
>
> > 2. self.item instead of getters and setters. I thought one of the main
> > purposes of OO was encapsulation. Doesn't messing with internal object-
> > representations break this?
>
> That is correct. Some languages (e.g. Java) don't allow you to encapsulate
> attributes so you have to write getter and setter methods. If you expose an
> attribute in Java then you cannot later insert some code into the lookup or
> override the set without getting all users of your code to change the way
> they access the value. This is bad.
>
> Other languages (e.g. Python, C#) allow you to intercept the attribute
> lookup so you can change a plain attribute into a property without
> requiring the users of your class alter their source code. With C# I
> think they would still need to recompile their code so it may be more
> appropriate to avoid using public attributes if you are producing a class
> library for widespread reuse, but with Python there is no difference to the
> user of your class whether they are accessing an attribute or a property.
>
> Sadly a lot of Java programmers mistake the limitations of their language
> for rules of OO programming, and worse this has spread from Java into other
> languages where these restrictions no longer need apply.
>
> Your Stack class is a bad example: the stack attribute is purely internal
> so you wouldn't want to expose it as part of the public interface. Consider
> instead something like:
>
> class AddressBookEntry(object):
>     def __init__(self, name, phone):
>         self.name = name
>         self.phone = phone
>
>     @property
>     def phone(self):
>         return self._phone
>
>     @property.setter
>     def phone(self, number)
>         validatephonenumber(number) # may throw an exception
>           self._phone = number
>
> If later you want to add some processing to the name attribute it is easy,
> but putting in dummy property getter/setter methods before you need them
> would be pointless.

Part of the value of accessor methods appears when you're changing
class definitions, or changing classes, after you've already started
to use them-- the same interface with a different implementation.

In the AddressBookEntry example, if you changed a pickled dictionary
to a shelf, you could reimplement the class and reprocess stored data
files, all without changing the code that uses the class-- especially
if there's a lot of it, or you don't know where it all is.

Nothing stops you from using accessor methods to offer encapsulation,
and permit back-end changes later.  But, nothing in Java stops you
from declaring class members public.

Depending on your development process, data hiding may enforce
distribution of labor a little better, resulting in errors in Java
where Python relies only on discipline.  If you're checking for value
validation, you can write a custom setter, regardless of language.

Python doesn't break encapsulation; you do.

In the Stack example, you have more options than you've mentioned.
Can you inherit from list directly?  Can you delegate using
reflection?  Are you studying this example specifically, or the class
model generally?  If you're choosing a language, be careful that
stricter enforcement doesn't cause harder-to-find bugs.

Useful link: Section 9.4 in the docs: http://docs.python.org/tut/node11.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does omniORBpy 3.2 supports DII?

2008-07-12 Thread Ilan
On 10 יולי, 17:42, Wolfgang Keller <[EMAIL PROTECTED]> wrote:
> > My apologies if this is not the correct forum for thses quiestions,
>
> It's not the wrong place to ask, but you're more likely to get answers
> from the omniORB mailing lists:
>
> http://www.omniorb-support.com/mailman/listinfo
>
> Sincerely,
>
> Wolfgang

Thank you for your response.
I already posted this question at that list, i did not get any
response yet..
--
http://mail.python.org/mailman/listinfo/python-list

Re: why is "self" used in OO-Python?

2008-07-12 Thread [EMAIL PROTECTED]
On 12 juil, 18:32, ssecorp <[EMAIL PROTECTED]> wrote:
> I first learned about OO from Java.
>
> I much prefer to program in Python though.
>
> However I am consufed about 2 things.
>
> 1. Why do I have to pass self into every method in a class?

You mean "declare self as the first argument", I assume ?

This has been explained many times here. Anyway: the point is that
what you define is not a method, but a function. This function needs
to have a way to get at the instance on which it's called, and the
simplest way to do so is to use the common way: passing it as an
argument. This avoids having to have two different constructs -
functions and methods - when one is enough.

> Since I am
> always doing why cant this be automated or abstracted away?

This could, probably, but you'd had complexity, break uniformity and
loose some interesting features of the language.

>
> 2. self.item instead of getters and setters. I thought one of the main
> purposes of OO was encapsulation.

I don't know if it's "one of the main purposes", but you're missing
the point: you have to use explicit getters and setters in Java
because Java doesn't have any support for computed attributes. In
Python, the object.attribute syntax doesn't mean you are directly
accessing an instance attribute. First because lookup rules are more
complex than that (not only the instance, but also it's class and it's
class parents are looked up), then because there are several ways to
hook into these lookup rules. Given that you can decouple the
interface (looks like an access attribute) from the implementation
(anything from an instance attribute to a method call in a distantly
related class, possibly including a network connection and database
access), you just don't need explicit getters and setters when
directly accessing an instance attribute is enough (and that's more
than often the case).

>  Doesn't messing with internal object-
> representations break this?

It does, indeed, but it's sometimes necessary (as a matter of fact,
there are ways to get at private attributes even in Java). Anyway,
this is unrelated to your above question about getters and setters.

> I see how the getters and setters could be just visual clutter and you
> have to add them to every class so it is annoying a bit in the same
> way as self described above.
> However I feel like I want getters and setters when I write classes,
> not sure of the advantages/disadvantages though.

Unless you need to do something else than accessing an instance
attribute, explicit getters and setters in Python are a pure waste of
time for you, anyone using your code, and even the computer.

> Only looking at the documentation of a Python-class, will internal
> representations be provided?

For which definition of "internal representation" ?

> If I have a class:
>
> class Stack(object):
> def __init__(self, *items):
> self.stack = list(items)
>
> def append(self, item):
> self.stack.append(item)

# OT : canonically, it's stac.push(item), not stack.append(item)

> def pop(self):
> return self.stack.pop()
>
> I can get to see the stack with var.stack but then why even implement
> append when I could do self.stack.append(x) etc.

Because you may want to change the implementation, as usual. But you
shouldn't expose stack as part of your API. The convention in Python
is to name implementation stuff with a leading underscore. This a
*very* strong convention saying "don't mess with this unless you know
exactly what you're doing and are willing and able to take full
responsability if you break anything or if your code breaks when I'll
change my class implementation". So just rename 'stack' to '_stack',
and anyone using your class will ignore it unless they have a pretty
good reason to mess with it and are ok to suffer the potential
consequences.

> That way you could do away with OO completely.

You could, but what would be the point ? Why would I mess with
implementation when I get what I need using the API ?

> So why let people
> access the main attribute but not let them manipulate it?

You just can't stop them from manipulating it if they really want, you
know. Don't worry, whatever the language, if someone want to mess with
implementation, he will find a way.

> Makes more sense to draw the line to not access any attributes at all
> no?

No. Most programmers are of at least median intelligence, and won't
even have a look at your implementation as long as they can - because
they don't want to have to worry about implementation. As long as you
clearly marked something as being "implementation, don't touch", and
provided a sound API, then you've done your job.

I know this can sound disturbing when coming from the ultra-dogmatic
chains-and-bondage world of Java, but from experience (from dozens of
years of thousands of programmers), Python's pragmatic approach
JustWorks(tm).

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


fix for wxPython incompatibility of BitTornado 0.3.18

2008-07-12 Thread Avi Kak
If you are unable to use the wxPython-based GUI interfaces in the
BitTornado 0.3.18 library on your Ubuntu 8.04 machine, you may wish to
download a directory of the library available through

 http://cobweb.ecn.purdue.edu/~kak/distbt/

If any problems, send me email at [EMAIL PROTECTED] with "BitTornado" in
the subject line to get past my procmail filter.


Avi Kak



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


Re: heapq question

2008-07-12 Thread Duncan Booth
"Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:

> 
> My question is the following: is it safe to avoid to re-heapify() a
> heap when I remove or move an element which is not the first one?
> Example:
> 
 from heapq import *
 heap = [2,4,6,7,1,2,3]
 heapify(heap)
 del heap[4]
 # Am I forced to heapify() the heap here?
> 
> Thanks in advance.

No, it is not safe to avoid re-heapifying.

After you call heapify the list is ordered such that for any 'n' in the 
range 1..len(heap)//2 it is the case that heap[n-1] <= heap[2*n-1] and when 
heap[2*n] exists heap[n-1] <= heap[2*n].

So:

>>> heap = [0, 100, 1, 101, 102, 2, 3]
>>> heapify(heap)
>>> heap
[0, 100, 1, 101, 102, 2, 3]
>>> del(heap[4])
>>> heap
[0, 100, 1, 101, 2, 3]
>>> heapify(heap)
>>> heap
[0, 2, 1, 101, 100, 3]

after deleting heap[4] it is no longer the case that heap[1] >= heap[4] as 
the old heap[5] was a child of heap[2] not of heap[1].
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is this blowing the stack, thought it was tail-recursive...

2008-07-12 Thread Marc Christiansen
ssecorp <[EMAIL PROTECTED]> asked:
> Why is this blowing the stack, thought it was tail-recursive...

Because python does no tail-call optimization.

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


Re: why is "self" used in OO-Python?

2008-07-12 Thread Duncan Booth
ssecorp <[EMAIL PROTECTED]> wrote:

> 1. Why do I have to pass self into every method in a class? Since I am
> always doing why cant this be automated or abstracted away?
> Are the instances where I won't pass self?
> I imagine there is some tradeoff involved otherwise it would have been
> done away with.

When you define a method in Java there is an implicit 'this' passed to the 
method. Python cannot tell when you define a function whether the function 
is going to be used as a function, an instance method, a class method, a 
static method or something else (or all of the above). Consider this:

>>> class C: pass

>>> def showme(*args, **kw):
print args, kw


>>> C.method = showme
>>> C.staticmethod = staticmethod(showme)
>>> C.classmethod = classmethod(showme)
>>> showme(1,2,3)
(1, 2, 3) {}
>>> C().method(1,2,3)
(<__main__.C instance at 0x00C4B580>, 1, 2, 3) {}
>>> C().staticmethod(1,2,3)
(1, 2, 3) {}
>>> C().classmethod(1,2,3)
(, 1, 2, 3) {}
>>> 

The dynamic nature of Python means you can lift a method out of a class and 
re-use it in a different context or inject a function into a class as a 
method. There are two ways to handle this sort of code: javascript has an 
implied 'this' for everything whether a function or what passes for a 
method, Python makes it explicit.

> 2. self.item instead of getters and setters. I thought one of the main
> purposes of OO was encapsulation. Doesn't messing with internal object-
> representations break this?

That is correct. Some languages (e.g. Java) don't allow you to encapsulate 
attributes so you have to write getter and setter methods. If you expose an 
attribute in Java then you cannot later insert some code into the lookup or 
override the set without getting all users of your code to change the way 
they access the value. This is bad.

Other languages (e.g. Python, C#) allow you to intercept the attribute 
lookup so you can change a plain attribute into a property without 
requiring the users of your class alter their source code. With C# I 
think they would still need to recompile their code so it may be more 
appropriate to avoid using public attributes if you are producing a class 
library for widespread reuse, but with Python there is no difference to the 
user of your class whether they are accessing an attribute or a property.

Sadly a lot of Java programmers mistake the limitations of their language 
for rules of OO programming, and worse this has spread from Java into other 
languages where these restrictions no longer need apply.

Your Stack class is a bad example: the stack attribute is purely internal 
so you wouldn't want to expose it as part of the public interface. Consider 
instead something like:

class AddressBookEntry(object):
def __init__(self, name, phone):
self.name = name
self.phone = phone

@property
def phone(self):
return self._phone

@property.setter
def phone(self, number)
validatephonenumber(number) # may throw an exception
  self._phone = number

If later you want to add some processing to the name attribute it is easy, 
but putting in dummy property getter/setter methods before you need them 
would be pointless.
--
http://mail.python.org/mailman/listinfo/python-list


heapq question

2008-07-12 Thread Giampaolo Rodola'
Hi,
this is related to what I'm trying to implement here:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/20796724c1daf1e1#

My question is the following: is it safe to avoid to re-heapify() a
heap when I remove or move an element which is not the first one?
Example:

>>> from heapq import *
>>> heap = [2,4,6,7,1,2,3]
>>> heapify(heap)
>>> del heap[4]
>>> # Am I forced to heapify() the heap here?

Thanks in advance.


--- Giampaolo
http://code.google.com/p/pyftpdlib/

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


Re: why is "self" used in OO-Python?

2008-07-12 Thread Carl Banks
On Jul 12, 12:32 pm, ssecorp <[EMAIL PROTECTED]> wrote:
> I first learned about OO from Java.
>
> I much prefer to program in Python though.
>
> However I am consufed about 2 things.

Short answer is, "Java isn't the only way OOP."

Longer answers follow.


> 1. Why do I have to pass self into every method in a class? Since I am
> always doing why cant this be automated or abstracted away?
> Are the instances where I won't pass self?
> I imagine there is some tradeoff involved otherwise it would have been
> done away with.

This is pretty simple: it was judged to be significantly more readable
if you mark class variables explicitly.  That is, when you see
something like "self.var" you instantly know it's an attribute of the
object and not a local or global variable.

That you sometimes see Java and (more often) C++ guidelines that
recommend always using "this" for accessing class members shows that
it's somewhat helpful to keep them visually distinct from other
variables.

I think it's a minor point, really, that people make a pretty big deal
over.


> 2. self.item instead of getters and setters. I thought one of the main
> purposes of OO was encapsulation.

Just as an aside: the usage of getters and setters probably does more
to thwart encapsulation than to protect it, in practice.

You see, it doesn't matter whether you access a member directly, or
through getters and setters: you're still accessing the member.
Getters and setters don't encapsulate your data one bit.  All they do
is to add a bunch of mostly unnecessary boilerplate.

OTOH, many people add getters and setters recklessly, based on the
above misconception.  Not only are they exposing internal details by
doing this, they're also giving the user a blessing to use them.

The practical advantage getters and setters have in Java is that, if
your class implementation changes and you no longer wish for something
that was once a single variable to be that way anymore, you can change
your underlying implementation without changing the interface.  That
advantage does not exist in Python, however, since in Python one can
do the same thing with properties.


> Doesn't messing with internal object-
> representations break this?
> I see how the getters and setters could be just visual clutter and you
> have to add them to every class so it is annoying a bit in the same
> way as self described above.
> However I feel like I want getters and setters when I write classes,
> not sure of the advantages/disadvantages though.
> Only looking at the documentation of a Python-class, will internal
> representations be provided?
>
> If I have a class:
>
> class Stack(object):
> def __init__(self, *items):
> self.stack = list(items)
>
> def append(self, item):
> self.stack.append(item)
>
> def pop(self):
> return self.stack.pop()
>
> I can get to see the stack with var.stack but then why even implement
> append when I could do self.stack.append(x) etc.
> That way you could do away with OO completely. So why let people
> access the main attribute but not let them manipulate it?
> Makes more sense to draw the line to not access any attributes at all
> no?

Much of what you're arguing is only true if you accept it as a given
that data hiding is important.  The designers of Python don't really
think it is, and that's why they don't have it.


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


Re: strip() using strings instead of chars

2008-07-12 Thread Duncan Booth
Christoph Zwerschke <[EMAIL PROTECTED]> wrote:

> Duncan Booth schrieb:
>>> if url.startswith('http://'):
>>>  url = url[7:]
>> 
>> If I came across this code I'd want to know why they weren't using 
>> urlparse.urlsplit()...
> 
> Right, such code can have a smell since in the case of urls, file names, 
> config options etc. there are specialized functions available. But I'm 
> not sure whether the need for removing string prefix/suffixes in general 
> is really so rare that we shouldn't worry to offer a simpler solution.
> 

One of the great things about Python is that it resists bloating the 
builtin classes with lots of methods that just seem like a good idea at the 
time. If a lot of people make a case for this function then it might get 
added, but I think it is unlikely given how simple it is to write a 
function to do this for yourself.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a timer/scheduler in Python?

2008-07-12 Thread Daniel Fetchinson
> I need what I'd call (in .Net) a timer, ie I need to run a function eg
> every 2 seconds - it doesn't need to be millisec accurate but it would
> be nice if it wasn't eg every 4 seconds or something.
>
> Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer'
> or 'scheduler', which leaves me wondering whether this is an aspect of
> Python that isn't perhaps widely used?
>
> Looking around on the net I can see references to a thread timer, but
> I'm not really looking to start any new threads (I just want part of
> the GUI to update every 2 secs) and don't want to get into that sort
> of complication while still just learning Python.
>
> Is there really no simple timer/scheduler function available in
> Python?


You might want to look at scheduler.py from turbogears which is
exactly the tool you describe and luckily is 99.99% independent of
turbogears. I'd think you need to modify 1-2 lines:

http://svn.turbogears.org/tags/1.0.4.4/turbogears/scheduler.py

Cheers,
Daniel
-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bypassing WebFilter security

2008-07-12 Thread Daniel Fetchinson
>> >> I am working in an organization, which is using a very strict
>> >> webcontent filter management suite. Due to this i am unable to
>> >> download any exe file, or surf web (even the necessary downloads from
>> >> sourceforgenet are blocked). I was wondering, if python could be of
>> >> any help. Say i have a python script, and i pass the URL of
>> >> downloadable file, and it just downloads the file for me.
>>
>> > Nice try. Can I talk to your employer for a minute? :)
>>
>> > Honestly, the language doesn't make any difference here, and there isn't
>> > much
>> > you can do unless you control both sides, i.e. the server and the
>> > client.
>> > But
>> > I would suggest you actually talk to your employer yourself to see if
>> > there's
>> > an official way to get what you want.
>>
>> Yes, the language itself doesn't matter as long as you go through the
>> web. But if I were you I would use an ssh client to ssh to a remote
>> machine on which I have an account, download the file there to that
>> machine and scp it to the local machine. Assuming of course port 21 is
>> not blocked.
>>
>> In fact, this is something I do regularly for similar reasons :)
>>
>> Good luck,
>> Daniel
>> --
>> Psss, psss, put it down! -http://www.cafepress.com/putitdown
>
> Daniel, cool even i thought of the same thing, but you see, the
> assumption has no use in my case! It is also blocked, Anyways, i will
> talk to the system admins here. Thanks all

Wait, port 21 is the *incoming* ssh port, when you use a client to ssh
*out* you open a generic high port number. So that should work, you
ssh out, download, go back to your local machine and scp out to get
the file. On your local machine port 21 is not needed simply because
you don't run an ssh server.

Good luck,
Daniel
-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


why is "self" used in OO-Python?

2008-07-12 Thread ssecorp
I first learned about OO from Java.

I much prefer to program in Python though.

However I am consufed about 2 things.

1. Why do I have to pass self into every method in a class? Since I am
always doing why cant this be automated or abstracted away?
Are the instances where I won't pass self?
I imagine there is some tradeoff involved otherwise it would have been
done away with.

2. self.item instead of getters and setters. I thought one of the main
purposes of OO was encapsulation. Doesn't messing with internal object-
representations break this?
I see how the getters and setters could be just visual clutter and you
have to add them to every class so it is annoying a bit in the same
way as self described above.
However I feel like I want getters and setters when I write classes,
not sure of the advantages/disadvantages though.
Only looking at the documentation of a Python-class, will internal
representations be provided?

If I have a class:

class Stack(object):
def __init__(self, *items):
self.stack = list(items)

def append(self, item):
self.stack.append(item)

def pop(self):
return self.stack.pop()

I can get to see the stack with var.stack but then why even implement
append when I could do self.stack.append(x) etc.
That way you could do away with OO completely. So why let people
access the main attribute but not let them manipulate it?
Makes more sense to draw the line to not access any attributes at all
no?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused

2008-07-12 Thread Michael Torrie
eric.butteriss wrote:
> Please tell me why may mail is being returned. The message says I
> have been blacklisted...for what reason? I never open mail that I
> know is not expected and I never send junk or spam. I am trying to
> send important info to my cousin.

Now I'm confused.  Is the python mailing list blacklisting you?  Unless
this is a python-related thing, I doubt you'll find anyone here who can
help.

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


Why is this blowing the stack, thought it was tail-recursive...

2008-07-12 Thread ssecorp
def fib(n):
def fibt(a, b, n):
if n <= 1:
return b
else:
return fibt(b, a + b, n - 1)
if n == 0:
return 0
else:
return fibt(0, 1, n);


and can memoization speed up this even more? tesintg with memoization
doesnt really say anything because it is so fast it is instant anyway.


(the classic easy-redable exponential fib-function can obv be helped
enormously with memoization though.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: spam <[EMAIL PROTECTED]> <[EMAIL PROTECTED]>

2008-07-12 Thread WDC
On Jul 11, 7:21 pm, Nobody Here <[EMAIL PROTECTED]> wrote:
> rickman <[EMAIL PROTECTED]> wrote:
> > spam
>
> No fucking shit, Sherlock, why double the volume by pointing out the obvious?

Calm down you all.

BTW I reported it, yo should too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using the Random Module.

2008-07-12 Thread WDC
On Jul 12, 10:06 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote:
> > You want a random integer.  Is there a range you want it in?
>
> > Past a certain point, you'll exceed the granularity of the random number
> > generator, and some values in the range will never be generated.
>
> You might want to produce an unbounded random integer, where *every*
> integer has a chance to be returned:
>
> def unbounded_randint():
>     i = 0
>     while True:
>         if random.random() < 0.5:
>             return i
>         i += 1
>
> This returns 0 with probability 1/2, 1 with probability 1/4, 2 with
> probability 1/8, etc. The probability distribution is centered close to
> zero (the mode and median are both zero, and I'm too lazy to calculate
> the mean) and it has an infinitely long tail.
>
> --
> Steven

Thanks Steven. I like how that bit works.

No range in particular. I was just wondering if there was a better way
than what I had been doing. Thanks for help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone suggest a date peocedure...

2008-07-12 Thread RV
On Thu, 10 Jul 2008 20:04:27 -0400, RV <[EMAIL PROTECTED]> wrote:

Gary, Larry, Michiel ,

Thanks very much, your helpful info has enabled me to get past a
learning bump.  

Ron


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


Re: Weird lambda rebinding/reassignment without me doing it

2008-07-12 Thread Steven D'Aprano
On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote:

>> g = lambda x:validate(x)
> 
> This is doubly diseased.
> 
> First, never write a 'name = lambda...' statement since it is equivalent
> to a def statement except that the resulting function object lacks a
> proper .funcname attribute.

Using lambda in this way is no more "diseased" than aliasing any other 
object. It's a matter of personal preference not to bind a lambda to a 
name. Functions, whether created by lambda or def, are first class 
objects, and as such there's nothing wrong with binding them to names.

Admittedly, the lack of a func_name attribute can sometimes make 
tracebacks harder to understand, especially if you've got many bound 
lambdas. But that's no worse than this:

>>> def factory(n):
... def f():
... return "spam"*n
... return f
...
>>> one_spam = factory(1)
>>> two_spam = factory(2)
>>> one_spam.func_name == two_spam.func_name
True

I'm sure that nobody would argue that using factory functions is 
"diseased" because the functions have the same func_name attribute -- 
even if it does sometimes make it harder to interpret tracebacks:

>>> one_spam()
'spam'
>>> one_spam('arg')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: f() takes no arguments (1 given)


So by all means say that you personally don't like to bind lambdas to 
names, but don't pretend that it is somehow wrong to do so.



> Second, never write a function (with either def or lambda) that simply
> returns a function of the argument(s).

I think you need to reconsider the way you say that. By definition, 
*every* function simply returns a function of the arguments. That's what 
functions do.

> The wrapping does nothing!  This
> is a waste of time and space for both you and the interpreter.

When I was a newbie, I used to write:

def sin(x):
return math.sin(x)

That was before I learned to just do this:

sin = math.sin

But just to prove that you should never say never:

>>> import timeit
>>> T1 = timeit.Timer("f(1)", """def g(x):
... return x+1
...
... f = g
... """)
>>> T2 = timeit.Timer("f(1)", """def g(x):
... return x+1
...
... def f(x):
... return g(x)
... """)
>>>
>>> T1.repeat()
[0.50848197937011719, 0.54573416709899902, 0.54767107963562012]
>>> T2.repeat()
[0.88546991348266602, 0.89811587333679199, 0.95785093307495117]

So that's a good reason to wrap a function in another function -- to 
measure the overhead of a function call.

*wink*


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


Re: strip() using strings instead of chars

2008-07-12 Thread Christoph Zwerschke

Duncan Booth schrieb:

if url.startswith('http://'):
 url = url[7:]


If I came across this code I'd want to know why they weren't using 
urlparse.urlsplit()...


Right, such code can have a smell since in the case of urls, file names, 
config options etc. there are specialized functions available. But I'm 
not sure whether the need for removing string prefix/suffixes in general 
is really so rare that we shouldn't worry to offer a simpler solution.


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


Re: Converting from local -> UTC

2008-07-12 Thread Sebastian "lunar" Wiesner
Gabriel Genellina <[EMAIL PROTECTED]>:

> En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt
> <[EMAIL PROTECTED]> escribi�:
> 
>> I am having a little trouble figuring out how to convert a python
>> datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would
>> like to create a UTC date so that when I send it to MySQL (which
>> treats all dates at local dates by default), it will already have
>> incorporated the proper UTC offset. I've tried looking through the
>> docs http://python.active-venture.com/lib/datetime-datetime.html), but
>> have not had any luck.
> 
> You have to use a "timezone aware" datetime object. If all you want is to
> store an UTC date, the tzinfo demo classes that you can find in the Python
> docs at  may be enough.
> A more complete implementation is at 

The python-dateutil package also provide classes to deal with timezone-aware
datetime objects.  See 

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list

..\..\Python-2.5.2\Include\pyport.h(117) : fatal error C1189: #error : "Python needs a typedef for Py_ssize_t in pyport.h."

2008-07-12 Thread Bill Davy
When I try and compile using VS2003 for Release.  Compiles fine for Debug. 
In a hurry (should be gardening).  Any solution?

TIA
Bill 


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


Re: Perfect hashing for Py

2008-07-12 Thread Raymond Hettinger
On Jul 12, 10:13 am, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On Jul 11, 3:01 pm, [EMAIL PROTECTED] wrote:
>
> > I have found this perfect hash (minimal too) 
> > implementation:http://burtleburtle.net/bob/hash/perfect.html
>
> > I have already translated part of it to D, and it seems to work well
> > enough. As discussed in the PyConDue, I think this may be used in
> > frozenset (and frozendict) to build a (minimal too?) perfect hash on
> > the fly, to allow (hopefully) faster retrieval of items that don't
> > change.

I played around with the idea and have a rough implementation sketch:

class PerfectSet(collections.Set):
__slots__ = ['len', 'hashvalue', 'hashfunc', 'hashtable']
DUMMY = object()
def __init__(self, keys, sparseness=0.5):
keys = frozenset(keys)
self.len = len(keys)
self.hashvalue = hash(keys)
n = (len(keys) / sparseness) + 1
assert n > self.len
self.hashfunc = make_perfect_hash_function(keys, n)
self.hashtable = [self.DUMMY] * n
for k in keys:
self.hashtable[self.hashfunc(k)] = k
del __len__(self, k):
return self.len
def __iter__(self, k)
return (k for k in self.hashtable if k is not self.DUMMY)
def __contains__(self, k):
return self.table[self.hashfunc(k)] is not self.DUMMY

The perfect hash function will need to use the regular hash(obj) as a
starting point.  This helps with non-string types and it preserves
existing relationships between __hash__ and __eq__.

The construction is more expensive than with regular frozensets so it
is only useful when lookups are very common.

Playing around with the idea suggests that a sparseness variable for
frozensets would largely accomplish the same goal without the overhead
of creating and applying a perfect hash function.  Sparse hash tables
rarely collide.


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


Re: Using the Random Module.

2008-07-12 Thread Steven D'Aprano
On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote:

> You want a random integer.  Is there a range you want it in?
> 
> Past a certain point, you'll exceed the granularity of the random number
> generator, and some values in the range will never be generated.

You might want to produce an unbounded random integer, where *every* 
integer has a chance to be returned:

def unbounded_randint():
i = 0
while True:
if random.random() < 0.5:
return i
i += 1

This returns 0 with probability 1/2, 1 with probability 1/4, 2 with 
probability 1/8, etc. The probability distribution is centered close to 
zero (the mode and median are both zero, and I'm too lazy to calculate 
the mean) and it has an infinitely long tail.


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


Re: Confused

2008-07-12 Thread D'Arcy J.M. Cain
On Sat, 12 Jul 2008 14:06:37 +0200
"eric.butteriss" <[EMAIL PROTECTED]> wrote:
> Please tell me why may mail is being returned. The message says I have been 
> blacklisted...for what reason? I never open mail that I know is not expected 
> and I never send junk or spam. I am trying to send important info to my 
> cousin.

Well, the subject is accurate anyway.

The problem is that sometimes error messages can be misleading.  In
this case the problem appears that you have arrived too late and the
Internet is full.  Please turn off your computer and go outside.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a timer/scheduler in Python?

2008-07-12 Thread Marc 'BlackJack' Rintsch
On Sat, 12 Jul 2008 10:30:00 +0100, John Dann wrote:

> Looking around on the net I can see references to a thread timer, but
> I'm not really looking to start any new threads (I just want part of
> the GUI to update every 2 secs) and don't want to get into that sort
> of complication while still just learning Python.

Look into the GUI toolkit because that's typically something solved with
functions from the specific toolkit.

> Is there really no simple timer/scheduler function available in
> Python?

You can do that quite easily with threads but almost all GUI toolkits
don't like it if you access the GUI from multiple threads.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing self: if self is a tree how to set to a different self

2008-07-12 Thread Kay Schluehr
On 10 Jul., 15:19, Bart Kastermans <[EMAIL PROTECTED]> wrote:
> I am playing with some trees.  In one of the procedures I wrote
> for this I am trying to change self to a different tree.  A tree
> here has four members (val/type/left/right).  I found that self = SS
> does not work; I have to write self.val = SS.val and the same for
> the other members (as shown below).  Is there a better way to do this?
>
> In the below self is part of a parse tree, F is the parse tree of a
> function f with argument x.  If a node in the parse tree is labelled
> f, we should replace it by the parse tree for the function f, F, with
> the remainder of the tree substituted for the input variable for the
> function f, here x.
>
> def elimF (self):
> if self.val == "f":
> SS = F.copy ()
> SS.subst ('x', self.left)
> self.val = SS.val# from here: set self to be SS
> self.type = SS.type
> self.left = SS.left
> self.right = SS.right# completed: set self to be SS
>
> if self.left != None:# iterate onward, inf recursion if f
>  # appears.  Would need a check in
>  # real version
> self.left.elimF ()
> if self.right != None:
> self.right.elimF ()
>
> Best,
> Bart

Since it is acting on a tree why doesn't the code substitute self in
its parent by SS? That's the natural perspective if one considers a
tree as a linked structure and inserts and deletes nodes within this
structure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing self: if self is a tree how to set to a different self

2008-07-12 Thread Paul McGuire
On Jul 12, 6:18 am, Bart Kastermans <[EMAIL PROTECTED]
macbook.local> wrote:
> This uses the function:
>
> def NoneOr (tree, mem_function, *arguments):
>     """ if tree is not None then tree.mem_function (arguments). """
>     if tree == None:
>         return None
>     else:
>         return getattr (tree, mem_function) (*arguments)
>
> Bart


This code reads wrongly to me on a couple of levels.  First, I think
the general computing consensus is that if-then-else is more readable/
logical if you assert the positive condition for the then-part, and
put the alternative condition in the else-part.  My impression is that
the non-None-ness of tree is actually the positive assertion, as in:

if tree != None:
return getattr(tree, mem_function)(*arguments)
else:
return None

Next, the more Pythonic test for None-ness is most clearly written as:

if tree is not None:

as there is only one None, and the identity "is not" check is simpler/
faster for Python to execute (and possibly - and more importantly -
also simpler for readers to follow, as this reads more like a
continuous sentence instead of a mixture of prose and mathematical
notations).

One might even suggest you could further abbreviate this test to:

if tree:

and get the same behavior.  I would quibble with that, however, that
this merely exploits a side-effect of Python, in which None values are
always False, and *most* non-None values are True.  But Python also
interprets many non-None values as False, such as 0, or empty
containers, such as lists, tuples, dicts, and strings.  In fact, your
tree class sounds like a structured container to me, and it would be
reasonable to assume that you might implement __nonzero__ (pre-Python
2.6) or __bool__ (Python 2.6 and later) in your class to return False
for an empty tree, which would still be a valid and not-None tree.
You should be able to invoke methods on an empty tree just as one can
call "".upper().  So for this case, I would stick with the more
explicit "if tree is not None".

Another Pythonicity is that methods will *always* return a value, even
if you do not write a return statement - and that value is None.  So
if you assert the tree-not-None as the if condition, you don't even
need the else part.  You could just write:

def NoneOr (tree, mem_function, *arguments):
""" if tree is not None then tree.mem_function (arguments).
"""
if tree is not None:
return getattr(tree, mem_function)(*arguments)

Surprisingly, this actually reads almost verbatim from your doc
string!  So I would guess that this implementation is probably closest
to your original intent for this method.  Still, for explicitness'-
sake, you might want to keep the else-part, just to make your intent
clear and spelled-out.  (Complaining about the presence or absence of
this bit of code goes beyond "persnickety"...)


Note that the original code is perfectly valid Python, and will run
just as efficiently as any of my alternative suggestions, which is why
I enclosed my comments in 'persnickety' (http://
dictionary.reference.com/browse/persnickety) tags.

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


Re: Use of index

2008-07-12 Thread Michiel Overtoom
SUBHABRATA wrote...

> Now, my q is can we use index like find?

Yes, you can.  There is only a difference when the string is not found: the
'find()' function will return -1, whereas 'index()' function will raise a
ValueError exception.

For example:

>>> b="A spaghetti monster is always great"
>>> print "monster" in b
True
>>> print b.find("monster")
12
>>> print b.index("monster")
12
>>> print b.find("pasta")
-1
>>> print b.index("pasta")
Traceback (most recent call last):
  File "", line 1, in 
print b.index("pasta")
ValueError: substring not found
>>> 


This is also documented in the built-in help:

>>> help(b.index)
Help on built-in function index:

index(...)
S.index(sub [,start [,end]]) -> int

Like S.find() but raise ValueError when the substring is not found.


>>> help(b.find)
Help on built-in function find:

find(...)
S.find(sub [,start [,end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within s[start,end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

Hope this helps,

Greetings

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-12 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> Traceback (most recent call last):
>>   File "H:/Personal/OutlookIF1/t2.py", line 18, in 
>> outlook = win32com.client.gencache.EnsureDispatch 
>> ("Outlook.Application")
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 536, in EnsureDispatch
>> mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
>> bForDemand=bForDemand)
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 393, in EnsureModule
>> module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 262, in GetModuleForTypelib
>> AddModuleToCache(typelibCLSID, lcid, major, minor)
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 554, in AddModuleToCache
>> dict = mod.CLSIDToClassMap
>> AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>
>
> Just in case, could you delete the contents of your gen_py
> directory (probably in %TEMP%\gen_py)
>
> TJG



OK, Put the following ahead with the following results.

TempDir = os.getenv("TEMP");
WorkDir = TempDir + '\\gen_py'
print WorkDir
try:
  os.rmdir(WorkDir);
except  WindowsError, detail:
  print "Ignoring Windows error: ", detail

...

Result:


C:\DOCUME~1\Bill\LOCALS~1\Temp\gen_py
Ignoring Windows error:  [Error 2] The system cannot find the file 
specified: 'C:\\DOCUME~1\\Bill\\LOCALS~1\\Temp\\gen_py'

Traceback (most recent call last):
  File "H:\Personal\OutlookIF1\t2.py", line 26, in 
outlook = win32com.client.gencache.EnsureDispatch 
("Outlook.Application")
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
bForDemand=bForDemand)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>>>

So, although that directory did exist, it does not now (even after the 
program has run).

Any other ideas?

But many thnaks,
Bill 


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


Re: Python 3.0 and removal of the 'string' module

2008-07-12 Thread Colin J. Williams

Benjamin wrote:

On Jul 11, 3:06 am, Ben Finney <[EMAIL PROTECTED]>
wrote:

"Martin v. Löwis" <[EMAIL PROTECTED]> writes:


This is rather disappointing. Is that entire page suspect?

All documentation about Python 3 is suspect until Python 3 gets
actually released (nobody can say for sure how the release will
look like in all details).

Is there a better information source, then, for the current state of
what's expected in Python 3.0?


Look at the development docs. We try to keep them up to date:
http://doc.python.org/dev/3.0

--


It would be good if the PEP references 
in 'What's New' could be clickable.


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


Re: sending input to an embedded application

2008-07-12 Thread mefyl
Uwe Schmitt wrote:
> On 12 Jul., 09:08, George Oliver <[EMAIL PROTECTED]> wrote:
>> What I would like to do is take a program and embed it or put it
>> within a Python-run GUI, using the GUI just to capture and send input
>> to the application, and display the ouput.
> 
> Which interface does your interpreter provide ? Just commandline or
> can you access by other methods ?
> 
> http://sourceforge.net/projects/pexpect/ might help you
> 

Although Pexpect looks more advanced and complete, you might want to take a
look at popen* modules. It enables you to easily run a subprocess, feed him
data on stdin, retrieve output from stdout/stderr, and wait for its
completion.

http://docs.python.org/lib/module-popen2.html

-- 
mefyl
R&D engineer at Gostai - http://www.gostai.com

To understand recursion, you must first understand recursion.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with using findAll() in BeautifulSoup

2008-07-12 Thread Paul McGuire
On Jul 12, 12:55 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Alexnb wrote:
> > I am making an app that screen scapes
> > dictionary.com for definitions.
>
> Do they have a policy for doing that?
>

>From the Dictionary.com Terms of Use (http://dictionary.reference.com/
help/terms.html):

3.2 You will not modify, publish, transmit, participate in the
transfer or sale, create derivative works, or in any way exploit, any
of the content, in whole or in part, found on the Site. You will
download copyrighted content solely for your personal use, but will
make no other use of the content without the express written
permission of Lexico and the copyright owner. You will not make any
changes to any content that you are permitted to download under this
Agreement, and in particular you will not delete or alter any
proprietary rights or attribution notices in any content. You agree
that you do not acquire any ownership rights in any downloaded
content.

IANAL, but it seems pretty clear that, unless this content scraper is
"solely for your personal use," you'll need to get written permission
to include content that you have scraped from Dictionary.com into your
app.

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


Confused

2008-07-12 Thread eric.butteriss
Please tell me why may mail is being returned. The message says I have been 
blacklisted...for what reason? I never open mail that I know is not expected 
and I never send junk or spam. I am trying to send important info to my cousin.

Thank you in anticipation

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

Re: Changing self: if self is a tree how to set to a different self

2008-07-12 Thread Bart Kastermans
Terry Reedy <[EMAIL PROTECTED]> writes:

> Bart Kastermans wrote:
>> I am playing with some trees.  In one of the procedures I wrote
>> for this I am trying to change self to a different tree.  A tree
>> here has four members (val/type/left/right).  I found that self = SS
>> does not work; I have to write self.val = SS.val and the same for
>> the other members (as shown below).  Is there a better way to do this?
>>
>> In the below self is part of a parse tree, F is the parse tree of a
>> function f with argument x.  If a node in the parse tree is labelled
>> f, we should replace it by the parse tree for the function f, F, with
>> the remainder of the tree substituted for the input variable for the
>> function f, here x.
>>
>> def elimF (self):
>> if self.val == "f":
>> SS = F.copy ()
>> SS.subst ('x', self.left)
>> self.val = SS.val# from here: set self to be SS
>> self.type = SS.type
>> self.left = SS.left
>> self.right = SS.right# completed: set self to be SS
>
> If you examine nodes from their parent, I believe you can do the
> substitution in one step. Something like:
>
> for slot,child in ( ('left',self.left), ('right',self.right) ):
>   if child is not None:
> if child.val == 'f':
>   setattr(self, slot, F.copy().subst('x', child.left))
> child.elimF
>
> where .subst returns the modified tree.

That worked very well.  The option that looks even better to me was
just to build a copy (the exceptional case of the root of the tree
that is needed bugged me a bit).  Then self does not have to be
changed at all.  Your use of setattr made me find getattr, and this
allowed for a quite smooth (I think) implementation.

def elimF (self):
""" do the substitution of all nodes labelled f.

"""
if self.val == "f":
ret_val = F.subst ('x', self.left)
ret_val.left = NoneOr (ret_val.left, 'elimF')
ret_val.right = NoneOr (ret_val.right, 'elimF')
return ret_val
else:
return Tree (self.val, self.type, \
 NoneOr (self.left, 'elimF'), \
 NoneOr (self.right, 'elimF') )

This uses the function:

def NoneOr (tree, mem_function, *arguments):
""" if tree is not None then tree.mem_function (arguments). """
if tree == None:
return None
else:
return getattr (tree, mem_function) (*arguments)



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


Re: sending input to an embedded application

2008-07-12 Thread Uwe Schmitt
On 12 Jul., 09:08, George Oliver <[EMAIL PROTECTED]> wrote:
> hi, I'm a novice programmer trying to better define a hobby project
> I'm thinking of.
>
> What I would like to do is take a program and embed it or put it
> within a Python-run GUI, using the GUI just to capture and send input
> to the application, and display the ouput.
>
> Specifically I want to use a Python module such as wxPython, pygame or
> pyglet to build the UI, capture key presses, and then send a string to
> the program, an interactive fiction interpreter; the reason for this
> is that the interpreter on its own doesn't have the capability to
> recognize certain key presses on the keyboard. I thought that writing
> a middle layer rather than a brand new interpreter would be easier for
> someone of my skill level.
>
> The interpreter would send its output to the Python GUI. The GUI then
> would be as light/translucent as possible, just accepting input,
> sending it to the interpreter, and displaying the output as if you
> were just running the interpreter by itself.
>
> As I don't really know the issues involved, I'm hoping someone can
> point me in the right direction. Do people 'frame' programs with
> something like wxPython or pygame and use the frame to capture and
> pass along input, and receive and display the output?
>
> thanks, George

Which interface does your interpreter provide ? Just commandline or
can you access by other methods ?

http://sourceforge.net/projects/pexpect/ might help you

Greetings, Uwe
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a timer/scheduler in Python?

2008-07-12 Thread Uwe Schmitt
On 12 Jul., 11:30, John Dann <[EMAIL PROTECTED]> wrote:
> I need what I'd call (in .Net) a timer, ie I need to run a function eg
> every 2 seconds - it doesn't need to be millisec accurate but it would
> be nice if it wasn't eg every 4 seconds or something.
>
> Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer'
> or 'scheduler', which leaves me wondering whether this is an aspect of
> Python that isn't perhaps widely used?
>
> Looking around on the net I can see references to a thread timer, but
> I'm not really looking to start any new threads (I just want part of
> the GUI to update every 2 secs) and don't want to get into that sort
> of complication while still just learning Python.
>
> Is there really no simple timer/scheduler function available in
> Python?

The usual way is to use threads. Depending on you GUI lib there may
exist
replacements for threads, eg wxPython. As most (all ?) GUIs have some
event handling
mechanisms they should be able to schedule tasks and process them in
the
background.

By the way: Using threads in Python is quite simple, even if you are
a  novice.

Greetings, Uwe
--
http://mail.python.org/mailman/listinfo/python-list


Use of index

2008-07-12 Thread SUBHABRATA
Dear All,
I have a small question.
If I have code line like the following:

a1="God"
a2="God is always great"
a3=a2.index(a1)
a4=a2.find(a1)
a5=a2.split()
a6=a5.index(a1)
a7=a5.find(a1) # Invalid as find is applicable only in string but not
in list.
if a4>-1:
print "God may be always great"

--
Now, my q is can we use index like find?

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


Re: Help with BeautifulSoup

2008-07-12 Thread Michiel Overtoom
Alex wrote...
>
>Okay, heres the general idea of the html I have to work with:
>
>
>   noun
>   
>   
>   
>   
>   verb
>   
>   
>   
>
>
>Okay, I left off some stuff. 

I wish you didn't, or at least provided an URL where I can get the page
which you are trying to parse.  Now I don't have a valid testcase to tinker
with.  And maybe you can also show your code which you already came up with.


> I can easily get the tables but it is the span's than I am having trouble
with. 

I can't see any SPAN tags in the example you provided.

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


How to create a timer/scheduler in Python?

2008-07-12 Thread John Dann
I need what I'd call (in .Net) a timer, ie I need to run a function eg
every 2 seconds - it doesn't need to be millisec accurate but it would
be nice if it wasn't eg every 4 seconds or something.

Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer'
or 'scheduler', which leaves me wondering whether this is an aspect of
Python that isn't perhaps widely used?

Looking around on the net I can see references to a thread timer, but
I'm not really looking to start any new threads (I just want part of
the GUI to update every 2 secs) and don't want to get into that sort
of complication while still just learning Python.

Is there really no simple timer/scheduler function available in
Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: decorator to prevent adding attributes to class?

2008-07-12 Thread rbossy
>> class Foo(Freezeable):
>> def __init__(self):
>> self.bar = 42
>> self.freeze() # ok, we set all variables, no more from here
>>
>>
>> x = Foo()
>> print x.bar
>> x.bar = -42
>> print x.bar
>> x.baz = "OMG! A typo!"
>>
>
>Pretty nice, but unfortunately the subclass has to remember to call freeze
>in it's init.  Too bad that can't be automated.

Not to mention that subclasses constructors could be bit, like that:

class Foo(Freezeable):
...

class Bar(Foo):
def __init__(self, *args, **kw):
Foo.__init__(self, *args, **kw)
self.something_bar = 42 # this should raise AttributeError


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


Re: MySQLdb will only import for root

2008-07-12 Thread martinnorth

Peter Otten wrote:

martinnorth wrote:


Hi,

I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I
try to import MySQLdb I get the following error:

ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08)
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import MySQLdb
Traceback (most recent call last):
   File "", line 1, in 
ImportError: No module named MySQLdb

But if I lrun python as the root user it imports fine. Can anyone
suggest what might be wrong with the installation? Or is there nothing
wrong? I haven't seen any examples that mentioned being root to import a
module.


You have probably installed two versions of Python. You can verify that by
typing

$ which python

and

$ sudo which python

I suspect that root sees the python that comes with Ubuntu and that has
MySQLdb installed while the normal user sees ActiveState's Python. 


Peter



Thanks Peter, that was it. Located the ActiveState directory and removed 
it. Now the module imports for all users.


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


Re: variable question

2008-07-12 Thread Peter Otten
happy wrote:

> I think its better to leave the "teach kiddies" tutoring opportunity
> for the python experts out there.

If you know how to make some simple scripts that do something that kids find
interesting and are able to convey your enthusiasm, you are better suited
to teach than any expert who tortures them with explanations of how a
variable is not a name is not a pointer.

Peter

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


Re: variable question

2008-07-12 Thread happy
On Jul 12, 8:05 am, Robert Lehmann <[EMAIL PROTECTED]> wrote:
> On Fri, 11 Jul 2008 20:13:04 -0700, happy wrote:
> > Can a variable be considered the simplest of the data structures. I am
> > tutoring some kids about basics of programming using python. Not an
> > expert in computer sciences, but am a python enthusiast.
>
> Why do you need this additional layer of indirection? Just explain the
> real simple data structures à la "look, kids, a string is a chain of
> characters which are bytes actually.  etc. here>". Although explaining encodings is an *important* thing (which
> many programmers still get wrong), it might be second priority to kids
> and you might just want to say "a string is text" and jump into higher-
> order data structures.
>
> > I wanted to know if it is correct to say a variable is a data structure,
> > it has a name and a value.
>
> Not at all. This sounds a lot like an explanation for variables in other
> languages (such as C, where the value also has a type). In Python, we use
> to speak of "names," not variables. They are more like name tags you can
> put on objects -- or you don't. Depending on the age/interest of your
> students, I'd insert an explanation about references, reference counting
> and garbage collection here (they usually find that quite understandable
> and it paves the way for The Real Stuff, even though you might argue that
> the refcounting gc is a CPython detail and might become obsolete with
> PyPy's rise ).
>
> The important thing is really that Python's approach of references is
> nearly orthogonal to the common approach of variables. In other
> languages, variables are (as you described above) containers (a bucket,
> really!) in your memory where you can put stuff into. Assignment is
> usually a copy or pointer operation.
> Python does not care at all about your memory. You have abstract objects
> (incidentally saved in your memory, okay) with names being one mechanism
> to reference them. Here, assignment is always a "put the left-hand side
> name tag onto the right-hand side object".
>
> > Put a stack of variables in a special data
> > structure called a dictionary where the each name associates to a value.
> > If in a data structure, one uses numbers starting from 0 to describe the
> > name, it becomes a list and  so forth
>
> First off, you really put objects in your data structures. Names are a
> one-way mapping -- the object does not know which name tags are assigned
> to it.
>
> Your explanation of dictionaries and lists sounds a little bit upside-
> down (not the mapping name->value or number->value makes it a dict or
> list -- the data structure makes it a mapping with this and that
> behaviour).
>
> HTH,
>
> --
> Robert "Stargaming" Lehmann

Thanks for the reply.
I think its better to leave the "teach kiddies" tutoring opportunity
for the python experts out there.
Would "python experts" have an appetite for newbies and "kiddies"?
Only time will tell...
I must really focus on learning the language better.

"Look kids, you will learn it when you grow up... Now get out of
here..."
--
http://mail.python.org/mailman/listinfo/python-list


Re: Perfect hashing for Py

2008-07-12 Thread Raymond Hettinger
On Jul 11, 3:01 pm, [EMAIL PROTECTED] wrote:
> I have found this perfect hash (minimal too) 
> implementation:http://burtleburtle.net/bob/hash/perfect.html
>
> I have already translated part of it to D, and it seems to work well
> enough. As discussed in the PyConDue, I think this may be used in
> frozenset (and frozendict) to build a (minimal too?) perfect hash on
> the fly, to allow (hopefully) faster retrieval of items that don't
> change.

A few thoughts:  Objects currently have their own hash function that
is independent of a given container.  We also have to hash types other
than strings (used in the examples in the links you provided).  While
a container such as a dict or set is being built, we don't even know
how many unique keys there are until the container is fully
populated.  Set-to-set operations and set-to-dict operations get their
speed from knowing that both containers use the same hash values --
this would get disrupted if each container had its own hash function.
Some types like strings (especially interned strings) remember their
own hash value -- this makes it very fast to look their values in a
set or dict -- that would be defeated if each container has its own
hash function which would need to be recomputed for every lookup.  An
important use case for sets is uniquification -- in that use case,
speed is determined by insertion time, we just don't care about
subsequent lookup time -- anything that slows down insertion (such as
computing a perfect hash value) works to the detriment of that use
case).  In the current design, sets and dicts are never more than 2/3
full and are usually much more sparse than that -- accordingly lookups
average between 1 and 1.5 probes per lookup.  This is somewhat hard to
beat with perfect hashing since we typically get very few collisions
anyway -- so you get the cost of increased insertion time, loss of
objects being able to remember their own hash, challenges with non-
string keys, a more complicated algorithm, and decreased
interoperability for set-to-set and set-to-dict options -- the only
benefits are to reduce collisions to zero when they are already not
that common.

For frozensets, it may be possible to add an optimize() method that
takes a completely built frozenset and optimizes its insertion order
and/or increases its size to make it arbitrarily sparse.  That would
only be useful for cases when the costs of optimizing the table is
fully repaid by an extensive number of lookups.  There are use some
cases where it would be pay table optimization costs in order to win
decreased lookup costs, but there are plenty of use cases where that
would not be a winning trade-off.  So, the optimize() step would need
to be optional, not builtin.


Raymond

FWIW, I mentioned all this at PyConDue but the message must have
gotten lost.

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


Re: palindrome function

2008-07-12 Thread Denis Kasak

Peter Otten wrote:

Denis Kasak wrote:


Basically, it reverses the list in place, so it modifies the list which
called it. It does not return a /new/ list which is a reversed version
of the original, as you expected it to. Since it doesn't return anything
explicitly, Python makes it return None. Hence, the comparison you are
doing is between the original list and a None, which is False, naturally.
Try this:

spam = ['a', 'n', 'n', 'a']
eggs = spam[:]
if spam.reverse() == eggs:
print "Palindrome"


Your explanation is correct, but your example code compares None to
['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either.


Of course. Thank you for the correction. I guess you know your caffeine 
has started to wear off when you start making the same mistakes you were 
trying to fix. :-)


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


sending input to an embedded application

2008-07-12 Thread George Oliver
hi, I'm a novice programmer trying to better define a hobby project
I'm thinking of.

What I would like to do is take a program and embed it or put it
within a Python-run GUI, using the GUI just to capture and send input
to the application, and display the ouput.

Specifically I want to use a Python module such as wxPython, pygame or
pyglet to build the UI, capture key presses, and then send a string to
the program, an interactive fiction interpreter; the reason for this
is that the interpreter on its own doesn't have the capability to
recognize certain key presses on the keyboard. I thought that writing
a middle layer rather than a brand new interpreter would be easier for
someone of my skill level.

The interpreter would send its output to the Python GUI. The GUI then
would be as light/translucent as possible, just accepting input,
sending it to the interpreter, and displaying the output as if you
were just running the interpreter by itself.

As I don't really know the issues involved, I'm hoping someone can
point me in the right direction. Do people 'frame' programs with
something like wxPython or pygame and use the frame to capture and
pass along input, and receive and display the output?


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