mail sending using telnet in python

2005-07-07 Thread praba kar
Dear All,
  Normally we can send mail using
telnet in linux. In the following way
[~user]telnet Ipaddress 25
mail from: [EMAIL PROTECTED]
250 o.k(response of from commandline)
rcpt to: [EMAIL PROTECTED]
250 o.k(response of from commandline)
data
354 go ahead(response of from commandline)
Hello world(message to send)
.
250 ok 1120805818 qp 1463

Is it possible to run same thing same manner
in python?  If possible kindly help me with
specimen code.  Actually I gone through
telnetlib module documentation but I cann't
get solution for it.

regards
prabahar







__
Free antispam, antivirus and 1GB to save all your messages
Only in Yahoo! Mail: http://in.mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-07 Thread Ron Adam
Steven D'Aprano wrote:

> Ron Adam wrote:

>> def count_records(record_obj, start=0, end=len(record_obj)):
> 
> 
> That would work really well, except that it doesn't work at all.

Yep, and I have to stop trying to post on too little sleep.


Ok, how about... ?


def count_records(record_obj, start=0, end='to-end'):
 if end == 'to-end':
 end = len(record_obj)
 n = 0
 for rec in record_obj.data[start:end]:
 if not rec.isblank():
 n += 1
 return n


This isn't really different from using None. While it's possible to 
avoid None, its probably not worth the trouble.  I use it myself.


Here's something interesting:

import time

x = None
t = time.time()
for i in range(100):
 if x==None:
 pass
print 'None:',time.time()-t

x = 'to-end'
t = time.time()
for i in range(100):
 if x=='to-end':
 pass
print 'String:',time.time()-t

 >>>
None: 0.4673515
String: 0.36133514


Of course the difference this would make on a single call in practically 
Nill.

Anyway, time to call it a night so tomorrow I don't make anymore silly 
mistakes on comp.lang.python. :)

Cheers,
Ron

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Christopher Subich
Ron Adam wrote:
> Christopher Subich wrote:
> 
>> As others have mentioned, this looks too much like a list 
>> comprehension to be elegant, which also rules out () and {}... but I 
>> really do like the infix syntax.
> 
> 
> Why would it rule out ()?

Generator expressions.  Mind you, Py3k might want to unify generators 
and lists in some way anyway, freeing up (). :)

> 
> You need to put a lambda express in ()'s anyways if you want to use it 
> right away.
> 
>  print (lambda x,y:x+y)(1,2)

Although print (1,2) has natural grouping: the lambda 
itself is effectively a single token.  I also like the infix style 
reminiscent of Python's existing comprehensions.

Hell, call it a 'function comprehension' or 'expression comprehension,' 
and we can pretend we invented the damn thing.

> My choice:
> 
> name = (let x,y return x+y)   # easy for beginners to understand
> value = name(a,b)
> 
> value = (let x,y return x+y)(a,b)

And a zero-argument lambda is (aside from really arcane)?
(let return 2)?

> I think the association of (lambda) to [list_comp] is a nice 
> distinction.  Maybe a {dictionary_comp} would make it a complete set. ;-)

Yeah, dictionary comprehensions would be an interesting feature. :) 
Syntax might be a bit unwieldy, though, and I doubt they'd be used often 
enough to be worth implementing, but still neat.
-- 
http://mail.python.org/mailman/listinfo/python-list


python nested class

2005-07-07 Thread Vedanta Barooah
greetings

in a python nested class is it possible to change the value of the
parent class's variable without actually creating an instance of the
parent class, consider this code:

class mother:
x=0
def __init__(self):
self.x=1
def show(self):
print self.x
class child:
def increase(self,num):
# mother.increase=num
o = mother()
o.show()
y=mother.child()
y.increase(20)
# this should print 20
o.show()

. is it possible somehow ???

thanks and regards,
vedanta
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Bengt Richter
On Thu, 07 Jul 2005 22:04:31 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:

>[EMAIL PROTECTED] (Bengt Richter) writes:
>
>> On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>>
>>>[EMAIL PROTECTED] (Bengt Richter) writes:
>>>
 On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> 
 wrote:

>I'm trying to implement __iter__ on an abstract base class while I don't
>know whether subclasses support that or not.
>>>
 Will a property or custom descriptor do what you want? E.g.

  >>> class Base(object):
  ... def __getIter(self):
  ... if hasattr(self, "Iterator"):
  ... return self.Iterator
  ... raise AttributeError, name
  ... __iter__ = property(__getIter)
>> [...]
>>>
>>>Yep, that's exactly what I need - thanks.
>>>
>> BTW, I forgot to mention that you could use property as a decorator
>> in the above single-argument case:
>>
>>  >>> class Base(object):
>>  ... @property
>>  ... def __iter__(self):
>>  ... if hasattr(self, "Iterator"):
>>  ... return self.Iterator
>>  ... raise AttributeError, name
>
>Of course.  I didn't spot this, but I cannot use this anyway for 2.3
>compatibility.
>
>>  ...
>>  >>> class Concrete(Base):
>>  ... def Iterator(self):
>>  ... yield 1
>>  ... yield 2
>>  ... yield 3
>>  ...
>>  >>> iter(Base())
>>  Traceback (most recent call last):
>>File "", line 1, in ?
>>  TypeError: iteration over non-sequence
>>  >>> iter(Concrete())
>>  
>>  >>> list(iter(Concrete()))
>>  [1, 2, 3]
>>
>> Hope there isn't a gotcha for your use case in the way an instance attribute
>> of the same name is allowed. A custom descriptor could eliminate that.
>>
>>  >>> inst = Concrete()
>>  >>> list(iter(inst))
>>  [1, 2, 3]
>>  >>> inst.__init__ = 'abc'
>>  >>> list(iter(inst))
>>  [1, 2, 3]
>>  >>> inst.__init__
>>  'abc'
>
>I don't understand what you mean here.  A __iter__ instance attribute?
>
Yes, but it seems very unlikely to cause a problem, especially since iter(inst)
bypasses it, as you probably would want. In other words, never mind ;-)

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


Re: Use cases for del

2005-07-07 Thread Steven D'Aprano
Ron Adam wrote:

> Steven D'Aprano wrote:
>> Er, maybe I'm misunderstanding something here, but surely the most 
>> obvious case is for default and special function arguments:
>>
>> def count_records(record_obj, start=0, end=None):
>> if end == None:
>> end = len(record_obj)
>> if start == None:  # this is not the default!
>> # start at the current position
>> start = record_obj.current
>> n = 0
>> for rec in record_obj.data[start:end]:
>> if not rec.isblank():
>> n += 1
>> return n

[snip]

> You have three possible outcomes,
>count all
>count range
>count using current index
>count range from beginning to current
>count range from current to end

That makes four outcomes by my count.

> The most consistent way to do this would be:
> 
> def count_records(record_obj, start=0, end=len(record_obj)):

That would work really well, except that it doesn't 
work at all.

At the time the function is defined, record_obj doesn't 
exist, so there is no way of telling what it's length 
will be when the function is called. Here is a simpler 
example showing the problem:

py> def func(s, start=0, end=len(s)):
... return s[start:end]
...
Traceback (most recent call last):
   File "", line 1, in ?
NameError: name 's' is not defined

The only way this strategy works is if there is a 
global variable s which defines a __len__ method. But 
then the default value of end will be fixed to the 
length of that global for all time (or at least until 
the module is reloaded).

So given a pre-existing global variable, you get a 
class of hard-to-debug bugs:

py> s = [0, 1, 2, 3]
py> def func(s, start=0, end=len(s)):
... return s[start:end]
...
py> func("function", start=1, end=5) # works correctly
"unct"
py> func("ant") # default works correctly here
"ant"
py> func("function") # default is broken here
"func"
py> s = "antidisestablishmentarianism"
py> func(s) # default is broken even when s changed
"anti"



-- 
Steven.

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


urllib2 - basic authentication and the put and delete methods

2005-07-07 Thread news.corp.adobe.com
I need to perform basic authentication and I also need to be able to use the 
put and delete methods to copy files / delete files on a server.

Here is how I successfully perform basic authentication to read a page:

import urllib2, os, base64

os.system("cls")

theurl = 'http://myurl.com:9090/ESG/en_US/GLtest/'
username = 'myusername'
password = 'mypassword'

req = urllib2.Request(theurl)

realm = 'Apache Tomcat/4.1.27'

base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)

handle = urllib2.urlopen(req)

thepage = handle.read()

print thepage


But despite much searching, I have yet to discover how to then use PUT and 
DELETE to copy files / delete files on the server.



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


Re: Polling, Fifos, and Linux

2005-07-07 Thread Jacob Page
Jeremy Moles wrote:
> This is my first time working with some of the more lower-level python
> "stuff." I was wondering if someone could tell me what I'm doing wrong
> with my simple test here?
> 
> Basically, what I need is an easy way for application in userspace to
> simply echo values "down" to this fifo similar to the way proc files are
> used. Is my understanding of fifo's and their capabilities just totally
> off base?

You shouldn't need to use select.poll(), unless I'm missing something. 
I was able to get the following to work:

-=-=-

import os

fifo = os.open("fifo", os.O_RDONLY | os.O_NONBLOCK)

while True:
 string = os.read(fifo, 1)
 if len(string):
 print string
 # Perhaps add a delay under an else

-=-=-

The Python script, when run, does nothing until you put data into the 
fifo from another process.  Then it immediately spits the data out, 
character by character.

I'm assuming that you've already created the fifo and that it's in the 
current working directory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Erik Max Francis wrote:
> Ron Adam wrote:
> 
>> Well in my previous explanation I *mean* it to be empty parenthesis.
>>
>> Does that help?
> 
> 
> Maybe it might be beneficial to learn a little more of the language 
> before proposing such wide-reaching (and un-Pythonic) reforms?

Hi Erik,

Getting more sleep is the answer to not making those kinds of oversights 
in this case.

It's really was not a (my) proposal, but a suggestion someone else made. 
  It seemed like an interesting idea and I wanted to see what kind of 
problems and benefits it would have.  Discussing an idea with other 
before it's fully thought out is a good way to explore its possibilities 
even though it may mean appearing silly at times, which I don't mind. :)

In the previous posts I was attempting to show a possible pattern or 
logic which doesn't currently correspond to the languages syntax using 
parenthesis.

 >>> (None)
 >>>

That's as close to an empty parenthesis as Python gets.  I was really 
trying to explain an underlying concept, not show actual python code.

And the conclusion (opinion) I've come to, is such a change might be 
made to work, but it would be very confusing to most people who have 
gotten use to the current None usage.  And difficult to emplement in a 
way that's consistant overall.

An alternative is to use a different word such as 'undefined'.  Then 
None can be used as it is currently, and undefined, can be used to test 
for in a comparison for undefined names.  Assigning a name to undefined 
could be used as an alternative to delete a name but so far I don't see 
an advantage to doing that way over using del.



if name is undefined: do something.

Instead of:

try:
   name
except:
   do something


And maybe:

 name = undefined

can be used in expressions where del name can't?

But so far this doesn't seem useful enough to propose and it would 
probably cause more problems (or confusion) than it solves.

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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Mike Meyer
"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I'll clarify. A lot of the time I hear arguments against
> features that boils down to.

It seems that you've lost some of the intent during the boiling.

> 1) I don't need it.

Is that what you get out of the oft-used "What's your use case"?
That's an attempt to find out what problem the proposer thinks the
feature would help solve, so said solution can be evaluated in
comparison to possible existing solutions.

> 2) Having the feature will make my job more difficult.

Well, if the job is "writing programs" or "debugging programs", then
that's a *good* reason for not adding the feature. Those jobs are hard
enough as it is. Any feature that makes them noticably harder needs to
provide some serious advantages in order to be justified.

> 3) I don't understand the merrits of the feature or I
>   have difficulty understanding what it does when I
>   encounter it.

I don't think I've seen the first one used as an argument against a
feature. I may well have missed them, as I don't follow all such
discussion completely. The second one is a variation on #2, above.

Adding features just because they are "cool" is not the right way to
grow a language. New features need to enhance the language in a
clearly positive manner, while having as little negative impact as
possible. Point 1 and the first part of 3 are cases of people who
don't see a real enhancement to the language. Point 2 and the second
part of 3 are cases where people see a serious negative impact from a
feature.

When people *quit* pointing out those kinds of problems with
proposals, then I'll be worried. Python will be on it's way to
becoming Perl 6 or Common LISP, rather than the powerful, elegant
language I've come to love.

Bringing up such objections also gives the proposer a chance to
correct the problem, which is to everyones advantage. Witness the
recent (short) discussion of adding dynamically scoped variables. As
originally proposed, they can produce very obscure and hard-to-find
bugs. The fix for this made them no worse than global variables.

> IMO these are arguments if followed sufficiently will lead to
> a language that is only usefull for mediocre programmers.

Unless you're arguing that Python is already a language that is only
usefull for mediocre programmers, then this is sort of moot. Those are
arguments being advanced against *adding* features, not for removing
them (at least, I don't think I saw any of them in the ongoing
discusion re map/filter/reduce/lambda). Or are you arguing that Python
will somehow become less useful as new features are proposed and
rejected?

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you program in Python?

2005-07-07 Thread Mike Meyer
Jorgen Grahn <[EMAIL PROTECTED]> writes:
> Hey, it's not fair to make fun of emacs now that I've mentioned vim
> favourably so many times ;-)
>
> Seriously, nothing about emacs seems big or slow today. It has been
> outbloated by pretty much everything else. Who could have imagined /that/
> ten years ago?

Actually, it hasn't. Then again, maybe it depends on how you use it. I
start an xemacs at login, and leave it running forever. Just like I do
a shell. It slowly accretes buffers as time goes by, many of them
useless (why do I need to keep traces of 14 POP sessions around?).

As a result, xemacs is usually the second biggest thing on my system

I treat most programs that way. I never exit them, just unmap them.
My WM is configured to map a single existing window, launch the
application if there is no existing window, or offer a menu of windows
if there's more than one existing window when I ask for an
application. So I tend to have a lot of old, big processes on the
system. And xemacs is usually bigger than everything but X.

And people wondered when I complained that Mac OS 9 and Windows 98
crashed a lot :-).

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Win32 API) callback to Python, threading hiccups

2005-07-07 Thread Tim Roberts
Scott David Daniels <[EMAIL PROTECTED]> wrote:

>Francois De Serres wrote:
>>PyGILState_STATE gil = PyGILState_Ensure();
>>result = PyEval_CallObject(my_callback, arglist);   
>>PyGILState_Release(gil);
>>Py_DECREF(arglist);
>>Py_DECREF(result);
>
>I think this should be:
>  PyGILState_STATE gil = PyGILState_Ensure();
>  result = PyEval_CallObject(my_callback, arglist);
>  Py_DECREF(arglist);
>  Py_DECREF(result);
>  PyGILState_Release(gil);
>
>The DECREFs need to be protected, that is where storage is
>recycled and such, and you still need Python's data structures
>to do that kind of work.

I freely admit to being woefully underinformed about the GIL, but I'm
wondering if your statement is really true.  If the purpose of the GIL is
simply to make things thread-safe, then I would have guessed that the first
one was correct.  If someone else holds a reference to "arglist", then the
DECREF is just a nice, atomic decrement.  If no one else holds a reference
to "arglist", then it's quite safe to delete it.

Is there more to the GIL than I'm assuming?
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about introspection using inspect module

2005-07-07 Thread Mike Meyer
Benjamin Rutt <[EMAIL PROTECTED]> writes:
> what I am actually trying to do is to build a database of Python
> modules.  so then later, I can write a tool in my favorite editor
> (Emacs) to invoke some forms of completion against this database
> (e.g. os.remov or socket. to see a list of all socket module
> definitions).

The problem with that is that Python is dynamic, so the list of
completions may change over time. Not very likely, I know, but still...

Have you considered writing this tool in Python, with Pymacs http://pymacs.progiciels-bpi.ca/ >? That way, you could get the list
at runtime with a  dir(module).

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f*cking re module

2005-07-07 Thread Mike Meyer
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> On Thu, 07 Jul 2005 06:47:54 -0400, Chris Smith wrote:
>> Oh, come on:  what's a Perliodic Table of Operators, between friends?
>> http://www.ozonehouse.com/mark/blog/code/PeriodicTable.html
> That, and the discussion on operators by Larry Wall, are two of the most
> scary things I've ever seen. Is there any possible sequence of bytes that
> will not be a valid Perl expression or operator?

Yes, but will it get as bad as TECO, where guessing what your name did
as a command sequence was a popular past time?

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Polling, Fifos, and Linux

2005-07-07 Thread Jeremy Moles
This is my first time working with some of the more lower-level python
"stuff." I was wondering if someone could tell me what I'm doing wrong
with my simple test here?

Basically, what I need is an easy way for application in userspace to
simply echo values "down" to this fifo similar to the way proc files are
used. Is my understanding of fifo's and their capabilities just totally
off base?

I've implemented something very similar in the past in C which works
fine; however, this app immediately takes up 100% of my CPU after the
first read from the fifo, regardless of whatever options I pass to
os.open(). Am I not actually reading the data out of the fifo? Is that
what's causing it to poll infinite thereafter?

Any help would be greatly appreciate, though I'll keep reading and
experimenting in the meantime.

#!/usr/bin/env python

import select
import os

poller = select.poll()
fifo   = os.open("fifo", os.O_RDONLY | os.O_NONBLOCK)

poller.register(fifo, select.POLLIN)

while True:
p = poller.poll()
# only have one file
string = os.read(p[0][0], 1)
if len(string):
print string

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


Re: calling python procedures from tcl using tclpython

2005-07-07 Thread chand
Hi.,

can anyone help me how to provide the info about the python file
procedure in the tcl script which uses tclpython i.e., is there a way
to import that .py file procedure in the tcl script


--BestRegards
--Chandra

Michael Schlenker wrote:
> chand wrote:
> > Hi..
> >
> > I am writing a Gui in TCL and my backend code is python. I want to call
> > python procedure in tcl using tclpyhton. I want to know clearly how
> > this should be implemented.
> >
> > let's say I have procedure test_function(arg1,arg2 ...) defined in
> > test.py.
> > I want to call this procedure in tcl. Let me know how this should be
> > achieved.
> > The doubt basically have is how the tcl code knows in which .py file
> > this procedure is defined.
> >
> > currently I have wriiten this tcl code which is not working
> >
> > package require tclpython
> > set interpreter [python::interp new]
> > $interpreter eval {def test_function(): arg1,arg2} ;
> > python::interp delete $interpreter
> >
> What does not work? You never load your file test.py anywhere inside,
> you just evaluate 'def test_function(): arg1,arg2' so what are you
> expecting to happen?
>
> Your call to '$interpreter eval' lets you call arbitrary python code,
> but you have to provide the python code that loads your function
> definitions etc. I don't know python, but it should be a trivial code.
> 
> Michael

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


Integrating a wx.App to a Panel (elegantly)

2005-07-07 Thread flamesrock
Perhaps one of you more experience wxPythoners can assist me.

I have two seperate programs and basically I want to integrate program
2, which inherits from wx.App to a wx.Panel on the original program.

Is there an elegant way to do this without carefully surgically
inserting wx.App 2 into wx.App 1?



(BTW wx.App 2 is this program:
http://www.simcitysphere.com/simnet/downloads/irc.py
which I adapted from
http://www.intertwingly.net/stories/2003/09/15/
for wxPython 2.6.0)

-thanks in advance for any help

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Erik Max Francis
Ron Adam wrote:

> Well in my previous explanation I *mean* it to be empty parenthesis.
> 
> Does that help?

Maybe it might be beneficial to learn a little more of the language 
before proposing such wide-reaching (and un-Pythonic) reforms?

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   But since when can wounded eyes see / If we weren't who we were
   -- Joi
-- 
http://mail.python.org/mailman/listinfo/python-list


Berkely DB – many writers, many rea ders

2005-07-07 Thread Andy Leszczynski


I need to now option I open the Berkley DB (both db and env) to have 
configuration for multiple writers and multiple readers.  Via multiple 
processes  and multiple threads. No trx needed.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Erik Max Francis wrote:

> Ron Adam wrote:
> 
>> It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
>> would be.
>>
>> (a,) == (,)
>>
>> which would be the same as:
>>
>> (,) == (,)
> 
> 
>  >>> ()
> ()
>  >>> a = ()
>  >>> type(a)
> 
>  >>> (,)
>   File "", line 1
> (,)
>  ^
> SyntaxError: invalid syntax
> 
> You've wandered way off into the woods now.

Yes,  ummm seems soo...  err.

This is one of those Python isn't quite consistent for practical reasons 
area.  I don't create empty tuples that way very often, but [] is to () 
is to {} is pretty obvious so I don't really have a good excuse.

 >>> (1)
1
 >>> ()
()

 >>> (1)
1
 >>> ((()))
()

Well in my previous explanation I *mean* it to be empty parenthesis.

Does that help?

Cheers,
Ron


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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Christopher Subich wrote:

> As others have mentioned, this looks too much like a list comprehension 
> to be elegant, which also rules out () and {}... but I really do like 
> the infix syntax.

Why would it rule out ()?

You need to put a lambda express in ()'s anyways if you want to use it 
right away.

  print (lambda x,y:x+y)(1,2)

If you don't use the ()'s it reads the y(1,2) as part of the lambda 
expression, might as well require the ()'s to start with rather than 
leave it open for a possible error.


You could even say () is to function as [] is to list.

a function :  name(args)  ->  returns a value

a list :  name[index] ->  returns a value



My choice:

 name = (let x,y return x+y)   # easy for beginners to understand
 value = name(a,b)

 value = (let x,y return x+y)(a,b)



I think the association of (lambda) to [list_comp] is a nice 
distinction.  Maybe a {dictionary_comp} would make it a complete set. ;-)

Cheers,
Ron













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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Erik Max Francis
Ron Adam wrote:

> It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
> would be.
> 
> (a,) == (,)
> 
> which would be the same as:
> 
> (,) == (,)

 >>> ()
()
 >>> a = ()
 >>> type(a)

 >>> (,)
   File "", line 1
 (,)
  ^
SyntaxError: invalid syntax

You've wandered way off into the woods now.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   But since when can wounded eyes see / If we weren't who we were
   -- Joi
-- 
http://mail.python.org/mailman/listinfo/python-list


Ann: The first PyWeek Python Game Programming Competition

2005-07-07 Thread pyweek1
The date for the first PyWeek challenge has been set: Sunday 28th August
to Sunday 4th September (00:00UTC to 00:00UTC). The PyWeek competition:

- Invites all Python programmers to write a game in one week from scratch
  either as an individual or in a team,
- Is intended to be challenging and fun,
- Will hopefully increase the public body of python game tools, code and
  expertise,
- Will let a lot of people actually finish a game, and
- May inspire new projects (with ready made teams!)

Entries must be developed during the competition, and must incorporate some
theme decided at the start of the competition.

See the competition timetable (including competition dates in various 
timezones), rules, sign-up (commencing 6th August) at:

  http://www.mechanicalcat.net/tech/PyWeek


Richard, the PyWeek coordinator


-
This mail was sent through http://webmail.obsidian.com.au
Brought to you by Obsidian Consulting Group.

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


Re: Is there an easy way to get at the value of DBL_MAX from Python?

2005-07-07 Thread Robert Kern
George Sakkis wrote:
> "Steve Juranich" <[EMAIL PROTECTED]> wrote:
> 
> 
>>I'm in a situation where it would be nice to have access to this
>>value. I've been looking for it all afternoon and can't find anything.
> 
> 
> Where exactly have you been looking ? I guess not in Google, because
> the fifth result after querying "dbl_max" is
> http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html,
> which follows up to
> http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html.
> There is a Numeric subpackage named 'kinds' that provides it along with
> other constants, but it seems it has been excluded from the latest (and
> final I believe) version of Numeric (24.0b2) that I have installed, so
> I can't actually check it.

It has been removed from the Numeric distribution and no one has made a 
real release since. However, it is still available in CVS.

http://cvs.sourceforge.net/viewcvs.py/numpy/kinds/

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


RE: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Philippe C. Martin
> For me, performance is the minor issue. Usability is the major issue. If
> find Eclipse to be highly unusable, so I don't use it.

I find it to be the best option out there

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


Re: Is there an easy way to get at the value of DBL_MAX from Python?

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

> Where exactly have you been looking ? I guess not in Google, because
> the fifth result after querying "dbl_max" is
> http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html,
> which follows up to
> http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html.

Oops, I copy-pasted it twice; the 5th google's result is actually
http://mail.python.org/pipermail/pythonmac-sig/2002-July/005907.html.

George

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


RE: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Delaney, Timothy (Tim)
Tony Meyer wrote:

> It would be interesting to know which JRE the Eclipse advocates are
> using, and which the people that dislike Eclipse are using...

For me, performance is the minor issue. Usability is the major issue. If
find Eclipse to be highly unusable, so I don't use it.

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


Re: Tkinter grid layout

2005-07-07 Thread Christopher Subich
Eric Brunel wrote:

> So you should either make your MainWindow class inherit from Tk, which 
> eliminates the unneeded container and the problems it may cause, or make 
> sure the pack or grid on your MainWindow instance actually tells the 
> container to grow with its container. With pack, it's quite easy: just 
> do myWindow.pack(fill=BOTH, expand=1). With grid, it's a bit more 
> complicated, since you will have to configure the grid on the container.

To expand on this, the grid-method uses a few calls that aren't 
immediately obvious.  Specifically, the containing object must have row 
and columnconfigure called on them:

 >>> r = Tk()
 >>> g = Text(r)
 >>> h = Entry(r)
 >>> g.grid(row=1,sticky=N+S+E+W)
 >>> h.grid(row=2,sticky=E+W)
 >>> r.columnconfigure(0,weight=1)
 >>> r.rowconfigure(1,weight=1)
 >>> r.mainloop()

This creats a window containing a text widget above an entry widget. 
Both will resize horizontally to fill the entire window, and the text 
widget will resize vertically.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to get at the value of DBL_MAX from Python?

2005-07-07 Thread George Sakkis
"Steve Juranich" <[EMAIL PROTECTED]> wrote:

> I'm in a situation where it would be nice to have access to this
> value. I've been looking for it all afternoon and can't find anything.

Where exactly have you been looking ? I guess not in Google, because
the fifth result after querying "dbl_max" is
http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html,
which follows up to
http://mail.python.org/pipermail/pythonmac-sig/2002-July/005916.html.
There is a Numeric subpackage named 'kinds' that provides it along with
other constants, but it seems it has been excluded from the latest (and
final I believe) version of Numeric (24.0b2) that I have installed, so
I can't actually check it.

George

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


RE: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Tony Meyer
> "Java" as a term means different things to different people, 

Agreed.  Python is similar in this respect - it's common to refer to cPython
here as Python, for example.

> but I expect most would think of the core language and its 
> standard library first and the JRE/JVM second. So saying "the 
> problem of X is Java" when you really mean "the problem of X 
> in platform Y is Sun's JVM in Y" is kinda misleading.

Obviously I wouldn't agree :)  The discussion here is about Java from a
user's POV, not a programmer (because we are using a Java application to
program in Python), and from the user's POV, the JRE/JVM is what is
important, not the language.  Much the same as a programmer who is using an
IDE written in Python to program in some other language would really only
care about how the Python VM performs.

> Disclaimer: I am neither Java's not Eclipse's advocate; I'll 
> choose python over Java any day, but let's put the blame 
> where it is due.

If there isn't a good VM for the OS that the vast majority of computers use,
then the language has a problem, IMO.  Having a great language spec is one
thing, but it's not really much use without a good implementation.

It would be interesting to know which JRE the Eclipse advocates are using,
and which the people that dislike Eclipse are using...

=Tony.Meyer

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


Re: Thoughts on Guido's ITC audio interview

2005-07-07 Thread George Sakkis
"Tony Meyer" <[EMAIL PROTECTED]> wrote:

> > Your first sentence contradicts the rest of your post; how is
> > Java the problem if it runs nice on a Mac and is sluggish on
> > Windows ?
>
> Because any Java program on (any version of) Windows (in my experience) is
> sluggish, and this is not true (again, in my experience) for Java programs
> on a Mac.
>
> There is a vast difference between the various JREs; whereas every platform
> I've used a cPython interpreter on has given reasonably constant performance
> (which is to be expected, with a C implementation).

"Java" as a term means different things to different people, but I
expect most would think of the core language and its standard library
first and the JRE/JVM second. So saying "the problem of X is Java" when
you really mean "the problem of X in platform Y is Sun's JVM in Y" is
kinda misleading.

Disclaimer: I am neither Java's not Eclipse's advocate; I'll choose
python over Java any day, but let's put the blame where it is due.

George

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


Re: Python exception hook simple example needed

2005-07-07 Thread Ed Leafe
On Jul 7, 2005, at 7:27 AM, Fuzzyman wrote:

> Do you have an exception handling dialog ?

Not per se, as there hasn't been a request for one; we have several 
dialogs ranging from simple messages to alerts to interactive dialogs, 
much as wxPython offers. But I'll make this offer: give me a spec as to 
what you need this "exception handling dialog" to do, and I'll have it 
added to the framework within 24 hours. Deal?

> Can you use the UI layer without being tied to the rest of the
> framework ? They seemed pretty integrated to me.

They are integrated, but nothing forces you to use anything you don't 
want. I know of several people who have developed UI-only apps, with no 
need for business objects or database connectivity. They started in 
plain wxPython, and switched to Dabo because it was so much easier, and 
so much more Pythonic.

  ___/
 /
__/
   /
  /
  Ed Leafe
  http://leafe.com/
  http://dabodev.com/

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


Is there an easy way to get at the value of DBL_MAX from Python?

2005-07-07 Thread Steve Juranich
I'm in a situation where it would be nice to have access to this
value. I've been looking for it all afternoon and can't find anything.

Thanks.
-- 
Steve Juranich
Tucson, AZ
USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: math.nroot [was Re: A brief question.]

2005-07-07 Thread Tim Peters
[Tim Peters]
 All Python behavior in the presence of infinities, NaNs, and signed
 zeroes is a platform-dependent accident, mostly inherited from that
 all C89 behavior in the presence of infinities, NaNs, and signed
 zeroes is a platform-dependent crapshoot.

[Michael Hudson]
>>> As you may have noticed by now, I'd kind of like to stop you saying
>>> this :) -- at least on platforms where doubles are good old-fashioned
>>> 754 8-byte values.

[Tim]
>> Nope, I hadn't noticed!  I'll stop saying it when it stops being true,
>> though .  Note that since there's not even an alpha out for 2.5
>> yet, none of the good stuff you did in CVS counts for users yet.

[Michael] 
> Well, obviously.  OTOH, there's nothing I CAN do that will be useful
> for users until 2.5 actually comes out.

Sure.  I was explaining why I keep saying what you say you don't want
me to say:  until 2.5 actually comes out, what purpose would it serve
to stop warning people that 754 special-value behavior is a x-platform
crapshoot?  Much of it (albeit less so) will remain a crapshoot after
2.5 comes out too.

>>> But first, I'm going to whinge a bit, and lay out some stuff that Tim
>>> at least already knows (and maybe get some stuff wrong, we'll see).
>>>
>>> Floating point standards lay out a number of "conditions": Overflow
>>> (number too large in magnitude to represent), Underflow (non-zero
>>> number to small in magnitude to represent), Subnormal (non-zero number
>>> to small in magnitude to represent in a normalized way), ...

>> The 754 standard has five of them:  underflow, overflow, invalid
>> operation, inexact, and "divide by 0" (which should be understood more
>> generally as a singularity; e.g., divide-by-0 is also appropriate for
>> log(0)).

> OK, the decimal standard has more, which confused me for a bit
> (presumably it has more because it doesn't normalize after each
> operation).

The "conditions" in IBM's decimal standard map, many-to-one, on to a
smaller collection of "signals" in that standard.  It has 8 signals: 
the 5 I named above from 754, plus "clamped", "rounded", and
"subnormal".  Distinctions are excruciatingly subtle; e.g., "rounded"
and "inexact" would be the same thing in 754, but, as you suggest, in
the decimal standard a result can be exact yet also rounded (if it
"rounds away" one or more trailing zeroes), due to the unnormalized
model.

>>> For each condition, it should (at some level) is possible to trap each
>>> condition, or continue in some standard-mandated way (e.g. return 0
>>> for Underflow).

>> 754 requires that, yes.

>>> While ignoring the issue of allowing the user to control this, I do
>>> wish sometimes that Python would make up it's mind about what it does
>>> for each condition.

>> Guido and I agreed long ago that Python "should", by default, raise an
>> exception on overflow, invalid operation, and divide by 0, and "should
>> not", by default, raise an exception on underflow or inexact.

And, I'll add, "should not" on rounded, clamped and subnormal too.

> OK.

OK .

>> Such defaults favor non-expert use.  Experts may or may not be happy
>> with them, so Python "should" also allow changing the set.
 
> Later :)

That's a problem, though.  754 subsets are barely an improvement over
what Python does today:  the designers knew darned well that each
default is going to make some non-trivial group of users horridly
unhappy.  That's why such extensive machinery for detecting signals,
and for trapping or not trapping on signals, is mandated.  That's a
very important part of these standards.

> (In the mean time can we just kill fpectl, please?)

Has it been marked as deprecated yet (entered into the PEP for
deprecated modules, raises deprecation warnings, etc)?  I don't know. 
IMO it should become deprecated, but I don't have time to push that.

>>> There are a bunch of conditions which we shouldn't and don't trap by
>>> default -- Underflow for example.  For the conditions that probably should
>>> result in an exception, there are inconsistencies galore:
>>>
>>> >>> inf = 1e300 * 1e300 # <- Overflow, no exception
>>> >>> nan = inf/inf # <- InvalidOperation, no exception

>> Meaning you're running on a 754 platform whose C runtime arranged to
>> disable the overflow and invalid operation traps.
 
> Isn't that the standard-mandated start up environment?

The 754 standard mandates "non-stop" mode (all traps disabled) at
startup, but who in this chain is _claiming_ to implement the 754
standard?  Your platform C may or may not, and your OS may or may not.

>> You're seeing native HW fp behavior then.

> But anyway, shouldn't we try to raise exceptions in these cases?

I believe Python should raise exceptions in these cases by default,
because, as above, they correspond to the overflow and
invalid-operation signals respectively, and Python should raise
exceptions on the overflow, invalid-operation, and divide-by-0 signals
by default.  But I also believe Python _dare not_ do so unle

Re: Use cases for del

2005-07-07 Thread George Sakkis
"Grant Edwards" <[EMAIL PROTECTED]> wrote:

> On 2005-07-07, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > I guess he means why not define foo as property:
> >
> > class demo(object):
> > foo = property(fget = lambda self: self.v,
> >fset = lambda self,v: setattr(self,'v',v))
> >
> > d = demo()
> > d.foo = 3
> > print d.foo
>
> In some ways that's even cleaner.
>
> In my simplivied example all the foo() method was doing was
> setting/returning an attribute, but usually there's a bit more
> going on (e.g. system calls with possible side effects).
>
> To me it's a bit more explicit that
>
>   d.foo(3)
>   d.foo()
>
> are doing something other than just getting/setting the value
> of an instance attribute.  If all I really wanted to do was
> get/set the instance's "v" attribute, I probably would have
> just done it like this
>
>   d.v = 3
>   print d.v

The main reason for bringing properties into the language was exactly
to *hide* the fact that something else might be going one behind the
scenes. Ideally, the user of the class shouldn't care [1] whether
getting an attribute returns a stored value in the instance's __dict__,
computes it on the fly, fetches it from a cache or a database, etc, and
similarly for setting the attribute.

George

[1] OTOH the user should probably be aware if a specific property (or
any callable for that matter) implies significant performance (or
other) costs.

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


Re: publishing an already instantiated class

2005-07-07 Thread J
I think I just found my own solution, so I will record it for future
references

I did this in my Constructor of X
{
PyStruct* lObject;
lObject = PyObject_New(PyStruct, &X::PyType);
lObject->mObject = this;
}

What does everyone think about this. I am posting a little bit out of
the hip here,
and should probably investigate my solution a little more.
Nevertheless, it is
a good way to record my experiences...

Cheers
Jochen

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


RE: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Tony Meyer
> Your first sentence contradicts the rest of your post; how is 
> Java the problem if it runs nice on a Mac and is sluggish on 
> Windows ?

Because any Java program on (any version of) Windows (in my experience) is
sluggish, and this is not true (again, in my experience) for Java programs
on a Mac.

There is a vast difference between the various JREs; whereas every platform
I've used a cPython interpreter on has given reasonably constant performance
(which is to be expected, with a C implementation).

> At best this may say something about the difference 
> in perfomance between the two JREs (assuming that most 
> Windows and Mac users of Eclipse have similar experience with yours).

Which was my point.  From what I've seen of this thread, people aren't
saying which platform they are using Eclipse on - I have a suspicion that
the JRE that people are using significantly effects the resulting opinion of
Eclipse.

=Tony.Meyer

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


Re: Thoughts on Guido's ITC audio interview

2005-07-07 Thread George Sakkis
"Tony Meyer" <[EMAIL PROTECTED]> wrote:

> The problem with Eclipse, IMO, is Java.  I've tried 3.1 on a WinXP machine
> and, like just about any Java program, it's incredibly slow and a real pain
> to use.  On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and
> smoothly and is reasonably nice to use.  I'd happily recommend that Mac
> users try Eclipse, but never a Windows (Python) programmer.
>
> =Tony.Meyer

Your first sentence contradicts the rest of your post; how is Java the
problem if it runs nice on a Mac and is sluggish on Windows ? At best
this may say something about the difference in perfomance between the
two JREs (assuming that most Windows and Mac users of Eclipse have
similar experience with yours).

George

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


RE: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Tony Meyer
> Everyone complaining about Eclipse in this thread needs to go 
> try 3.1. The interface is much much much more responsive.

The problem with Eclipse, IMO, is Java.  I've tried 3.1 on a WinXP machine
and, like just about any Java program, it's incredibly slow and a real pain
to use.  On a (similarly spec'd) Mac OS X Tiger machine, it runs nice and
smoothly and is reasonably nice to use.  I'd happily recommend that Mac
users try Eclipse, but never a Windows (Python) programmer.

=Tony.Meyer

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


publishing an already instantiated class

2005-07-07 Thread J
Hi everyone,

Thanks for your awsome replies. I started replacing Javascript
with python 2 days ago and I already have my first scripts running.
Mainly due to the wealth of information in this blog.

I have a C++ object that is already instantiated and now
I want to give python a reference to it... Basically I have

class X
{
typedef struct
{
PyObject_HEAD
ScnNode* mObject;
} PyStruct;

static PyTypeObject PyType;

static init()
{
   PyType_Ready(&PyType) < 0)
   Py_INCREF(&PyType);
   PyModule_AddObject(sModule, "Node", (PyObject*) &PyType);
}
};

I think that in the constructor of X I now have to make some calls in
order to provide access to this instance from a python script I
also think that I only want to get PyObject_New to be called, but not
PyObject_Init, because there I create a new instance of X when it is
instantiated through a script Am I on the right track here ?

Cheers
Jochen

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


Re: threads and sleep?

2005-07-07 Thread Grant Edwards
On 2005-07-07, Peter Hansen <[EMAIL PROTECTED]> wrote:

>>>Maybe you should consider and explain what you mean by
>>>"multiple interpreters"?
>> 
>> That in a multi-theraded Python program, the code that
>> impliments the Python VM is executing "simultaneously" in
>> multiple contexts: one for each thread (and possibly one
>> master thread).
>
> Okay, this description seems correct.  Multiple threads,
> multiple stacks, therefore multiple contexts and yes, by this
> definition, multiple interpreters.
>
> No "master thread" however.  Just all the threads that are
> visible in "threading.enumerate()", which includes the main
> thread (that the code runs in at startup) and any new ones
> spawned afterwards.

Oh.  I assumed that CPython used Posix threads on Posix
platforms.  At least in my experience under Linux, libpthread
always creates an extra "manager" thread.  Though in our case
that thread probably wouldn't be running a Python interpreter.

-- 
Grant Edwards   grante Yow!  Uh-oh!! I'm having
  at   TOO MUCH FUN!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import Help Needed - Newbie

2005-07-07 Thread GregM
A search on google for odbchelper resulted in:
http://linux.duke.edu/~mstenner/free-docs/diveintopython-3.9-1/py/odbchelper.py

I think this will help you.
Greg.

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


Re: Windows Cmd.exe Window

2005-07-07 Thread [EMAIL PROTECTED]


> In the past I have created .bat wrapper files that just call the python
> interpreter, but it is a bit tedious to have to create a matching .bat
> file for every script.  So I came up with the following approach...
>

I frequently use a batch file wrapper.  Typically it has a long
friendly name for others in my (non-IT) department, and calls the
actual python script in a subfolder, often with arguments.  The last
line of the batch file is usually a pause command.

As an alternative, I have a couple of main procedures wrap a try/except
around the entire script, and if an error occurs, then logs the details
before quitting.  I suppose you could also print the error, and add a
call raw_input() so its visible before the window closes.

Hope that helps,
Brian.

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


Re: Options to integrate Python modules into native windows applications

2005-07-07 Thread Philippe C. Martin
Thanks Larry,

I want to:

1) Modify my code as little as possible
2) Please/reassure the lambda VB or VC++ oriented company

Regards,

Philippe



Larry Bates wrote:

> Other methods (services, sockets, pipes, etc.)
> can also work well, but it depends on what you
> want to do and how you wish to communicate between
> the modules.

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


Re: Upgrading from Python 2.2 to 2.4 (can't find _ssl.pyd)

2005-07-07 Thread Larry Bates
Never mind.  Seems that the standard distribution at
www.python.org has it included (I was using ActiveState).

FYI, Larry

Larry Bates wrote:
> Well I'm still on my "quest".  I've been putting this
> off for quite some time because I KNEW it was going to
> be hard.  I tried to wait a while to upgrade to let all
> these things become readily available.
> 
> So far Sam Rushing has been my hero in putting
> updated versions (2.4) of calldll and npstruct
> on his website:
> 
> http://www.nightmare.com/~rushing/dynwin/index.html
> 
> Thanks Sam!
> 
> I've been able to track everything else down, but I have
> to admit that it has been harder than I thought...and
> I'm not done.
> 
> Now I can't find _ssl.pyd compiled for Python 2.4.
> Anybody have a copy they can share?
> 
> Thanks in advance,
> Larry Bates
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Christopher Subich
Terry Hancock wrote:
> With list comprehensions and generators becoming so integral, I'm
> not sure about "unpythonic".  And a syntax just occured to me --
> what about this:
> 
> [y*x for x,y]
> 
> ?
> 
> (that is:
> 
> [ for ]
> 
> It's just like the beginning of a list comprehension or generator, but
> without the iterator.  That implies that one must be given, and
> the result is therefore a callable object.

As others have mentioned, this looks too much like a list comprehension 
to be elegant, which also rules out () and {}... but I really do like 
the infix syntax.

Perhaps using angle-brackets would be useful? These have no 
grouping-meaning in Python that I'm aware of.  Example,



I'd also prefer using 'with' rather than 'for' as the keyword -- 'with' 
doesn't suggest iteration.  I also suggest parenthization of the 
argument list, since that makes a zero-argument lambda not look weird.

To replicate the examples from 
http://wiki.python.org/moin/AlternateLambdaSyntax

1 lambda a, b, c:f(a) + o(b) - o(c)
   
2 lambda x: x * x
   
3 lambda : x
   
4 lambda *a, **k: x.bar(*a, **k)
   
5 ((lambda x=x, a=a, k=k: x(*a, **k)) for x, a, k in funcs_and_args_list)
   ( for x, a, k in funcs_and_args_list)
-- 
http://mail.python.org/mailman/listinfo/python-list


import Help Needed - Newbie

2005-07-07 Thread Dan
Hi

I am trying to learn Python with the "Dive Into Python" book coming from 
VB, but am getting stuck at Example 2.3 
(http://www.diveintopython.org/getting_to_know_python/everything_is_an_object.html).
 
   Here is what I get following the book's directions for:

 >>> import odbchelper
Traceback (most recent call last):
   File "", line 1, in 
ImportError: No module named odbchelper

I am thinking this has something to do with the PATH that Python 
traverses to find code to load as a module.  I would greatly appreciate 
it if you could help me get this to work.

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


Re: threads and sleep?

2005-07-07 Thread Peter Hansen
Grant Edwards wrote:
> On 2005-07-06, Peter Hansen <[EMAIL PROTECTED]> wrote:
>>Maybe you should consider and explain what you mean by
>>"multiple interpreters"?
> 
> That in a multi-theraded Python program, the code that
> impliments the Python VM is executing "simultaneously" in
> multiple contexts: one for each thread (and possibly one master
> thread).

Okay, this description seems correct.  Multiple threads, multiple 
stacks, therefore multiple contexts and yes, by this definition, 
multiple interpreters.

No "master thread" however.  Just all the threads that are visible in 
"threading.enumerate()", which includes the main thread (that the code 
runs in at startup) and any new ones spawned afterwards.

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


Upgrading from Python 2.2 to 2.4 (can't find _ssl.pyd)

2005-07-07 Thread Larry Bates
Well I'm still on my "quest".  I've been putting this
off for quite some time because I KNEW it was going to
be hard.  I tried to wait a while to upgrade to let all
these things become readily available.

So far Sam Rushing has been my hero in putting
updated versions (2.4) of calldll and npstruct
on his website:

http://www.nightmare.com/~rushing/dynwin/index.html

Thanks Sam!

I've been able to track everything else down, but I have
to admit that it has been harder than I thought...and
I'm not done.

Now I can't find _ssl.pyd compiled for Python 2.4.
Anybody have a copy they can share?

Thanks in advance,
Larry Bates
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads and sleep?

2005-07-07 Thread Peter Hansen
Jonathan Ellis wrote:
> Peter Hansen wrote:
>>I can't address the issue of whether or not "most" such projects require
>>distributed locking, because I'm not familiar with more than half of
>>such projects, as you appear to be. 
> 
> Your sarcasm is cute, I suppose, but think about it for a minute.  If
> the opposite of what I assert is true, why would even the mainstream
> press be running articles along the lines of "multicore CPUs mean
> programming will get tougher because locking is hard to get right and
> you can't just scale by relying on the cpu to run your one
> thread/process really fast anymore."
> 
> http://www.gotw.ca/publications/concurrency-ddj.htm for one example.

Thanks, but then let me remove the last (sarcastic) part, the "as you 
appear to be", and just leave the rest as is.  I am *not* familiar with 
this issue, but nevertheless still feel that the OP's problem does not 
involve any such locking, so although it's quite possible that you are 
correct, I have nothing more to add on the matter.  If you think he 
needs locking, and that therefore multi-process stuff via Pyro might not 
work, he's probably the guy to talk to...  I happen to feel it would 
probably work fine.

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


Re: Determining actual elapsed (wall-clock) time

2005-07-07 Thread Peter Hansen
zooko wrote:
> The traditional use of gettimeofday() to (insecurely and unreliably)
> approximate elapsed local time is one of my pet peeves.
> 
> Fortunately a real monotonic clock has finally been added to the linux
> kernel and glibc:
> 
> http://www.imperialviolet.org/page24.html#e474

Interestingly, the author of that page appears to have made a number of 
the same misassumptions about the actual behaviour of the timeofday 
clock (assuming time.time() fairly faithfully reproduces/wraps that 
behaviour).  Either that or time.time() does magic that avoids the bulk 
of the problems in which case I can say only "sucks not to be using 
Python, doesn't it?"

I'd be more interested in this monotonic clock feature if it were not 
the case that time.time() is pretty much monotonic except in the face of 
the minor (sub-100ms) tweaks that might occur once every week or two 
with an NTP client running.  It certainly doesn't cause the one hour 
jumps forwards and backwards which I and the author of that page both 
thought it would.

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


Re: Options to integrate Python modules into native windows applications

2005-07-07 Thread Larry Bates
pywin32 and COM is good.  Seems to work for me.

Other methods (services, sockets, pipes, etc.)
can also work well, but it depends on what you
want to do and how you wish to communicate between
the modules.

Larry Bates


Philippe C. Martin wrote:
> Hi,
> 
> I am looking for the pros and cons as to how to integrate a Python module
> into a Windows native application.
> 
> So far I have looked at
> 
> 1) coding the C wrapper myself
> 2) using Pyrex
> 3) go for pywin32 and COM
> 
> Thanks,
> 
> Philippe
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-07 Thread Peter Hansen
Duncan Booth wrote:
> Peter Hansen wrote:
>>Tom Anderson wrote:
>>>How about just getting rid of del? 
>>
>>Arguing the case for del: how would I, in doing automated testing, 
>>ensure that I've returned everything to a "clean" starting point in all 
>>cases if I can't delete variables?  Sometimes a global is the simplest 
>>way to do something... how do I delete a global if not with "del".
> 
> I generally find that unit tests force me to structure the code in a 
> cleaner manner, e.g. to not use globals as much, but if you do need to 
> delete a global you do it in exactly the same way as you delete anything: 
> use the "del" statement:

Umm: huh?  Tom suggested getting rid of del, I suggested it was required 
for some cases in doing testing in the fact of globals (for cases where 
they are the simplest approach), then you suggest that the correct 
approach is to use "del".

Well, I agree (including your point on use of globals, which I attempted 
to anticipate with my comment starting "sometimes"), but I don't really 
see the point of your posting, Duncan...  it appears redundant on all 
counts.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Ron Adam wrote:

> Reinhold Birkenfeld wrote:
>> Ron Adam wrote:
>>>(a) == ()
>> 
>> 
>> Whoops! a (which is None) is equal to the empty tuple (which is not None)?
> 
> It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
> would be.

But empty parenthesis are parsed as empty tuple::

  In [8]: type( () )
  Out[8]: 

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


Re: question about introspection using inspect module

2005-07-07 Thread Fernando Perez
Benjamin Rutt wrote:

> Fernando Perez <[EMAIL PROTECTED]> writes:
> 
>> I certainly don't want to discourage you from learning about python
>> introspection, it's one of the most fun aspects of the language.  But just
>> as an FYI, the pydoc system already does much of what you have in mind, at
>> least if I'm reading your description correctly:
>>
>> planck[/tmp]> pydoc -p 12345
>> pydoc server ready at http://localhost:12345/
> 
> thanks, I'm aware of that actually, and seeing all the information
> available there was inspiring to me.

OK, you never know :)

> what I am actually trying to do is to build a database of Python
> modules.  so then later, I can write a tool in my favorite editor
> (Emacs) to invoke some forms of completion against this database
> (e.g. os.remov or socket. to see a list of all socket module
> definitions).

well, I have no idea if this will be of any use, but it might:

http://cedet.sourceforge.net/

I use their speedbar quite a bit, but it sounds from the description like they
have some other fancier tools.  I'd be quite curious to know if they play
nicely with python (they mention C++ explicitly), and how much value they add.
Let me know if you are familiar with them, or if you end up investigating
these further.

Cheers,

f

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


Re: print values from Py_BuildValue

2005-07-07 Thread John Machin
[EMAIL PROTECTED] wrote:
> Hello,
> 
> How do i print values returned by Py_BuildValue in Linux?

1. The same way as you would "in" any other operating system.
2. With difficulty.
3. If you must print something from C, print the C components (no 
difficulty).
4. If you are interested in checking what you have created, return the 
value to the Python caller, and print from there (no difficulty).
5. However if you have a debugging problem, read on ...

> 
> PyObject *obj = Py_BuildValue("{s:i}", "Status", status);
> 
> I need to print the Status value here

What is the 'Status' value?
'"Status"' and 'status' are C expressions which you should be able to 
print using printf.
Do you mean 'obj'?
Why do you think you need to print something here? Are you asking 
because you are getting a strange exception?
Have you tested the value returned by Py_BuildValue -- like this:
/* the following line is written to clarify intent,
not as an example of good coding style :-) */
if (obj == NULL) goto free_resources_and_return_NULL;

Are you extending or embedding?
Is this your first attempt?
Have you considered using Pyrex? It does almost of the hard work for you.

HTH,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calculating average time

2005-07-07 Thread GregM
Thanks Skip. As usual I want to make it harder then it actually is.

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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread jayessay
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> "jayessay" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > 1. Someone recently remarked that good Lisp macros are basically
> >   executable pseudo code.  I think that is pretty much exactly right
> >   and is a pretty good "sound bite" distillation of what it is all
> >   about.
> 
> Several years ago  I remarked that Python reads like executable pseudocode. 
> I still think that that is pretty much right.
> 
> Googling, I discovered that the creators of some thing I had never heard of 
> said the same thing about *their* language a couple of years ago.  I wish 
> web pages, like newgroup posts, were dated so one could better trace the 
> history of such usages.

In the context discussed, the idea was the pseudo code was a _direct_
match to the description of the task in the _domain_.  If your domain
is "algorithms" or some such, then I would agree Python would work as
a reasonably decent pseudo language, otherwise no.  It's too low
level.  Same with base CL.  It's too low level.

/Jon

-- 
'j' - a n t h o n y at romeo/charley/november com
-- 
http://mail.python.org/mailman/listinfo/python-list


Options to integrate Python modules into native windows applications

2005-07-07 Thread Philippe C. Martin
Hi,

I am looking for the pros and cons as to how to integrate a Python module
into a Windows native application.

So far I have looked at

1) coding the C wrapper myself
2) using Pyrex
3) go for pywin32 and COM

Thanks,

Philippe


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


Re: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Paul Rubin
Joseph Garvin <[EMAIL PROTECTED]> writes:
> Also, everyone keeps discussing Eclipse as something that gives Java a
> leg up on Python. *Ahem* PyDev :) Which you should also give another
> try if you haven't in a few versions.  Easiest way to get a GUI
> debugger for python.

Can you give a brief description of what the Python debugger is like?
Can it debug multi-threaded Python programs?

IDLE has a rudimentary debugger that can be useful sometimes, but it
wedges up when you exit from it, making its usefulness limited.

> My only misgiving with Eclipse now is that I think development of
> plugins for it is always going to be slower than for Emacs and other
> editors because they have to be written in Java.

I had thought that using the Python debugging interface for required
writing C extensions.  There's a mention in the Python cookbook of
some C-only interface needed for cross-thread signalling.  What's up
with that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Joseph Garvin
Everyone complaining about Eclipse in this thread needs to go try 3.1. 
The interface is much much much more responsive.

Also, everyone keeps discussing Eclipse as something that gives Java a 
leg up on Python. *Ahem* PyDev :) Which you should also give another try 
if you haven't in a few versions. Easiest way to get a GUI debugger for 
python.

My only misgiving with Eclipse now is that I think development of 
plugins for it is always going to be slower than for Emacs and other 
editors because they have to be written in Java.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about introspection using inspect module

2005-07-07 Thread Benjamin Rutt
Fernando Perez <[EMAIL PROTECTED]> writes:

> I certainly don't want to discourage you from learning about python
> introspection, it's one of the most fun aspects of the language.  But just as
> an FYI, the pydoc system already does much of what you have in mind, at least
> if I'm reading your description correctly:
>
> planck[/tmp]> pydoc -p 12345
> pydoc server ready at http://localhost:12345/

thanks, I'm aware of that actually, and seeing all the information
available there was inspiring to me.

what I am actually trying to do is to build a database of Python
modules.  so then later, I can write a tool in my favorite editor
(Emacs) to invoke some forms of completion against this database
(e.g. os.remov or socket. to see a list of all socket module
definitions).

I was browsing pydoc.py but at first glance was having trouble
separating what in the code what is for the GUI, what is for the Web
server, and what does the introspection.  I have actually borrowed the
ModuleScanner class already, to build the list of modules.  It is just
inspecting those modules further where I'm having trouble.

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


Re: print values from Py_BuildValue

2005-07-07 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
> How do i print values returned by Py_BuildValue in Linux?
> 
> PyObject *obj = Py_BuildValue("{s:i}", "Status", status);
> 
> I need to print the Status value here

I'm confused. You say you need to print the Status value here,
but then you also say you want to print the value returned
from Py_BuildValue, which is *not* the status value, but
a dictionary.

You also don't say whether you want to print this using
Python code or C code, so this gives a total of four interpretations
of your question:

1. Print status from C, on Linux:

   printf("The status is %d\n", status);

2. Print status from Python:

   print dict_returned_from_buildvalue['Status']

3. Print value returned from Py_BuildValue, from Python:

   print dict_returned_from_buildvalue

4. Print value returned from Py_BuildValue, in C

   PyObject_Print(obj, stdout, 0);

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


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Ed Leafe
On Jul 7, 2005, at 3:24 AM, Alessandro Brollo wrote:

> 1. I don't want to post banal questions about Python
> to main Python list. Does a "banal Python questions
> list" or a "Python beginners list" exist?
>
> 2. There is somewhere a very patient fellow willing to
> be my free "python tutor" by personal e-mailing
> outside the mail list? . The ideal candidate would be
> someone, sharing with me some other fields of interest
> (I'm a middle-aged Italian pathologist, with some
> dBase III and dBase IV past programming experience,
> and I like nature and mainly horses).

There is an email list called ProPython 
(http://leafe.com/mailman/listinfo/propython) that was started by a 
group of Visual FoxPro developers who are taking up Python. So it is 
definitely newbie-friendly, and has many people willing to help walk 
you through the learning process. And with your database programming 
background, you're sure to fit in with a Fox-flavored crowd!

  ___/
 /
__/
   /
  /
  Ed Leafe
  http://leafe.com/
  http://dabodev.com/

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Terry Hancock
On Wednesday 06 July 2005 08:38 am, Tom Anderson wrote:
> On Wed, 6 Jul 2005, Terry Hancock wrote:
> > With list comprehensions and generators becoming so integral, I'm
> > not sure about "unpythonic".
> 
> I'm going to resist the temptation to argue that list comps are themselves 
> unpythonic :).

Ah, but GvR likes them, so that pretty much makes them "pythonic"
by definition, doesn't it?  ;-)

> Hang on, where's the punctuation in either of those? They *are* done with 
> keywords! 

Yeah, that's true, and it could be true here too, if you throw away the
[].  I see that's one of the proposed alternatives.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Terry Reedy

"Stian Søiland" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On 2005-07-06 02:46:27, George Sakkis wrote:

>> So, who would object the full-word versions for python 3K ?
>> def -> define
>> del -> delete
>> exec -> execute
>> elif -> else if

>Objections for the "else if" might be that it sounds like you can
>replace "else if" with "else x=94" if you want. Thumbs up for "else if"
>because it explains what it is much better than "elif".  "elseif" ?

Today, on pydev list, in thread Chaining try statements: eltry?,
Guido said 'and in fact I sometimes think it was
a mistake to introduce elif just to save typing "else if".'

So maybe this will be reconsidered for 3.0

Terry J. Reedy





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

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Terry Hancock
On Wednesday 06 July 2005 09:41 am, Steven Bethard wrote:
> Terry Hancock wrote:
> > And a syntax just occured to me -- what about this:
> > [ for ]
> 
> If you haven't already, see:
> http://wiki.python.org/moin/AlternateLambdaSyntax
> for other similar proposals.

Yeah, it's basically "Robert Brewer: for (no-parens) syntax 
[3]" isn't it (except that his eliminates the [], which is 
probably saner).

But hey, it's surely a good thing (in the sense of being 
more obvious) that it occured to me independently, 
right? ;-)

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Python Module Exposure

2005-07-07 Thread Rocco Moretti
Robert Kern wrote:
> Jacob Page wrote:
> 
>> Does this newsgroup find attachments acceptable?
> 
> No. Please put files somewhere on the web and post a URL. This would be 
> a good forum to informally announce and discuss your module. 

To add to what Robert said, keep in mind this newsgroup is also mirrored 
to a mailing list, so posting anything but example code snippets would 
quickly fill up people's inboxes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: python-constraint 1.0

2005-07-07 Thread Gustavo Niemeyer
Hello Alexandre,

> People interested in CSP and python may also want to check Logilab's
> constraint module which has been available from some time at:
> 
> http://www.logilab.org/projects/constraint/

Indeed! And please send us some notes comparing both. :-)

The AIMA book inspired me to write that module. IIRC, there's
also some kind of constraint code in Python by one of the book
authors (Peter Norvig). For those who are interested, chapter 5,
which talks about CSPs, may be found in the web site.

> Gustavo, maybe we should coordinate and merge our efforts?

Probably. I confess that even though I'm using CSP logic on
other real world projects, I wrote that module completely for
fun, and was not really caring if I was reinventing the wheel
or not.

> Alexandre Fayolle  LOGILAB, Paris (France).

I'm currently in Paris, btw.

-- 
Gustavo Niemeyer
http://niemeyer.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calculating average time

2005-07-07 Thread Skip Montanaro

greg> 1. Is there a better time function to use?

For this particular scenario I think time.time() is probably what you want:

cumulative = 0.0
n = 0
for link in links:
t = time.time()
ie.Navigate(link)
cumulative += time.time() - t
n += 1

print "average page load time:", cumulative/n, "seconds"

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


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Terry Reedy

"Pawe³ Sakowski" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Tom Anderson wrote:
> def flatten(ll):
>  return reduce(lambda a, l: a.extend(l), ll, [])
>
> How would one do that as a list comp, by the way? I'm really not very 
> good
> with them yet.

Not really a list-comprehension based solution, but I think what you want 
is

>>> ll=[[1,2],[3,4,5],[6]]
>>> sum(ll,[])
[1, 2, 3, 4, 5, 6]

Unless sum knows to typecheck input items and special-case lists and use 
list.extend rather than list+list, this turns an O(n) operation into an 
O(n**2) operation.  Sum is meant for numbers.

Terry J. Reedy



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

Re: Python Module Exposure

2005-07-07 Thread Jacob Page
Robert Kern wrote:

> Jacob Page wrote:
> 
>> I have created what I think may be a useful Python module, but I'd 
>> like to share it with the Python community to get feedback, i.e. if 
>> it's Pythonic.  If it's considered useful by Pythonistas, I'll see 
>> about hosting it on Sourceforge or something like that.  Is this a 
>> good forum for exposing modules to the public, or is there somewhere 
>> more-acceptable?  Does this newsgroup find attachments acceptable?
> 
> No. Please put files somewhere on the web and post a URL. This would be 
> a good forum to informally announce and discuss your module. Formal 
> announcements once you, e.g. put it on SF should go to c.l.py.announce .

Thanks for the information, Robert.  Anyway, here's my informal 
announcement:

The iset module is a pure Python module that provides the ISet class and 
some helper functions for creating them. Unlike Python sets, which are 
sets of discrete values, an ISet is a set of intervals. An ISet could, 
for example, stand for all values less than 0, all values from 2 up to, 
but not including 62, or all values not equal to zero. ISets can also 
pertain to non-numeric values.

ISets can be used in much the same way as sets. They can be or'ed, 
and'ed, xor'ed, added, subtracted, and inversed. Membership testing is 
done the same as with a set. The documentation has some examples of how 
to create and use ISets.

The iset module is for Python 2.4 or later.

I am seeking feedback from programmers and mathematicians on how to 
possibly make this module more user-friendly, better-named, 
better-documented, better-tested, and more Pythonic.  Then, if this 
module is considered acceptable by the community, I'll create a more 
permanent home for this project.

To download the iset module and view its pydoc-generated documentation, 
please visit http://members.cox.net/apoco/iset/.
-- 
http://mail.python.org/mailman/listinfo/python-list


Calculating average time

2005-07-07 Thread GregM
Hi,
I'm hoping that someone can point me in the right direction with this.
What I would like to do is calculate the average time it takes to load
a page. I've been searching the net and reading lots but I haven't
found anything that helps too much. I'm testing our web site and hiting
+6000 urls per test. Here is a subset of what I'm doing.

import IEC
#IE controller from http://www.mayukhbose.com/python/IEC/index.php
from win32com.client import Dispatch
import time
import datetime
from sys import exc_info, stdout, argv, exit
failedlinks = []
links = open(testfile).readlines()
totalNumberTests = len(links)
ie = IEC.IEController()
start = datetime.datetime.today()
# asctime() returns a human readable time stamp whereas time() doesn't
startTimeStr = time.asctime()
for link in links:
start = datetime.datetime.today()
ie.Navigate(link)
end = datetime.datetime.today()
pagetext = ie.GetDocumentText()
#check the returned web page for some things
if not (re.search(searchterm, pagetext):
 failedlinks.append(link)
ie.CloseWindow()
finised = datetime.datetime.today()
finishedTimeStr = time.asctime()
# then I print out results, times and etc.

So:
1. Is there a better time function to use?

2. To calculate the average times do I need to split up min, sec, and
msec and then just do a standard average calculation or is there a
better way?

3. is there a more efficient way to do this?

4. kind of OT but is there any control like this for Mozilla or
firefox?

This is not intended to be any sort of load tester just a url
validation and page check.

Thanks in advance.
Greg.

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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions andbackground unscientific mini-survey]

2005-07-07 Thread Terry Reedy
The difference in readability between

func = lambda x: x**3 - 5*x

def func(x):
return x**3 - 5*x

def func(x): return x**3 - 5*x

is obviously a matter of personal vision.

The fuctional difference (and, I believe, the only difference) is that the 
def form attaches the specific name 'func' to the function object as its 
func_name attribute while the lambda form attaches the generic 'name' 
''.   This makes tracebacks, for instance, less informative.

The reason some think the name=lambda form an abuse is that it is a second 
way to do almost the same thing (with the functional difference being a 
negative) while ignoring the intended purpose of lambda's presence in the 
language.  (But I will not argue this either way.)

Terry J. Reedy





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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Robert Kern
Terry Reedy wrote:
> "jayessay" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>1. Someone recently remarked that good Lisp macros are basically
>>  executable pseudo code.  I think that is pretty much exactly right
>>  and is a pretty good "sound bite" distillation of what it is all
>>  about.
> 
> Several years ago  I remarked that Python reads like executable pseudocode. 
> I still think that that is pretty much right.
> 
> Googling, I discovered that the creators of some thing I had never heard of 
> said the same thing about *their* language a couple of years ago.  I wish 
> web pages, like newgroup posts, were dated so one could better trace the 
> history of such usages.

Trawling through http://web.archive.org might help.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Terry Reedy

"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I'll clarify. A lot of the time I hear arguments against
> features that boils down to.
>
> 1) I don't need it.
>
> 2) Having the feature will make my job more difficult.
>
> 3) I don't understand the merrits of the feature or I
>   have difficulty understanding what it does when I
>   encounter it.
>
> IMO these are arguments if followed sufficiently will lead to
> a language that is only usefull for mediocre programmers.

True.  But these arguments did not stop expert-level features like 
metaclasses, decorators, and (in 2.5) context-management blocks 
(with-blocks).

TJR



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


Re: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Ville Vainio
> "Fabio" == Fabio Zadrozny <[EMAIL PROTECTED]> writes:

>> I agree about the project management part. Though I would still love
>> to use Eclipse instead, if it only was supported for my line of work
>> :-/.

Fabio> What line of work is not supported in eclipse?

C++ programming for Symbian OS. Editing the C++ code works, debugging
doesn't, at least yet.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Terry Reedy

"jayessay" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> 1. Someone recently remarked that good Lisp macros are basically
>   executable pseudo code.  I think that is pretty much exactly right
>   and is a pretty good "sound bite" distillation of what it is all
>   about.

Several years ago  I remarked that Python reads like executable pseudocode. 
I still think that that is pretty much right.

Googling, I discovered that the creators of some thing I had never heard of 
said the same thing about *their* language a couple of years ago.  I wish 
web pages, like newgroup posts, were dated so one could better trace the 
history of such usages.

Terry J. Reedy 



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


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>
>>[EMAIL PROTECTED] (Bengt Richter) writes:
>>
>>> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>>>
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
>>
>>> Will a property or custom descriptor do what you want? E.g.
>>>
>>>  >>> class Base(object):
>>>  ... def __getIter(self):
>>>  ... if hasattr(self, "Iterator"):
>>>  ... return self.Iterator
>>>  ... raise AttributeError, name
>>>  ... __iter__ = property(__getIter)
> [...]
>>
>>Yep, that's exactly what I need - thanks.
>>
> BTW, I forgot to mention that you could use property as a decorator
> in the above single-argument case:
>
>  >>> class Base(object):
>  ... @property
>  ... def __iter__(self):
>  ... if hasattr(self, "Iterator"):
>  ... return self.Iterator
>  ... raise AttributeError, name

Of course.  I didn't spot this, but I cannot use this anyway for 2.3
compatibility.

>  ...
>  >>> class Concrete(Base):
>  ... def Iterator(self):
>  ... yield 1
>  ... yield 2
>  ... yield 3
>  ...
>  >>> iter(Base())
>  Traceback (most recent call last):
>File "", line 1, in ?
>  TypeError: iteration over non-sequence
>  >>> iter(Concrete())
>  
>  >>> list(iter(Concrete()))
>  [1, 2, 3]
>
> Hope there isn't a gotcha for your use case in the way an instance attribute
> of the same name is allowed. A custom descriptor could eliminate that.
>
>  >>> inst = Concrete()
>  >>> list(iter(inst))
>  [1, 2, 3]
>  >>> inst.__init__ = 'abc'
>  >>> list(iter(inst))
>  [1, 2, 3]
>  >>> inst.__init__
>  'abc'

I don't understand what you mean here.  A __iter__ instance attribute?

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


Re: latex/bibtex python paper?

2005-07-07 Thread Jules Dubois
On Wednesday 06 July 2005 09:28, [EMAIL PROTECTED] <[EMAIL PROTECTED]>
(<[EMAIL PROTECTED]>) wrote:

> Hi All,
> 
> Does anyone have a good template that I might use for writing a python
> paper in latex/bibtex?  [...]
> 
> When I cite these, I get something like this (Foundation[2005]).

Questions like this are better asked in comp.text.tex, where they are
on-topic.

There is a fine TeX/LaTeX/etc. FAQ at:

  http://www.tex.ac.uk/cgi-bin/texfaq2html

Finally, here are some sample bibtex results:

  http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Module Exposure

2005-07-07 Thread Robert Kern
Jacob Page wrote:
> I have created what I think may be a useful Python module, but I'd like 
> to share it with the Python community to get feedback, i.e. if it's 
> Pythonic.  If it's considered useful by Pythonistas, I'll see about 
> hosting it on Sourceforge or something like that.  Is this a good forum 
> for exposing modules to the public, or is there somewhere 
> more-acceptable?  Does this newsgroup find attachments acceptable?

No. Please put files somewhere on the web and post a URL. This would be 
a good forum to informally announce and discuss your module. Formal 
announcements once you, e.g. put it on SF should go to c.l.py.announce .

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: Favorite non-python language trick?

2005-07-07 Thread Robert Kern
Edvard Majakari wrote:
> Simon Brunning <[EMAIL PROTECTED]> writes:
> 
>>http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb
> 
> Neat.
> 
> I guess about 75% about programming-related things classified as neat-o or
> "convenient!" are already implemented by some Pythonista(s). Spoils all the
> fun for reinventing the wheel, doesn't it. :)

Doesn't seem to stop most Pythonistas from trying, though.  :-)

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Daniel Schüle
> Am I just weird?

I feel the same way about where to use lambda's and where *not*
I come from C and C++ background and defining a function at the top 
level (no nested functions) would always require good reasons

function name has to be remembered, to put it in other words it has to 
be added in a mental list of available function
and writing a 2 liner function would only cause call overhead
(if not inlined) this may be the reason why "def" feels to me to have 
more weight as "lambda"
usually you define lambda and forget it, no wasted time to find proper 
name, which may also pollute the namespace
I find it more clear solution, it's concise

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


Re: ANN: python-constraint 1.0

2005-07-07 Thread Alexandre Fayolle
On Thu, Jul 07, 2005 at 03:40:10AM -0300, Gustavo Niemeyer wrote:
> 
> Overview
> 
> 
> **python-constraint** [1]_ is a Python module offering solvers for
> Constraint Solving Problems (CSPs) over finite domains in simple
> and pure Python. CSP is class of problems which may be represented
> in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...),
> and constraints (`a < b`, ...).
> 
> .. [1] http://codespeak.net/~niemeyer/constraint/

People interested in CSP and python may also want to check Logilab's
constraint module which has been available from some time at:

http://www.logilab.org/projects/constraint/

Gustavo, maybe we should coordinate and merge our efforts?

-- 
Alexandre Fayolle  LOGILAB, Paris (France).
http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Python Module Exposure

2005-07-07 Thread Jacob Page
I have created what I think may be a useful Python module, but I'd like 
to share it with the Python community to get feedback, i.e. if it's 
Pythonic.  If it's considered useful by Pythonistas, I'll see about 
hosting it on Sourceforge or something like that.  Is this a good forum 
for exposing modules to the public, or is there somewhere 
more-acceptable?  Does this newsgroup find attachments acceptable?

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


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Dieter Maurer
Thomas Heller <[EMAIL PROTECTED]> writes on Wed, 06 Jul 2005 18:07:10 +0200:
> Thomas Heller <[EMAIL PROTECTED]> writes:
> ...
> > class Base:
> > def __getattr__(self, name):
> > if name == "__iter__" and hasattr(self, "Iterator"):
> > return self.Iterator
> > raise AttributeError, name
> >
> > class Concrete(Base):
> > def Iterator(self):
> > yield 1
> ...
> > If, however, I make Base a newstyle class, this will not work any
> > longer.  __getattr__ is never called for "__iter__" (neither is
> > __getattribute__, btw).  Probably this has to do with data descriptors
> > and non-data descriptors, but I'm too tired at the moment to think
> > further about this.
> >
> > Is there any way I could make the above code work with new style
> > classes?
> 
> I forgot to mention this: The Base class also implements a __getitem__
> method which should be used for iteration if the .Iterator method in the
> subclass is not available.  So it seems impossible to raise an exception
> in the __iter__ method if .Iterator is not found - __iter__ MUST return
> an iterator if present.

Then, it should return an interator (a new object) that uses
the "__getitem__" method to iterate.


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


Re: Use cases for del

2005-07-07 Thread Dieter Maurer
Daniel Dittmar <[EMAIL PROTECTED]> writes on Wed, 06 Jul 2005 16:12:46 +0200:
> Peter Hansen wrote:
> > Arguing the case for del: how would I, in doing automated testing,
> > ensure that I've returned everything to a "clean" starting point in
> > all cases if I can't delete variables?  Sometimes a global is the
> > simplest way to do something... how do I delete a global if not with
> > "del"?
> 
> 
> globals ().__delitem__ (varname)
> 
> except that the method would probably be called delete.

You now have a uniform way to remove an object from a namespace.

Why would you want to give each namespace its own method to
remove objects from it?

Can you imagine how much code you would break (would your proposal
to remove "del" got accepted)?


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


Re: Use cases for del

2005-07-07 Thread Ron Adam
Steven D'Aprano wrote:

> Ron Adam wrote:
> 
>> Why would you want to use None as an integer value?
>>
>> If a value isn't established yet, then do you need the name defined? 
>> Wouldn't it be better to wait until you need the name then give it a 
>> value?
> 
> 
> Er, maybe I'm misunderstanding something here, but surely the most 
> obvious case is for default and special function arguments:
> 
> def count_records(record_obj, start=0, end=None):
> if end == None:
> end = len(record_obj)
> if start == None:  # this is not the default!
> # start at the current position
> start = record_obj.current
> n = 0
> for rec in record_obj.data[start:end]:
> if not rec.isblank():
> n += 1
> return n
> 
> which you call with:
> 
> # current position to end
> count_records(myRecords, None)
> # start to end
> count_records(myRecords)
> # start to current position
> count_records(myRecords, end=myRecords.current)


You have three possible outcomes,
count all
count range
count using current index
count range from beginning to current
count range from current to end


The most consistent way to do this would be:


def count_records(record_obj, start=0, end=len(record_obj)):
 n = 0
 for rec in record_obj.data[start:end]:
 if not rec.isblank():
 n += 1
 return n


# current position to end
count_records(myRecords, myRecords.current)

# start to end
count_records(myRecords)

# start to current position
count_records(myRecords, end=myRecords.current)


Cheers,
Ron



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


Re: Use cases for del

2005-07-07 Thread Ron Adam
Grant Edwards wrote:

> On 2005-07-07, Ron Adam <[EMAIL PROTECTED]> wrote:

>>It would be a way to set an argument as being optional without
>>actually assigning a value to it.
>>
>>So it would still work like you expect even though v is not
>>bound to anything.  Like I said the bigger problem is that
>>globals will be visible and that would create a conflict.
>>Setting a value to None in a function hides globals of the
>>same name.  That wouldn't happen if None unbound names as del
>>does.
> 
> Good point.  I hadn't thought of that.

The easiest way to fix that is to create a Nil or Null object as a 
replacement for the current None object.


>>>I find it more obvious to set the name to None during the
>>>periods that it isn't valid than to delete it and check for a
>>>NameError when I want to know if the value is usable or not.
>>
>>You would still be able to do that explicitly and it probably would be a 
>>good idea when you aren't sure if a name is left over from something else.
>>
>>If a name is None, it means it's available and unassigned, so
>>you don't have to check for a NameError.
> 
> 
> How would you spell "if a name is None"?

How about:

if name is None: name = something

Making None the same as undefined wouldn't change this.  I think the 
parser would need to be a little smarter where None is concerned in 
order to be able to handle it in bool expressions,  and catch improper 
name = undefined assignments.

But it might not change things as much as you think.


> Personally, I think the spellings
> 
>del name
>if 'name' in locals()
> 
> is much more explicit/obvious than
> 
>name = None
>name is None   

This would be
  name = None # remove it from locals()
  if name is None: dosomething# if it's not in locals()

No need to check locals or globals.  That's one of the plus's I think.


Since we can already assign a value to any name without first 
initializing it,  this just allows us to use it in a some expressions 
without also first initializing it.  It would still give an error if we 
tried to use it in "any" operation.  Just like the present None.


> I expect the "=" operator to bind a name to a value.  Having it
> do something completely different some of the time seems a bit
> unpythonic.

But you are assigning it a value. Instead of having a Name assigned to a 
None object, the name is just removed from name space to do the same 
thing and you save some memory in the process.



How about keeping None as it is as a place holder object, and having a 
keyword called "undefined" instead.

x = 3
x = undefined   # delete x from name space
if x is not undefined: print x

if an undefined name is used with any operator, it could give a 
'UndefinedName' error.

This would be more compatible with the current python language.

Cheers,
Ron

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


Re: question about introspection using inspect module

2005-07-07 Thread Fernando Perez
Benjamin Rutt wrote:

> I'm trying to learn about introspection in Python.  my ultimate goal
> is to be able to build a module "text database" of all modules that
> are in the sys.path, by discovering all candidate modules (I've
> already done that), importing all of them, and then introspecting on
> each module to discover its functions, globals and classes.  But for
> now I am having a problem with the latter.

I certainly don't want to discourage you from learning about python
introspection, it's one of the most fun aspects of the language.  But just as
an FYI, the pydoc system already does much of what you have in mind, at least
if I'm reading your description correctly:

planck[/tmp]> pydoc -p 12345
pydoc server ready at http://localhost:12345/


Just point your favorite webbrowser to that URL (use any port number you want,
and which isn't already in use).

Cheers,

f

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


print values from Py_BuildValue

2005-07-07 Thread [EMAIL PROTECTED]
Hello,

How do i print values returned by Py_BuildValue in Linux?

PyObject *obj = Py_BuildValue("{s:i}", "Status", status);

I need to print the Status value here

-Thanks,
Ashton

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


Re: How do you program in Python?

2005-07-07 Thread Jorgen Grahn
On Thu, 07 Jul 2005 18:10:44 +1000, Gregory Bond <[EMAIL PROTECTED]> wrote:
> Jorgen Grahn wrote:
>
>> Emacs and vim are almost always installed, or trivially installable. All I
>> need to remember is to bring my emacs config file.
>
> And, fortunately, USB pen drives are now big enough to hold it!

Hey, it's not fair to make fun of emacs now that I've mentioned vim
favourably so many times ;-)

Seriously, nothing about emacs seems big or slow today. It has been
outbloated by pretty much everything else. Who could have imagined /that/
ten years ago?

/Jorgen
(And just in case this thread deteriorates into a silly emacs-vs-vi
argument, I hereby declare myself out of the game.)

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


Re: Deleting variables [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Tom Anderson
On Thu, 7 Jul 2005, Steven D'Aprano wrote:

> On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote:
>
>>> del -> delete
>>
>> How about just getting rid of del? Removal from collections could be done
>> with a method call,
>
> Which would be called object.del() I presume.

That would be fine.

> And that opens a big can of worms.
>
> Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do?

Delete the item at index 1, just as del L[1] would.

> It looks like it should result in L becoming [4, 3, 2, 0].

Why? I guess if you hadn't read the documentation and were just calling 
methods at random, you might, but i can't think of any other case.

> An easy mistake to make, if you forget that the argument is (presumably) 
> an index.

Not the kind of thing people tend to forget! There is the problem that 
people might get del and remove mixed up; i didn't actually realise there 
was a remove method on lists until i looked just now.

> You could make it clear by insisting on L.del[1] but that requires a big 
> change in Python's syntax.

It would, so i wouldn't dream of insisting on it.

> What should L.del() do, with no arguments? Raise an error?

Er, exactly the same as calling any other method with a wrong-length 
argument list - a TypeError, i should think.

> Now, you have something like this:
>
> class thing:
>pass
> obj = thing()
> obj.alpha = [4, 3, 2, 1, 0]
> obj.beta = 5
>
> Python's object model suggests that obj.alpha.del() should call alpha's 
> del method, in the same way that obj.alpha.append() would call alpha's 
> append method.

Exactly so.

> So how do you delete obj.alpha? obj.del("alpha") might work. But what if 
> obj itself is a mapping, with a key "alpha" as well as an attribute 
> alpha. Which one should obj.del("alpha") delete?

I don't think objects should have a del method by default. I'd suggest a 
delattr or removeattr builtin, working along the lines of getattr and 
setattr, for this task.

> Now, if you said that L.del() should raise an exception earlier, what 
> about obj.beta.del()?

Unless int has a del method, that would be an exception - an 
AttributeError, to be precise.

> Presumably every object automatically has a del method,

I'd say no, but for the sake of argument, let's say it does.

> so you don't have to program a del method yourself. obj.del is a method 
> object. So it has a del method. (Yes, sometimes you want to delete 
> methods. Functions are first class objects in Python.) Which has a del 
> method. Which has a del method.

Right.

> What should obj.del.del.del.del.del.del.del.del.del() do?

Raise a TypeError, since you haven't passed any parameters.

As for obj.del.del.del.del.del.del.del.del.del("del"), that's an 
interesting one - it comes down to the question of whether those del 
methods are the same object or not. I'd say not: for two objects a and b 
of the same class, a.foo and b.foo are considered different objects in 
python, and that applies here.

>> and i'm not convinced that deleting variables is something we really 
>> need to be able to do (most other languages manage without it).
>
> Most other languages don't have namespaces that can get polluted, or
> on-the-fly creation of variables. Most other languages don't consider
> variables to be simply attributes of a module object.

How much is that really used? And how many of those cases wouldn't be 
covered by a delattr builtin?

> And most other languages don't allow you to run interactive sessions 
> where it is easy to mistakenly make variables you don't want.
>
> py> x = 1
> py> u = x+2  # oops, typo, meant y not u
> py> del u  # prevent confusion in the programmer's mind
>
> It is also useful sometimes to delete a module object from the top level 
> namespace before re-importing it, rather than merely reloading it. That 
> requires being able to delete a variable.

That's a very strong use case. However, it would be straightforward to 
make variable deletion an interpreter thing rather than a language thing.

> In summary: del being a keyword works. del() being an object method is 
> unclear, confusing and complicated.

Only if you give it the bizarre semantics you use above!

I think having del as a keyword is actually unhelpful, since it's 
overloaded to do two quite different things - remove items from lists and 
dicts, and expunge attributes from namespaces. Far better to do let lists 
and dicts expose methods to let themselves be manipulated, and to play 
with attributes through a uniform troika of {get, set, del}attr builtins.

tom

-- 
They travel the world in their ice cream van ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change a script while it is running

2005-07-07 Thread Do Re Mi chel La Si Do
Hi !

Try :


def ff(a):
print a*2

ff(111)

exec('''def ff(a):
print a*3
''',globals(),globals())

ff(111)



@-salutations

Michel Claveau





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


Re: flatten()

2005-07-07 Thread Björn Lindström
Tom Anderson <[EMAIL PROTECTED]> writes:

> Stian Søiland wrote:
>
> > Or what about a recursive generator?
>
> That's the sort of thing i like to see!

That can be a neat method. It's a pretty verbose way to do flatten(),
but it's a good example:

def flatten(l):
for e in l:
if isinstance(e, list):
for f in flatten(e):
yield f
else:
yield e

for x in flatten([0, [1, 2, [3, 4], 5], 6, 7]):
whatever()

--
Björn Lindström <[EMAIL PROTECTED]>
Student of computational linguistics, Uppsala University, Sweden
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: precision problems in base conversion of rational numbers

2005-07-07 Thread [EMAIL PROTECTED]


Raymond Hettinger wrote:
> > > For a simple example, convert both 10247448370872321 and
> > > 10247448370872319 from base ten to 4 digits of hex.  The calculations
> > > need to be carried out to 15 places of hex (or 17 places of decimal)
> > > just to determine whether the fourth hex digit is a 7 or 8:
> > >
> > > >>> hex(10247448370872321)
> > > '0x246801L'
> > > >>> hex(10247448370872319)
> > > '0x2467ffL'
> >
> > I don't understand your simple example.
> >
> > log(10)/log(16) = 0.83048202372184058696757985737235
> >
> > Multiplying by the number of decimal digits (17) gives
> >
> > 14.11819440327128997844885757533
> >
> > Rounding up to an integer digit count, we need need 15 hex digits.
> > Isn't that exactly what you concluded? Where does that 4 hex digit
> > stuff come from?
>
> It is part of the OP's problem spec.  Given a number x (which may be a
> decimal, float, long integer, or rational), a base b, and a desired
> precision p, compute the conversion to p-digits:
>
>   >>> convert(x=10247448370872319L, b=16, p=4)
>   '246800'

But you haven't explained why you are using p=4. The OP's problem
is that he's doing convert(x=10247448370872319L, b=16, p=17).
So of course it's going to be wrong because base 16 numbers are
bigger than base 10 numbers. By trying to use the same precision
with different bases, he's asking for more precision in the base 17
number than what exists in the base 10 number.

>
> He wanted to know what decimal precision he needed to set to make the
> conversion accurate to the last place.  The required precision for
> intermediate calculations depends on how close x is to a representable
> value in the target base.  The 16 digits are not known a priori since x
> may be a rational, float, or decimal.  For instance, an internal
> precision of 17 digits would also be needed for other nearby values of
> x:
>
>   >>> convert(x=Decimal("10247448370872319.1", b=16, p=4)
>   '246800'

Now your base 10 number has 26 digits. So shouldn't your convert be
using p=22?

>
> The number 17 does not just pop-out of a simple logarithm.

It most certainly does

>>> print floor(math.log10(10247448370872319)) + 1
17.0


> How many
> internal digits of precision do you need for convert(math.pi, b=16,
> p=5)?

I think I would need 7.

Because
>>> print math.log(16)/math.log(10)*5
6.02059991328


>>> from gmpy import *
>>> import math
>>> print math.pi
3.14159265359

Using math.pi

>>> print fdigits(math.pi,16,5)
[EMAIL PROTECTED]

Using only seven digits

>>> print fdigits(mpf("3.141593"),16,5)
[EMAIL PROTECTED]

I don't see any problem.

> If the result falls closely between reprentable values, the OP
> may need to set his "magic number" to something larger than you would
> have predicted.
>
> If you want insight into why the OP's problem statement is deeper than
> it appears, then ponder the mystery of why the following returns False:
>
>   >>> x = 554459760520464551937111727196883414687442277344893869152167
>   >>> float(x) == float(str(x))
>   False

No big mystery. Isn't that why they added the Decimal module?

>
> Hint, the two different underlying routines are trying to compute,
> convert(x, b=2, p=53), without the benefit of arbitrary precision
> arithmetic.

Yep, sure is nice to have that.

>>> x = mpz(554459760520464551937111727196883414687442277344893869152167)
>>> float(x)==float(str(x))
True


> 
> 
> Raymond

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


method for Exception base class to raise the exception in an expression?

2005-07-07 Thread Bengt Richter
Sometimes it could be handy, e.g., cutting short iteration:

 >>> def raisex(self, *args):
 ... raise self.__class__(self, *args)
 ...
 >>> Exception.raisex = raisex
 >>> list(i for i in xrange(20) if i<10 or StopIteration().raisex())
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> list(i for i in xrange(20) if i<15 or StopIteration().raisex())
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
 >>> list(i for i in xrange(20) if i<25 or StopIteration().raisex())
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

a class method could be nicer once we have Exception as a new-style class.

Just a thought.

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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Ron Adam
Steven D'Aprano wrote:

> On Thu, 07 Jul 2005 09:36:24 +, Duncan Booth wrote:
> 
> 
>>Steven D'Aprano wrote:
>>
>>>This is something I've never understood. Why is it bad 
>>>form to assign an "anonymous function" (an object) to a 
>>>name?
>>
>>Because it obfuscates your code for no benefit. You should avoid making it 
>>hard for others to read your code (and 'others' includes yourself in the 
>>future).

Use a descriptive name like this?

def get_the_cube_of_x_and_then_subtract_five_multiplied_by_x(x):
  x**3 - 5*x

I think I like the lambda version here.  ;-)

It would probably have a name which refers to the context in which it's 
used, but sometimes the math expression it self is also the most readable.



> Put it this way: whenever I see a two-line def as above, I can't help
> feeling that it is a waste of a def. ("Somebody went to all the trouble
> to define a function for *that*?") Yet I would never think the same about
> a lambda -- lambdas just feel like they should be light-weight. 

In the case of an interface module you might have a lot of two like 
def's that simply change the name and argument format so several modules 
can use it and have a standard consistent or simplified interface.

The lambda may be perfectly fine for that.  But why not use def?

func_x = lambda x: (someother_func_x(x,'value'))

def func_x(x): return someother_func_x(x,'value')

There's both nearly identical, but the def is understandable to 
beginners and advanced python programs.


Cheers,
Ron


> Am I just weird?

Aren't we all?   ;-)

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


Re: latex/bibtex python paper?

2005-07-07 Thread ansobol
Kurt,

Try  and search
this site (the famous UK TeX FAQ) at
 for
other info.

You might also ask this question at the comp.text.tex group (which, in
my experience, is as nice as this one).

HTH
Andrei

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


Re: flatten(), [was Re: map/filter/reduce/lambda opinions ...]

2005-07-07 Thread Tom Anderson

On Thu, 7 Jul 2005, Ron Adam wrote:


Stian Søiland wrote:

> Or what about a recursive generator?


That's the sort of thing i like to see!

Ok, lets see...  I found a few problems with the testing (and corrected 
it) so the scores have changed.  My sort in place routines were cheating 
because the lists weren't reset between runs so it had the advantage 
after the first time though of sorting already sorted list.


Aaagh, of course!

And Tom's recursive no copy had a bug which kept a reference to one of 
it's arguments so it's output was doubling the list.


Oops. I really should have written tests as well as benchmarks.

And the hasattr function was slowing everyone down, so I inlined it for 
everyone who used it. Using a 1000 item list and starting with a flat 
list and increasing the depth (unflatten) to shallow, medium, and deep. 
(but not so deep to cause recursion errors.)


I wrote a new and improved test harness myself, but left my laptop at 
work, and haven't been in today due to the bombs :(. I ran tests out to 
100 000 elements, and your implementation was still faster, although not 
by a lot - but then i hadn't found the bugs you had, so it's all moot.



And the winners are...

Stians flatten generator is nearly tied with Tom's recursive zerocopy. 
My nonrecursive inplace is faster for very shallow lists, but Tom's 
quickly over takes it.  I was able to improve my nonrecursive copy 
flatten a bit, but not enough to matter.


I also came up with an improvement to my version that should cut down on 
recursive calls - a sort of recursion unrolling. I doubt it wouldd make 
much difference, though.


So Tom's recursive zerocopy is the overall winner with Stian's flatten 
generator close behind and just barely winning out in the very deep 
catagory.


\o/


But they're all respectable times so everyone wins. ;-)


Everyone shall have medals!

tom

--
They travel the world in their ice cream van ...-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >