Re: how to append to a list twice?

2006-04-21 Thread Alex Martelli
Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> 
> > > But of course that only does it once, and I don't want to have to copy
> > > and paste the append line. Perhaps there's a better way than this.
> >
> > def makeseries(N):
> >   series = [N]
> >   append = series.append
> >   for tailer in xrange(N-1, -1, -1):
> > append(tailer)
> > append(tailer)
> 
> But Now You've Violated The DRY Principle!!!

Just as with any other unrolled loop, yes -- loop unrolling is an
optimization which is based exactly on exchanging some textual
repetition for a tiny bit more speed.

Of course, optimizations can easily be premature, and in any case need
to be checked by measurement.  E.g., here are a few variations:

def makeseries_a(N):
  series = [N]
  append = series.append
  for tailer in xrange(N-1, -1, -1):
append(tailer)
append(tailer)
  return series

def makeseries_b(N):
  series = [N]
  append = series.append
  for tailer in xrange(N-1, -1, -1):
  for x in (1,2):
append(tailer)
  return series

def makeseries_c(N):
  series = [N]
  extend = series.extend
  for tailer in xrange(N-1, -1, -1):
extend((tailer,tailer))
  return series

def makeseries_d(N):
  series = [N]
  extend = series.extend
  for tailer in xrange(N-1, -1, -1):
extend((tailer,)*2)
  return series


And:

brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_a(100)'
1 loops, best of 3: 31.7 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_b(100)'
1 loops, best of 3: 57.4 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_c(100)'
1 loops, best of 3: 36.2 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_d(100)'
1 loops, best of 3: 54.4 usec per loop

So, it would seem that (at least among these few variations) I had
guessed right, this time -- the loop-unrolling is beneficial and append
is minutely better than extend. Of course, the yanking from the loopbody
of the boundmethod is also a key optimization here -- with unyanked
(more natural) versions [[i.e., calling series.append or series.extend
right in the loop body]] I measure:

brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_a(100)'
1 loops, best of 3: 57.3 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_b(100)'
1 loops, best of 3: 83.5 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_c(100)'
1 loops, best of 3: 48 usec per loop
brain:~/downloads alex$ python -mtimeit -s'import rep'
'rep.makeseries_d(100)'
1 loops, best of 3: 68.4 usec per loop


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


Re: Powerful Command line parsers

2006-04-21 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 John Machin <[EMAIL PROTECTED]> wrote:

>To meet your specifications, the module would need to incorporate a 
>mini-language:
>
>if a and (b or c): nasty("blah 1")
>if not (a or b or c or d): nasty("blah 2")
>if a and c and not d: nasty("blah 3")

Prolog-style predicates. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda

2006-04-21 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello,
>
> I need your help understanding lambda (and doing it a better way
> without).
>
> f  = lambda x : x*x

There is no reason to ever write name=lambda...

def f(x): return x*x

is better because it attaches the name to the function for tracebacks.

> # this is a list of functions
> [f for y in range(1,5)]
>
> [f for y in range(1,5)][0](2)
> # returns 4, as expected
>
>
> # ok now I want a list like
> # [x^2, 2*x^2, 3*x^2,...]

Given:

def makef(multiplier):
   def f(x): return multiplier*x*x
   return f

> [f*y for y in range(5)]

I believe

[makef(y) for y in range(5)]

will do what you want.

The slightly abbreviated lambda form is never necessary, that I know of, 
and notoriously confusing when used in list comprehensions.  So I advise 
don't.

Terry Jan Reedy



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


Re: Can you create an instance of a subclass with an existing instance of the base class?

2006-04-21 Thread Cavingdeep
With new-style classes you can find out a class' subclasses and then
you can instantiate the subclass you want. Suppose you have two classes
A and B, B is a subclass of A, A is a new-style class. Now you have an
A's instance called "a", to instance B you can do the following:

b = a.__class__.__subclasses__()[0]()

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


Re: R Paul Johnson is out of the office.

2006-04-21 Thread Terry Reedy

"RK" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> ok,  who's been playing with mailman?

I am sure the problem is a mis-configured auto-responder robot.  Nothing 
like telling the world that you are not around to watch your home or 
office,  Reminds me of when newspapers used to carry society notices of 
people going off on trips, like to Europe.

The more common misbehavior is to privately spam posters on the list rather 
than the list itself.

The message really should just say Ex Y. Zeta is not responding to email 
(until ...).  No reason to say why.

Terry Jan Reedy



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


Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Ravi Teja
> Well, Java does have this great feature called "market-hype"...

I ... concede.

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Anthony Liu

OK, I actually just want to "manually" create Hidden
Markov Models by randomly generating the initial state
probabilities PI, the transition probabilities A and
the emission probabilities B, instead of learning such
statistics from a corpus.  They have to be subject the
constraint that 

sum(PI) = 1.0
sum(each row of A) = 1.0
sum(each row of B) = 1.0

Got an idea?

Thank you for your help.  I guess I can use random()
instead of uniform(0,1) given your comments about
uniform.  I did not know the uniform function until a
moment ago when I checked the python.org
documentation.

As a matter of fact, given that we have to specify the
number of states for an HMM, I would like to create a
specified number of random floating numbers whose sum
is 1.0.



--- Edward Elliott <[EMAIL PROTECTED]> wrote:

> Anthony Liu wrote:
>  > But, I want the random numbers just generated sum
> up
>  > to 1 .
> 
> This seems like an odd request.  Might I ask what
> it's for?
> 
> Generating random numbers in [0,1) that are both
> uniform and sum to 1 looks 
> like an unsatisfiable task.  Each number you
> generate restricts the 
> possibilities for future numbers.  E.g. if the first
> number is 0.5, all 
> future numbers must be < 0.5 (indeed, must *sum* to
> 0.5).  You'll end up 
> with a distribution increasingly skewed towards
> smaller numbers the more 
> you generate.  I can't imagine what that would be
> useful for.
> 
> If that's not a problem, do this: generate the
> numbers, add them up, and 
> divide each by the sum.
> 
> nums = [random.uniform(0,1) for x in range(0,100)]
> sum = reduce(lambda x,y: x+y, nums)
> norm = [x/sum for x in nums]
> 
> Of course now the numbers aren't uniform over [0,1)
> anymore.
> 
> Also note that the sum of the normalized numbers
> will be very close to 1, 
> but slightly off due to representation issues.  If
> that level of accuracy 
> matters, you might consider generating your rands as
> integers and then 
> fp-dividing by the sum (or just store them as
> integers/fractions).
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


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


Re: Updated PEP 359: The make statement

2006-04-21 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> The make statement was mostly syntactic sugar for::
>
>class  :
>__metaclass__ = 
>
>
> So was technically unnecessary from the beginning. ;)  Here's the one
> post where he presented a few reasons he didn't like it:
>
> http://mail.python.org/pipermail/python-3000/2006-April/000704.html
>
> He didn't say a whole lot else about it, but when he mentioned that he'd
> like the discussion to end, I offered to end it. ;)

In nice contrast to people who do the opposite when directly requested to 
stop.

I think you carried out a model PEP process, making frequent revisions as 
warrented by comments.  I also thought the process had about run its 
course, with pretty much every thing said, with people repeating things, 
and without the proposal gaining enough traction to go anywhere.  So nice 
to end gracefully.

Oh, and I did learn something new about how to 'abuse' class and metaclass.

Terry Jan Reedy




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


Re: python equivalent of VB code sample

2006-04-21 Thread mirandacascade
Thank you for pointing me in the direction of XMLHTTP.  I'm still
thinking about this in terms of creating a python script that is
functionally equivalent to the VB code in the original post. The
information I reviewed about XMLHTTP makes me think that it may be
possible to use the win32com.client to provide the python script with
the same methods and properties that the VB program is using.

Is win32com.client what I should be using?  The Dispatch method of
win32com.client?

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 03:16 +, Edward Elliott escreveu:
> If that level of accuracy 
> matters, you might consider generating your rands as integers and then 
> fp-dividing by the sum (or just store them as integers/fractions).

Or using decimal module: http://docs.python.org/lib/module-decimal.html

-- 
Felipe.

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

Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Aahz
In article <[EMAIL PROTECTED]>,
Carl Banks <[EMAIL PROTECTED]> wrote:
>Cameron Laird wrote:
>> In article <[EMAIL PROTECTED]>,
>> Carl Banks <[EMAIL PROTECTED]> wrote:
>>>Wildemar Wildenburger wrote:

 Are there any concepts that python has not borrowed, concepts that were
 not even inspired by other languages? I'm just interested if it is
 "merely" a best-of collection of language features or if there are
 actually inventions that have not - or hardly - existed in programming
 before python?
>>>
>>>Nesting by indentation
>>
>> You *do* realize this was present in ABC, among others, right?
>
>Yes.  I took the question to mean "what has Python made a commercial
>success out of that wasn't popular before", which I guess was taking
>quite a bit of liberty with it.  But he did give us the out of
>"hardly".  I think it would be fair to say nesting by indentation
>hardly existed before Python.

Yup.  I started following up to your post exactly as Cameron did before
I realized the rejoinder you were almost certain to make.  So I kept my
mouth shut.  ;-)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Edward Elliott
Anthony Liu wrote:
 > But, I want the random numbers just generated sum up
 > to 1 .

This seems like an odd request.  Might I ask what it's for?

Generating random numbers in [0,1) that are both uniform and sum to 1 looks 
like an unsatisfiable task.  Each number you generate restricts the 
possibilities for future numbers.  E.g. if the first number is 0.5, all 
future numbers must be < 0.5 (indeed, must *sum* to 0.5).  You'll end up 
with a distribution increasingly skewed towards smaller numbers the more 
you generate.  I can't imagine what that would be useful for.

If that's not a problem, do this: generate the numbers, add them up, and 
divide each by the sum.

nums = [random.uniform(0,1) for x in range(0,100)]
sum = reduce(lambda x,y: x+y, nums)
norm = [x/sum for x in nums]

Of course now the numbers aren't uniform over [0,1) anymore.

Also note that the sum of the normalized numbers will be very close to 1, 
but slightly off due to representation issues.  If that level of accuracy 
matters, you might consider generating your rands as integers and then 
fp-dividing by the sum (or just store them as integers/fractions).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Carl Banks
Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Carl Banks <[EMAIL PROTECTED]> wrote:
> >Wildemar Wildenburger wrote:
> >> Are there any concepts that python has not borrowed, concepts that were
> >> not even inspired by other languages? I'm just interested if it is
> >> "merely" a best-of collection of language features or if there are
> >> actually inventions that have not - or hardly - existed in programming
> >> before python?
> >
> >Nesting by indentation
>   .
> You *do* realize this was present in ABC, among others, right?

Yes.  I took the question to mean "what has Python made a commercial
success out of that wasn't popular before", which I guess was taking
quite a bit of liberty with it.  But he did give us the out of
"hardly".  I think it would be fair to say nesting by indentation
hardly existed before Python.


Carl Banks

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Mel Wilson
Anthony Liu wrote:
> I am at my wit's end.
> 
> I want to generate a certain number of random numbers.
>  This is easy, I can repeatedly do uniform(0, 1) for
> example.
> 
> But, I want the random numbers just generated sum up
> to 1 . 
> 
> I am not sure how to do this.  Any idea?  Thanks.

numbers.append (random.uniform (0, 1.0-sum(numbers)))

might help, perhaps.

or

scaled = [x/sum(numbers) for x in numbers]

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


Re: proposed Python logo

2006-04-21 Thread Grant Edwards
On 2006-04-21, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  Grant Edwards <[EMAIL PROTECTED]> wrote:
>
>>Sincy Python wasn't named after the snake, why the insistence
>>on using a snake in the logo?
> ...
>>I think something Monty Python related would be better.  How
>>about a nice can of spam?
>
> Six words: copyright violation ... trademark violation.

Hence my remarks about how it might upset Hormel.

IOW, I was kidding.

I have really been to the SPAM museum, though.  Since SPAM is
intimately connected to WWII in many peoples hearts and minds,
they had a bunch of WWII planes fly in for the SPAM museum
grand opening.  Way cool.  It's pretty impresive having a B-25
bomber taxi up to withing a couple dozen feet of you while you're
standing there stunned by the noise...

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


Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Michael Spencer
Anthony Liu wrote:
> I am at my wit's end.
> 
> I want to generate a certain number of random numbers.
>  This is easy, I can repeatedly do uniform(0, 1) for
> example.
> 
> But, I want the random numbers just generated sum up
> to 1 . 
> 
> I am not sure how to do this.  Any idea?  Thanks.
> 
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 

Divide each of your random numbers by their sum, perhaps?

Michael

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


Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Anthony Liu
I am at my wit's end.

I want to generate a certain number of random numbers.
 This is easy, I can repeatedly do uniform(0, 1) for
example.

But, I want the random numbers just generated sum up
to 1 . 

I am not sure how to do this.  Any idea?  Thanks.

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


Re: String To Dict Problem

2006-04-21 Thread Felipe Almeida Lessa
Em Sex, 2006-04-21 às 18:40 -0700, Clodoaldo Pinto escreveu:
> Only a small problem when I try to evaluate this:
> 
> safe_eval('True')

Change

def visitName(self,node, **kw):
raise Unsafe_Source_Error("Strings must be quoted", 
 node.name, node)

To
otherNames = {
'True': True,
'False': False,
'None': None
}

def visitName(self, node, **kw):
name = node.name
try:
return self.__class__.otherNames[name]
except KeyError:
raise Unsafe_Source_Error("Strings must be quoted", 
  name, node)


-- 
Felipe.

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

Re: String To Dict Problem

2006-04-21 Thread Michael Spencer
Clodoaldo Pinto wrote:
> Michael Spencer wrote:
> 
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469
> 
> Very nice work. It will be very useful. Thanks.
> 
> Only a small problem when I try to evaluate this:
> 
> safe_eval('True')
> 
> I get:
> 
> Traceback (most recent call last):
>   File "safe_eval.py", line 63, in ?
> safe_eval('True')
>   File "safe_eval.py", line 59, in safe_eval
> return walker.visit(ast)
>   File "safe_eval.py", line 19, in visit
> return meth(node, **kw)
>   File "safe_eval.py", line 23, in default
> return self.visit(child, **kw)
>   File "safe_eval.py", line 19, in visit
> return meth(node, **kw)
>   File "safe_eval.py", line 47, in visitName
> node.name, node)
> __main__.Unsafe_Source_Error: Line 1.  Strings must be quoted: True
> 
> This is just to let you know. I can live with that. I just replace True
> for 1.
> 
> Regards, Clodoaldo Pinto
> 
Alternatively, you could edit visitName to allow 'True' and any other 
identifiers you specify e.g. (untested):

 allowed = {"True": True, "False": False}
 def visitName(self,node, **kw):
try:
 return self.allowed[node.name]
 except KeyError:
 raise Unsafe_Source_Error("Strings must be quoted",
  node.name, node)

Cheers
Michael

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


Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Carl Banks <[EMAIL PROTECTED]> wrote:
>Wildemar Wildenburger wrote:
>> Are there any concepts that python has not borrowed, concepts that were
>> not even inspired by other languages? I'm just interested if it is
>> "merely" a best-of collection of language features or if there are
>> actually inventions that have not - or hardly - existed in programming
>> before python?
>
>Nesting by indentation
.
.
.
You *do* realize this was present in ABC, among others, right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String To Dict Problem

2006-04-21 Thread Clodoaldo Pinto
Michael Spencer wrote:

> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469

Very nice work. It will be very useful. Thanks.

Only a small problem when I try to evaluate this:

safe_eval('True')

I get:

Traceback (most recent call last):
  File "safe_eval.py", line 63, in ?
safe_eval('True')
  File "safe_eval.py", line 59, in safe_eval
return walker.visit(ast)
  File "safe_eval.py", line 19, in visit
return meth(node, **kw)
  File "safe_eval.py", line 23, in default
return self.visit(child, **kw)
  File "safe_eval.py", line 19, in visit
return meth(node, **kw)
  File "safe_eval.py", line 47, in visitName
node.name, node)
__main__.Unsafe_Source_Error: Line 1.  Strings must be quoted: True

This is just to let you know. I can live with that. I just replace True
for 1.

Regards, Clodoaldo Pinto

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


Re: perspective on ruby

2006-04-21 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Edward Elliott <[EMAIL PROTECTED]> wrote:

>XML?  Conceptually (and more elegantly) covered 
>as LISP s-expressions. 

"...Lisp is still #1 for key algorithmic techniques such as recursion 
and condescension."
-- Verity Stob 


>XSLT?  Just a bastardized spawn of Prolog.

As is any kind of pattern matching, including everyone's favourite 
regular expressions. Prolog did it all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Module Dependancies

2006-04-21 Thread mwt
Wow! Just ran pychecker on a couple of modules. I'm blown away by how
much information I'm getting. Thanks again!

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


Re: Finding Module Dependancies

2006-04-21 Thread mwt
Wow! Just ran pychecker on a couple of modules. I'm blown away by how
much information I'm getting. Thanks again!

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


Re: How to create a dictionary from a string?

2006-04-21 Thread Michael Spencer
Clodoaldo Pinto wrote:
> Is there a simple way to build a dictionary from a string without using
> eval()?
> 
 s = '{"a":1}'
 d = eval(s)
 d
> {'a': 1}
> 
> Regards, Clodoaldo Pinto
> 

Here is a discussion about one way to do it:
http://tinyurl.com/o8mmm

HTH
Michael

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


Re: Finding Module Dependancies

2006-04-21 Thread mwt

John Machin wrote:

>
> This is called "testing". Yes, it could take a long time.

Thanks for the clarification. ;)  Actually, I've done hellish amounts
of testing on these code pieces, which is why I don't want to have to
do it all over again just to check the imports.


>
> Consider pychecker and pylint. I haven't tried pylint, but pychecker
> does what you want and a whole lot more:
>
> C:\junk>type miss_import.py
> # need to import re, but forgot
> def my_isdigit(s):
>  return bool(re.match(r"\d+", s))
>
> C:\junk>pychecker miss_import
>
> C:\junk>c:\python24\python.exe
> c:\python24\Lib\site-packages\pychecker\checker.py miss_import
> Processing miss_import...
>
> Warnings...
>
> miss_import.py:3: No global (re) found
> 
> C:\junk>

That sounds really useful. I'll check it out. Thanks!

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


Re: Raising a specific OSError

2006-04-21 Thread Kelvie Wong
Looking at the Python docs.. I found this:
http://docs.python.org/ext/errors.html

"""
Another useful function is PyErr_SetFromErrno(), which only takes an
exception argument and constructs the associated value by inspection
of the global variable errno. The most general function is
PyErr_SetObject(), which takes two object arguments, the exception and
its associated value. You don't need to Py_INCREF() the objects passed
to any of these functions.
"""

So, in a C extension, to raise a a specific OSError...

errno = ENOENT;
PyErr_SetFromErrno(PyExc_OSError);

should work...

On 4/21/06, Kelvie Wong <[EMAIL PROTECTED]> wrote:
> I do not see the point in doing so (why not just copy+paste that
> string?), but the errno (specifically ENOENT) corresponds to the
> POSIX.1 error number, and the string "No such file or directory" is
> done in C via strerror(ENOENT); (check errno(3) and strerror(3)).
>
> I doubt there is something that does this in the standard library
> (just checked, there's an errno module, but it is quite sparse), but a
> simple C extension would be trivial to write.
>
> However, the best way is just to copy and paste that text into your
> program, I mean, why not?
>
> raise OSError("[Errno 2] No such file or directory")
>
> On 4/21/06, David Hirschfield <[EMAIL PROTECTED]> wrote:
> >  I wasn't clear enough in my original post.
> >
> >  I know how to raise a basic OSError or IOError, but what if I want to raise
> > specifically an "OSError: [Errno 2] No such file or directory"?
> >  Somehow it must be possible to raise the error with the correct information
> > to bring up the standard message, but where do I find the right values to
> > give?
> >
> >  Thanks,
> >  -Dave
> >
> >
> >
> >  alisonken1 wrote:
> >  To raise a specific error, just find the error that you want to raise,
> > then give the error a text string to print: ex.
> >
> > raise IOError("This raises an IO error")
> >
> > On the stderr output, when the routine hits this line, you will get:
> >
> >
> >
> >
> >
> >  raise IOError("This raises an IOError")
> >
> >  Traceback (most recent call last):
> >  File "", line 1, in ?
> > IOError: This raises an IOError
> >
> >
> >  Just be sure of the error that you want to raise, since some of them
> > will do stuff like closing open file descriptors as well.
> >
> >
> >
> >
> > --
> > Presenting:
> > mediocre nebula.
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> >
>
>
> --
> Kelvie
>


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


Re: Pythonesque interface.

2006-04-21 Thread Gaz
:)

Right now im trying to dl Jython (SF.net server down?), if it's
language sintaxis is just like Python and allows to use numpy and PIL,
im in! (i think :) )

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


Re: Raising a specific OSError

2006-04-21 Thread Kelvie Wong
I do not see the point in doing so (why not just copy+paste that
string?), but the errno (specifically ENOENT) corresponds to the
POSIX.1 error number, and the string "No such file or directory" is
done in C via strerror(ENOENT); (check errno(3) and strerror(3)).

I doubt there is something that does this in the standard library
(just checked, there's an errno module, but it is quite sparse), but a
simple C extension would be trivial to write.

However, the best way is just to copy and paste that text into your
program, I mean, why not?

raise OSError("[Errno 2] No such file or directory")

On 4/21/06, David Hirschfield <[EMAIL PROTECTED]> wrote:
>  I wasn't clear enough in my original post.
>
>  I know how to raise a basic OSError or IOError, but what if I want to raise
> specifically an "OSError: [Errno 2] No such file or directory"?
>  Somehow it must be possible to raise the error with the correct information
> to bring up the standard message, but where do I find the right values to
> give?
>
>  Thanks,
>  -Dave
>
>
>
>  alisonken1 wrote:
>  To raise a specific error, just find the error that you want to raise,
> then give the error a text string to print: ex.
>
> raise IOError("This raises an IO error")
>
> On the stderr output, when the routine hits this line, you will get:
>
>
>
>
>
>  raise IOError("This raises an IOError")
>
>  Traceback (most recent call last):
>  File "", line 1, in ?
> IOError: This raises an IOError
>
>
>  Just be sure of the error that you want to raise, since some of them
> will do stuff like closing open file descriptors as well.
>
>
>
>
> --
> Presenting:
> mediocre nebula.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


How to create a dictionary from a string?

2006-04-21 Thread Clodoaldo Pinto
Is there a simple way to build a dictionary from a string without using
eval()?

>>> s = '{"a":1}'
>>> d = eval(s)
>>> d
{'a': 1}

Regards, Clodoaldo Pinto

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


Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Tim Chase
> Actually, I can't think off the top of my head, any
> feature in the Java language (and I am making no
> assertions about the implementation of specific
> instances) that was truly innovative.

Let's see...it has bytecode compliation.  Oh...not original. 
Okay, howsabout cross-platform neutrality?  You mean 
there are others?!  Okay...how about a humongous class 
library?  Nah.  It's tough to call Java original...

Well, Java does have this great feature called "market-hype"...

-tkc









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


Re: Finding Module Dependancies

2006-04-21 Thread John Machin
On 22/04/2006 8:18 AM, mwt wrote:
> When I'm rewriting code (cutting and pasting pieces from earlier
> modules)

Instead of propagating multiple copies of source code, consider 
refactoring those modules so that top-level functions and classes can be 
used in other modules.

> is there a quick way to determine if I have imported all the
> necessary modules? I am used to working in Java, where the compiler
> will tell you if you haven't imported everything,

That's a clever design. It would be even better if it just shut up and 
did the imports for you :-)

> and also Eclipse,
> which has the handy "organize imports" feature. This is not the case in
> Python, since it's not compiled, of course, and also running it might
> not insure you've got all the imports, unless you go through every
> possible usage scenario -- which in some cases is quite a few, and
> could take a long time.

This is called "testing". Yes, it could take a long time.

> 
> So what I'm looking for is a command, like "check dependencies" or
> something, which will list all the modules needed for a source module
> to run.
> 

Consider pychecker and pylint. I haven't tried pylint, but pychecker 
does what you want and a whole lot more:

C:\junk>type miss_import.py
# need to import re, but forgot
def my_isdigit(s):
 return bool(re.match(r"\d+", s))

C:\junk>pychecker miss_import

C:\junk>c:\python24\python.exe 
c:\python24\Lib\site-packages\pychecker\checker.py miss_import
Processing miss_import...

Warnings...

miss_import.py:3: No global (re) found

C:\junk>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Module Dependancies

2006-04-21 Thread Larry Bates
mwt wrote:
> When I'm rewriting code (cutting and pasting pieces from earlier
> modules), is there a quick way to determine if I have imported all the
> necessary modules? I am used to working in Java, where the compiler
> will tell you if you haven't imported everything, and also Eclipse,
> which has the handy "organize imports" feature. This is not the case in
> Python, since it's not compiled, of course, and also running it might
> not insure you've got all the imports, unless you go through every
> possible usage scenario -- which in some cases is quite a few, and
> could take a long time.
> 
> So what I'm looking for is a command, like "check dependencies" or
> something, which will list all the modules needed for a source module
> to run.
> 
If you are an accomplished Eclipse user (I'm not), you should look at
the Python plug-in for Eclipse.

Remember that Python is so dynamic that you can build dependencies
during program execution and import them on-the-fly.  So a dependency
checker would always be incomplete.  You always need to write unit
tests.

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


Re: Jython: exec a string

2006-04-21 Thread Fabio Zadrozny
On 4/21/06, Edward Elliott <[EMAIL PROTECTED]> wrote:
iirc java doesn't like multiple classes in a single file (not countinganonymous or inner classes).  sounds like jython may have the samerestriction...Actually, that's not completely true. The restriction is that you can have only 1 public class in the top-level, but you can have other non-public top-level classes, and jython does not share that restriction.
abcd wrote:> the error i get when i run the exec is, "java.lang.ClassFormatError
"...>Could you post the examples you're using? In a simple test it works for me.Cheers,Fabio
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: what has python added to programming languages? (lets be esoteric, shall we ; )

2006-04-21 Thread Ravi Teja
>>"like the hashtable in java"

People don't give a reference to a language feature only because it
added/invented it but also because it is a popular one that many are
familiar with.

Java did not invent HashTables. They existed long before and were
available to most languages before Java. Neither is it even a Java
programming language feature (it's a class in it's standard library).

Actually, I can't think off the top of my head, any feature in the Java
language (and I am making no assertions about the implementation of
specific instances) that was truly innovative. But that's OK.
Incremental is good.

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


Re: Finding Module Dependancies

2006-04-21 Thread Fabio Zadrozny
Actually, if you use the pydev extensions plugin for Eclipse (http://www.fabioz.com/pydev), it would make that analysis for you (and is actually quite fast).Cheers,
FabioOn 21 Apr 2006 15:18:05 -0700, mwt <[EMAIL PROTECTED]> wrote:
When I'm rewriting code (cutting and pasting pieces from earliermodules), is there a quick way to determine if I have imported all thenecessary modules? I am used to working in Java, where the compilerwill tell you if you haven't imported everything, and also Eclipse,
which has the handy "organize imports" feature. This is not the case inPython, since it's not compiled, of course, and also running it mightnot insure you've got all the imports, unless you go through every
possible usage scenario -- which in some cases is quite a few, andcould take a long time.So what I'm looking for is a command, like "check dependencies" orsomething, which will list all the modules needed for a source module
to run.--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

converting xmllib to xml.sax

2006-04-21 Thread Sakcee
Hi

I am trying to convert an override of xmllib.XMLparser , in the
handle_doctype method we are catching the entities using
load_dtd(sysid).gen_ents

how can I do the same with xml.sax, does xml.sax has anything to catch
the entties


thanks

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


Re: Powerful Command line parsers

2006-04-21 Thread John Machin
On 22/04/2006 4:15 AM, PyPK wrote:
> Is there a Command line parser in python that can:
> 1. resolve conflicts
> 2. specify something like requires
> 3. and smart

"... that can ... and smart" does not compute.

> 
> for ex:
> python test.py --a --b --c --d

I'm used to seeing --fubar and -f; what does --f mean?

> 
> Case 1:
> If 'a' is an option 'b' or 'c' cannot be specified.
> 
> Case 2:
> atleast one option should be specified
> 
> Case 3:
> IF 'a' and 'c' are given then 'd' has to be given
> 
> or  many such cases.
> 
> I was wondering as this is a very common problem there if there is a
> module that could do these things .
> 'optparse' is not this smart I guess.

Modules are neither dumb nor smart. The author of optparse is IMHO 
smart; it does just about what it ought to do.

To meet your specifications, the module would need to incorporate a 
mini-language:

if a and (b or c): nasty("blah 1")
if not (a or b or c or d): nasty("blah 2")
if a and c and not d: nasty("blah 3")

Again IMHO, it would be an enormous waste of effort to implement such a 
mini-language inside a command-line parser, when the call to the parser 
  can be followed by whatever conditions and actions you like, written 
in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonesque interface.

2006-04-21 Thread alisonken1
OP = Original Poster

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


Re: lambda

2006-04-21 Thread Ben C
On 2006-04-21, Alexis Roda <[EMAIL PROTECTED]> wrote:
> Ben C escribió:
>> On 2006-04-21, Ben C <[EMAIL PROTECTED]> wrote:
>> Having said that, I attempted to confirm this using def rather than
>> lambda, and encountered something I cannot explain at all-- it appears
>> that the functions are getting redefined whenever they are called, to
>> effect a kind of "dynamic scoping" behaviour. I would appreciate any
>> explanation anyone can give of this:
>> 
>> fns = []
>> for y in range(2):
>>  def fn():
>>  yy = y  # exactly the same with yy = int(y)
>>  print "defining fn that returns", yy
>>  return yy
>>  print "Appending at", y
>>  print fn, fn()
>>  fns.append(fn)
>
>
> yy = y does assign y's current value (current == fn call time, not fn 
> definition time). To return 0 and 1 as expected you should create a 
> "different/private" y for every fn's definition.
>
> 
>
> fns = []
> for y in range(2):
>   def fn(y=y):
>   yy = y
>   print "defining fn that returns", yy
>   return yy
>   print "Appending at", y
>   print fn, fn()
>   fns.append(fn)
>
>
> 

Yes; the difficulty is that the body of the function is executed
(obviously) every time you call it. The body of the function reads y
which is a global variable and has whatever value it has at the time.

The parameters are the only part of a function definition where you get
to write some code that initializes things in the function's "frame"
when the function is defined rather than when it's called.

I got confused because I was thinking of yy = y in the body of fn's
definition as an initialization, not as an assignment. In other
languages it's possible to distinguish, but not in Python.

Really this is what classes are for in Python:

def f(x):
return x * x

class fn(object):
def __init__(self, y):
# "define-time" things are here
self.y = y

def __call__(self, x):
# "call-time" things are here
return f(x) * self.y

fns = [fn(i) for i in range(1, 10)]
for f in fns:
print f(1)

is I think quite a good way to do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonesque interface.

2006-04-21 Thread Gaz
OP?

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


Re: proposed Python logo

2006-04-21 Thread Carl J. Van Arsdall
Lawrence D'Oliveiro wrote:
> In article <[EMAIL PROTECTED]>,
>  Grant Edwards <[EMAIL PROTECTED]> wrote:
>
>   
>> Sincy Python wasn't named after the snake, why the insistence
>> on using a snake in the logo?
>> 
> ...
>   
>> I think something Monty Python related would be better.  How
>> about a nice can of spam?
>> 
>
> Six words: copyright violation ... trademark violation.
>   

Six? 

Looks more like 4 to me.



-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Can you create an instance of a subclass with an existing instance of the base class?

2006-04-21 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "Sandra-24" <[EMAIL PROTECTED]> wrote:

>Can you create an instance of a subclass using an existing instance of
>the base class?

I think you're taking Python's OO-ness too seriously. One of the 
strengths of Python is that it can _look_ like an OO language without 
actually being OO.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposed Python logo

2006-04-21 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "Michael Tobis" <[EMAIL PROTECTED]> wrote:

>I think the colon as snake-eyes thing is a big win

I liked that bit too. Whatever changes are made, that should be kept.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Updated PEP 359: The make statement

2006-04-21 Thread Steven Bethard
Tim Roberts wrote:
> Steven Bethard <[EMAIL PROTECTED]> wrote:
> 
>> Steven Bethard wrote:
>>> I've updated PEP 359 with a bunch of the recent suggestions. ...
>> Guido has pronounced on this PEP:
>>http://mail.python.org/pipermail/python-3000/2006-April/000936.html
>> Consider it dead. =)
> 
> I tried to follow the thread backwards and find out what proposed change in
> the "class" construct would render "make" unnecessary, but I couldn't find
> it.  Can you summarize, Steven?

The make statement was mostly syntactic sugar for::

class  :
__metaclass__ = 


So was technically unnecessary from the beginning. ;)  Here's the one 
post where he presented a few reasons he didn't like it:

http://mail.python.org/pipermail/python-3000/2006-April/000704.html

He didn't say a whole lot else about it, but when he mentioned that he'd 
like the discussion to end, I offered to end it. ;)

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


Re: proposed Python logo

2006-04-21 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Grant Edwards <[EMAIL PROTECTED]> wrote:

>Sincy Python wasn't named after the snake, why the insistence
>on using a snake in the logo?
...
>I think something Monty Python related would be better.  How
>about a nice can of spam?

Six words: copyright violation ... trademark violation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposed Python logo

2006-04-21 Thread Grant Edwards
On 2006-04-21, Michael Tobis <[EMAIL PROTECTED]> wrote:

> This http://www.informatik.uni-trier.de/~roth/bilder/mpfc/GUMBY3.JPG
> chap?
>
> I'm not sure that conveys the intended gravitas to the
> corporate community, though.

Monty Python never was very big on "corporate community
gravitas", so that's probably going to be a persistent problem
should one try to find a Monty Pythonesque logo.

-- 
Grant Edwards   grante Yow!  Do I have a lifestyle
  at   yet?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyLint results?

2006-04-21 Thread Felipe Almeida Lessa
Em Sex, 2006-04-21 às 13:49 -0400, Michael Yanowitz escreveu:
>I ran the new pylint and my code and I had a few questions on why those
> are warnings or what I can do to fix them:

You can ignore the warnings you don't like with the --disable-msg
option. Also, you can add a header to the file to apply a rule just to
it.

> 1) W:  0: Too many lines in module (1587)
>  Why is 1587 considered too many lines? Would there be necessarily be an
>advantage to split it up into 2 or 3 files? Can I up the limit?

Because Python is terse, and this can be a really large module. Or not.
PyLint is not perfect, maybe you should disable this warning.

> 2) C:  0: Missing required attribute "__revision__"
>What is this? Is that for CVS? I don't use CVS (we use SVN). I have not
>seen any sample code which includes this tag yet. But if I include
>__revision 1.0  somewhere in the code it will remove that warning?

Don't include the variable just to remove the warning -- disable it.

> 3) W:230:readDiscreteData: Using the global statement
>What is wrong with using the global statement? 

Your code can get unmaintainable if you abuse of it. If you really need
it and know how to use it well, disable the warning. 

> 4) W:261:getDiscreteData: Catch "Exception"
>What is wrong with that?

You may catch things you don't want to catch, like KeyboardInterrupt
exceptions.

> 5) R:547:readDiscreteData: Too many branches (28/12)
>Python doesn't have the switch/case statements that C/C++ have. So I
>could have a large block if/elif/else statements.
>Is there any way to avoid that?

Only splitting the method into 2 or more parts. If that's not possible,
disable the warning.

> 6) R:722:waitDiscretes: Too many local variables (38/15)
>That's new to me. What is wrong with too many local variables?
>Can anything be done to improve that besides having too many globals?

The more local variables you have, the more difficult the code is to
read. Or you use less variables, or you split the method into 2 or more
parts, or you disable the warning.

> 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer scope
> (line
>What is wrong with using the same variable name in a function that is
> used by its caller?

You are hiding something. For example, this code fails strangely (I know
this example isn't that good, but you get the idea):

files = glob('something/*')
for file in files:
# do_something 
filename = do_something_with_the_name(file)
# do_something_more
contents = file(filename).read() # fails here

> 8) W:995:sendStringToSocket: Used builtin function 'map'
>Is that a problem?

Sometimes it's slower than list comprehensions, sometimes it's less
legible than list comp. and IIRC GvR doesn't like it, but if you do,
disable the warning.

HTH,

-- 
Felipe.

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

Re: Raising a specific OSError

2006-04-21 Thread David Hirschfield




I wasn't clear enough in my original post.

I know how to raise a basic OSError or IOError, but what if I want to
raise specifically an "OSError: [Errno 2] No such file or directory"?
Somehow it must be possible to raise the error with the correct
information to bring up the standard message, but where do I find the
right values to give?

Thanks,
-Dave


alisonken1 wrote:

  To raise a specific error, just find the error that you want to raise,
then give the error a text string to print: ex.

raise IOError("This raises an IO error")

On the stderr output, when the routine hits this line, you will get:

  
  

  
raise IOError("This raises an IOError")

  

  
  Traceback (most recent call last):
  File "", line 1, in ?
IOError: This raises an IOError

  
  
Just be sure of the error that you want to raise, since some of them
will do stuff like closing open file descriptors as well.

  


-- 
Presenting:
mediocre nebula.



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

Re: proposed Python logo

2006-04-21 Thread Michael Tobis
A more Monty sort of Python logo would be fine with me. A flying sheep
perhaps? An exploding penguin? A giant hedgehog? A dog license with the
word "dog" crossed out and "cat" written in crayon? A great big book on
how to put your budgie down?

This http://www.informatik.uni-trier.de/~roth/bilder/mpfc/GUMBY3.JPG
chap?

I'm not sure that conveys the intended gravitas to the corporate
community, though.

mt

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


Re: Raising a specific OSError

2006-04-21 Thread alisonken1

To raise a specific error, just find the error that you want to raise,
then give the error a text string to print: ex.

raise IOError("This raises an IO error")

On the stderr output, when the routine hits this line, you will get:

>>> raise IOError("This raises an IOError")
Traceback (most recent call last):
  File "", line 1, in ?
IOError: This raises an IOError

>>>

Just be sure of the error that you want to raise, since some of them
will do stuff like closing open file descriptors as well.

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


Re: proposed Python logo

2006-04-21 Thread Tim Parkin
BartlebyScrivener wrote:
>>>(and it's an older version of the logo) because
>>>you can get T-Shirts from cafepress.com/pydotorg and any profits go to
>>>the psf.
> 
> 
> I just ordered some stuff from cafe press, are you saying I'm getting
> an old version of the logo?
> 

An alternate 'collectors' rendition of the new logo as used by Guido Van
Rossum in his recent New York Google presentations and also as on
t-shirts, mugs and flags handed out during EuroPython 2005!

Tim Parkin

p.s. was that good enough spin for you ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Raising a specific OSError

2006-04-21 Thread David Hirschfield
I know this should be obvious, but how does one raise a specific type of 
OSError?
When I attempt to perform a file operation on a non-existent file, I get 
an OSError: [Errno 2], but what if I want to raise one of those myself?

Thanks in advance,
-Dave

-- 
Presenting:
mediocre nebula.

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


Finding Module Dependancies

2006-04-21 Thread mwt
When I'm rewriting code (cutting and pasting pieces from earlier
modules), is there a quick way to determine if I have imported all the
necessary modules? I am used to working in Java, where the compiler
will tell you if you haven't imported everything, and also Eclipse,
which has the handy "organize imports" feature. This is not the case in
Python, since it's not compiled, of course, and also running it might
not insure you've got all the imports, unless you go through every
possible usage scenario -- which in some cases is quite a few, and
could take a long time.

So what I'm looking for is a command, like "check dependencies" or
something, which will list all the modules needed for a source module
to run.

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


Re: how to append to a list twice?

2006-04-21 Thread Peter Otten
John Salerno wrote:

> If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...]
> (where each item is repeated twice after the first one), how might I do
> that most efficiently?

series = [100]*21
series[1::2] = series[2::2] = range(99, 89, -1)

:-)

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


Re: Pythonesque interface.

2006-04-21 Thread bearophileHUGS
Michael Tobis>Yes but he obviously wants this to be delivered to the
browser.<

I think Jython can be used to create applets that run with the JavaVM.
Can't it be used to solve the OP problem (even without PIL)?

Bye,
bearophile

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


Re: Tkinter hiding/showing widgets

2006-04-21 Thread Philippe Martin
Maybe like this ?

http://www.faqts.com/knowledge_base/view.phtml/aid/21215/fid/264


I noticed with wxWidget, which uses the same packing principle (xlib
inheritance ?) that hidding a widget can have a strange effect on the
layout of the "other guys" still visible ... so I just disable them now
instead of hiding them.

Regards,

Philippe




Anony wrote:

> Is it possible to hide and show widgets while the window is open?

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


Re: Announce: RPyC's wiki!

2006-04-21 Thread gangesmaster
[for people who missed my previous posts]

"""RPyC is a transparent, symmetrical python library for
distributed-computing. Pronounced "are-pie-see", it began as an RPC
library (hence the name), but grew into something much more
comprehensive with many use cases. It basically works by giving you
full control over a remote slave-interpreter (a separate process),
which performs operations on your behalf."""



-tomer

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


Announce: RPyC's wiki!

2006-04-21 Thread gangesmaster
the RPyC's project page has moved to
http://rpyc.wikispaces.com

the old site (http://rpyc.sourceforge.net) redirects there now. because
it's the official site, i chose to limit changes to members only.

it's so much easier to maintain the wiki that the crappy htmls at
sourceforge :)
anyway, the new site contains much more info and is organized better.

i'm currently working on:
* more documentation on the wiki
* version 2.50 - fix a bug with multiple threads using the same
connection.

version 2.46 is ready, but as it provides nothing critical, i dont find
a reason to release it now. you''ll need to wait for 2.50 (somewhere in
May/June i guess)



-tomer

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


Re: lambda

2006-04-21 Thread Alexis Roda
Ben C escribió:
> On 2006-04-21, Ben C <[EMAIL PROTECTED]> wrote:
> Having said that, I attempted to confirm this using def rather than
> lambda, and encountered something I cannot explain at all-- it appears
> that the functions are getting redefined whenever they are called, to
> effect a kind of "dynamic scoping" behaviour. I would appreciate any
> explanation anyone can give of this:
> 
> fns = []
> for y in range(2):
>   def fn():
>   yy = y  # exactly the same with yy = int(y)
>   print "defining fn that returns", yy
>   return yy
>   print "Appending at", y
>   print fn, fn()
>   fns.append(fn)


yy = y does assign y's current value (current == fn call time, not fn 
definition time). To return 0 and 1 as expected you should create a 
"different/private" y for every fn's definition.



fns = []
for y in range(2):
def fn(y=y):
yy = y
print "defining fn that returns", yy
return yy
print "Appending at", y
print fn, fn()
fns.append(fn)




fns = []
def factory(y) :
def fn() :
yy = y
print "defining fn that returns", yy
return yy
return fn

for y in range(2) :
fn = factory(y)
print "Appending at", y
print fn, fn()
fns.append(fn)




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


Re: Read and extract text from pdf

2006-04-21 Thread Jim
There is a pdftotext executable, at least on Linux.

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


Re: Recommended IDE for creating GUI?

2006-04-21 Thread Edward Elliott
can anyone here comment on boa constructor?
http://boa-constructor.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython: exec a string

2006-04-21 Thread Edward Elliott
iirc java doesn't like multiple classes in a single file (not counting 
anonymous or inner classes).  sounds like jython may have the same 
restriction...

abcd wrote:
> the error i get when i run the exec is, "java.lang.ClassFormatError"...
> 
> thanks
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposed Python logo

2006-04-21 Thread BartlebyScrivener
>> (and it's an older version of the logo) because
>> you can get T-Shirts from cafepress.com/pydotorg and any profits go to
>> the psf.

I just ordered some stuff from cafe press, are you saying I'm getting
an old version of the logo?

rick

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


Re: PyLint results?

2006-04-21 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Michael
Yanowitz wrote:

> 2) C:  0: Missing required attribute "__revision__"
>What is this? Is that for CVS? I don't use CVS (we use SVN). I have not
>seen any sample code which includes this tag yet. But if I include
>__revision 1.0  somewhere in the code it will remove that warning?

AFAIK that's a requirement at Logilab.  They use the tool themselves.  :-)

> 3) W:230:readDiscreteData: Using the global statement
>What is wrong with using the global statement? I know the use of Globals
>should be discouraged, but often they can't be avoided.

I guess more often than you think.

>Suppose I have a constant. In C or C++, I could just use a #define and
>it would be known throughout the whole file. In Python, there isn't a
>similar construct, so rather than creating a large parameter list, of
>constants, I like to use globals.

If they are constants then you don't rebind them from within functions or
methods, right?  Then you don't need ``global``.  This works without
problems::

 ANSWER = 42

 def spam():
 print ANSWER


> 4) W:261:getDiscreteData: Catch "Exception"
>What is wrong with that?

It catches *any* exception.  For example `KeyboardInterrupt` which can
lead to programs that can't be stopped with CTRL+C or `ZeroDivisionError`
or `NameError` so programming errors are silenced.

> 5) R:547:readDiscreteData: Too many branches (28/12)
>Python doesn't have the switch/case statements that C/C++ have. So I
>could have a large block if/elif/else statements.
>Is there any way to avoid that?

One idiom is to create a dictionary with the values to "switch on" mapped
to callables to handle the case.

> 6) R:722:waitDiscretes: Too many local variables (38/15)
>That's new to me. What is wrong with too many local variables?

Well, they are just to many.  :-)

> 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer scope
> (line
>What is wrong with using the same variable name in a function that is
> used by its caller?

It's not used by the caller but in the outer scope.  It may confuse the
reader seeing `ham` in the outer scope and then `ham` in the function
without noticing that this is actually another `ham`.

> 8) W:995:sendStringToSocket: Used builtin function 'map'
>Is that a problem?

`map` is "deprecated" in favor of list comprehensions.  A matter of taste…

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

Re: Looking for a programming resource for newbees

2006-04-21 Thread Evgeny
maybe
How to Think Like a Computer Scientist:
http://www.ibiblio.org/obp/thinkCSpy/
will help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommended IDE for creating GUI?

2006-04-21 Thread petrov
http://wxglade.sourceforge.net/ - WxGlade is one option. It is quite
helpful although somewhat unstable.

http://wingware.com/ - is an IDE i dont remember if it has a UI
builder. Probably worth checking anyway.

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


Tkinter hiding/showing widgets

2006-04-21 Thread Anony
Is it possible to hide and show widgets while the window is open?

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


www.python.org problems

2006-04-21 Thread Aahz
Before people start sending a flood of e-mail to webmaster, we already
know that www.python.org is having problems.  Please be patient.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython: exec a string

2006-04-21 Thread abcd
the error i get when i run the exec is, "java.lang.ClassFormatError"...

thanks

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


Re: Thanks from the Java Developer

2006-04-21 Thread John Salerno
Kent Johnson wrote:

>> At least in the Bay Area, the jobmarket for Python programmers is wild,
>> right now -- firms such as Google, Pixar, BitTorrent, IronPort, etc,
>> etc, all hungry for Pythonistas -- BayPIGgies mailing list bitching over
>> too many job-offer posts, and the nuisance of all those recruiters
>> haunting our monthly meetings and how much time they take, ...!!!
> 
> Hmm...eagerly awaiting this phenomenon to reach the Boston area.

Hey, I was just thinking the same thing! Of course, what I'm *really* 
waiting for is the "looking for people who like to *think* they are 
Python developers but aren't really" trend to hit Boston.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BIOCHIP --->>> NO GOOD !!

2006-04-21 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Petr Prikryl wrote:

> rainbow.cougar wrote in message
>> okay wrote:
>> > To Archbishop Christodoulos Paraskevaides of the Greek Orthodox Church
>> > in Athens and Greece Archbishop,
>> > I talked with a Greek Orthodox believer in Australia and he told me two
>>
>> I'm thinking a list comprehension...
> 
> Possibly some filter(map()) for the really orthodox believers...

And ``ifilter(imap(…))`` for the reformists.

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

Re: threading, how to?

2006-04-21 Thread akrapus
Thanks a lot to all of you guys.
I think it'll take some time before I grasp it properly...

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


Re: win32com.client.constants - AttributeError

2006-04-21 Thread kbperry
Wow..I didn't even realize that this existed.  Thanks for your help!

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


Jython: exec a string

2006-04-21 Thread abcd
I have a single jython file, foo.py which contains multiple classes.  I
read that into a string and try to exec itbut I get errors saying
something like unable to load class.  It seems to work fine if foo.py
only contains a single class, any ideas?

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


Re: lambda

2006-04-21 Thread rubbishemail
Hello Alexis,

thank you for the fast help!
I am not against lambdas, but, sometimes they are a bit confusing to
me, especially as you don't see many examples used.


Daniel

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


Re: lambda

2006-04-21 Thread Ben C
On 2006-04-21, Ben C <[EMAIL PROTECTED]> wrote:
> On 2006-04-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> Hello,
>>
>> I need your help understanding lambda (and doing it a better way
>> without).
>>
>> f  = lambda x : x*x
>> [...]
>> # the idea is now to give the definition of the multiplication of
>> functions and integers
>> # (f * c)(xx) := f(x)*c
>> [lambda xx: f(xx)*y for y in range(1,5)][0](1)
>> # returns 4
>> # I would expect 1*x*x = 1
>
> If you change the 5 in range(1,5) to a 10, this returns 9.
>
> So it looks like each of the lambda xx : f(xx) * y is getting the last
> value of y.
>
> I can do this for example:
>
> f = lambda x : x * x
> fns = [lambda xx: f(xx)*y for y in range(1,10)]
> for fn in fns:
>   print fn(1)
>
> And I get 9 printed out 9 times.
>
> It does seem a bit surprising, but I suppose if you think about it
> there's only one "y"-- the one in the outer scope. This one variable is
> bound 9 times, to a new value each time.
>
> What one would need for it to work would be for each of the functions to
> have a variable in its own scope. But you can't, as far as I know,
> create local variables in functions defined with lambda.

Having said that, I attempted to confirm this using def rather than
lambda, and encountered something I cannot explain at all-- it appears
that the functions are getting redefined whenever they are called, to
effect a kind of "dynamic scoping" behaviour. I would appreciate any
explanation anyone can give of this:

fns = []
for y in range(2):
def fn():
yy = y  # exactly the same with yy = int(y)
print "defining fn that returns", yy
return yy
print "Appending at", y
print fn, fn()
fns.append(fn)

print "OK"

for fn in fns:
print "Calling", fn
print fn, fn()

y = 10

for fn in fns:
print "Calling", fn
print fn, fn()

The output:

Appending at 0
 defining fn that returns 0
0
Appending at 1
 defining fn that returns 1
1
OK
Calling 
 defining fn that returns 1
1
Calling 
 defining fn that returns 1
1
Calling 
 defining fn that returns 10
10
Calling 
 defining fn that returns 10
10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strategy Design Pattern

2006-04-21 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Daniel  Santa
Cruz wrote:

> In the specific case of the Strategy pattern, I think the goal is to
> abstract out of the class an algorithm that can then be reused by some
> of the inherited classes.  This way we don't repeat ourselves.  Maybe I
> got this all wrong...

IMHO yes.  The goal isn't to reuse the algorithm elsewhere but to plug in
different algorithms into the "main class", which is called `context` in
the GoF book.

> Abstract Base Class: Duck
> + FlyBehavior _fly
> + swim()
> + fly() -> calls _fly.fly()
> 
> Interface: FlyBehavior
> + fly()
> 
> Concrete Interface FlyHigh (implements FlyBehavior): + fly()
> 
> Concrete Class Duck1 (Inherits Duck): + Constructor: _fly = new
> FlyHigh()

No need to make a subclass of `Duck` and the base class should not be
abstract but take a strategy in the constructor instead.

Silly, contrived example with ducks (the `context`):

class Duck(object):
def __init__(self, fly_strategy=lambda duck: None):
self._fly = fly_strategy
self.battery = 100.0# Percent.

def fly(self):
self._fly(self)

A dumb strategy:

def flap_as_fast_as_you_can(duck):
duck.battery -= 5

And a more sophisticated one:

def ExploitThermodynamics(object):
def __init__(self):
# Initialize data structures to keep track of wind, target etc.

def __call__(self, duck):
# Check wind, update data and change the heading of the duck
# accordingly.
duck.battery -= used_power

Now some ducks:

no_fly_duck = Duck()
fast_but_soon_tired_duck = Duck(flap_as_fast_as_you_can)
gliding_duck = Duck(ExploitThermodynamics())

If the `strategy` is a callable one can decide if a simple function is
sufficient or if the `strategy` needs some state that must be preserved
between calls to the strategy object.

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


Re: win32com.client.constants - AttributeError

2006-04-21 Thread Roger Upole
There are a couple of different ways to run makepy.
Start Pythonwin, and from the menu select
Tools->Com Makepy Utility.  You should see a list
of registered typelibs.  Select "Microsoft Word x.y
Object Library" and hit Ok.
This can also be done programatically by initiating
Word with
win32com.client.gencache.EnsureDispatch('Word.Application')

  Roger

"kbperry" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> how do I do this?  Where is the Word object library?
> 



== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to append to a list twice?

2006-04-21 Thread Gerard Flanagan
John Salerno wrote:
> If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...]
> (where each item is repeated twice after the first one), how might I do
> that most efficiently?
>
> Right now I have this:
>
> series = [100]
> for x in range(10):   # just for testing
>  series.append(series[-1] - 1)
>
> But of course that only does it once, and I don't want to have to copy
> and paste the append line. Perhaps there's a better way than this.
>
> Thanks.


series = [100] + [ t for t in range(99,90,-1) for _ in [0,1] ]

(what's wrong with two appends again...?)

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


Can you create an instance of a subclass with an existing instance of the base class?

2006-04-21 Thread Sandra-24
Can you create an instance of a subclass using an existing instance of
the base class?

Such things would be impossible in some languages or very difficult in
others. I wonder if this can be done in python, without copying the
base class instance, which in my case is a very expensive object.

Any ideas?

Thanks,
-Sandra

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


Re: how to append to a list twice?

2006-04-21 Thread Dave Hansen
On 21 Apr 2006 12:50:38 -0700 in comp.lang.python,
[EMAIL PROTECTED] wrote:

>I don't get it (the Elliot solution)... How is it that the first value
>is repeated once times, and the remaining values are repeated twice
>times?

Integer division truncates.  200/2 -> 100, 199/2 -> 99, 198/2 -> 99,
etc.  Regards,

-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposed Python logo

2006-04-21 Thread Tim Parkin
Michael Tobis wrote:
> 
> That said, and conceding that the first impression is positive, I don't
> see how it represents Python. More to the point, the longer I look at
> it the less I like it, and I would NOT wear it on a T-shirt.
> 

over 25 people disagree with you so far and thats without any
advertising whatsoever (and it's an older version of the logo) because
you can get T-Shirts from cafepress.com/pydotorg and any profits go to
the psf.

I'll add the new logo over the weekend.

> 
>>The + formation is positive enough, and it has a yin-yang
>>feel to it which to me conjures up the image of balance, not
>>divisiveness.
> 
> Both the cross and the yin-yang have religious associations, which will
> be positive for some and negative for others but will certainly be
> unrepresentative of what Python is. This would be a great logo for
> Taoist Christians, if such a group exists.
> 
> How is Python about "balance"? It is about abstraction, composition,
> the whole greater than the parts, yes, but there's nothing there that
> really draws on duality. So the whole two-ness of the thing is one of
> the parts that disturbs me.
>

They're freindly snakes at a tadpole fancy dress competition having a
'cuddle'. Where do you think Python eggs come from...

Tim Parkin

p.s. the logo is actually based on mayan representations of snakes which
very often represent only the head and perhaps a short length of tail.
The structure of the snake representations the natural coiling/nesting
of a snake as seen side on.. The following image shows a similar
representation (we have a snake house nearby which makes it easier to
observe behaviour)

http://www.xcalak.info/images/florafauna/fer_de_lance_l.jpg

The mesoamerican calendar also represents snake heads in a similar manner.

http://en.wikipedia.org/wiki/Tzolkin

The abstraction of the snake design used in mayan culture seemed
non-denominational enough to only raise contrived objections. The shapes
used (cross/spiral/yin-yang) are also primitive enough that there will
always be connotations that can be derived.

http://www.alovelyworld.com/webhon/gimage/hdu011.jpg

http://www.khoahoc.com.vn/photos/Image/2005/11/16/maya-snake.jpg

http://www.xcalak.info/images/florafauna/fer_de_lance_l.jpg

The two headed snake was also an influence on the design

http://www-personal.umich.edu/~bjayatil/British%20Museum%20&%20London/slides/17-aztec_snake.html

which is also a common 'meme' in many continents, including africa

http://www.sfu.ca/archaeology/museum/ndi/cam5.jpg

And I'd like to see you tell a civil war soldier that it looks like his
trousers are held up by a two headed tadpole

http://www.civilwarrelics.com/museum/graphics/Frame25a.JPG

If you look carefully at the logo, you will also see an indian symbol of
peace.. (I'll leave this one alone as it can also mean something else).



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


Re: Thanks from the Java Developer

2006-04-21 Thread Ant
> So switch jobs -- it's a good time.

If it were that easy I would.. However, I have family commitments
keeping me in Yorkshire (UK) (as well as the fact that I really like
the area!), and the jobs in the area are all Java, .NET (predominantly
C#) and C++.

Always on the lookout for Python work though, and I actively try to
inject at least a bit of it into the work I do, even if it's just
scripts or test programs.

When the time comes, I'll be there though :-)

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


Re: Recommended IDE for creating GUI?

2006-04-21 Thread Anony
Marty Christion wrote:
> What are some good free or inexpensive (<$50) IDE's for learning how to
> program and create GUI's for Python?  I'm pretty good with the simple
> programming aspect of the language, but I'm a little mystified by the world
> of GUI's, and the options available in python.

I have 2 links for basic use of Tkinter (but Tkinter doesn't work
correctly on Macs as I have read):
http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf
http://www.pythonware.com/library/tkinter/an-introduction-to-tkinter.pdf

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


Re: how to append to a list twice?

2006-04-21 Thread John Salerno
John Salerno wrote:
> [EMAIL PROTECTED] wrote:
>> I don't get it (the Elliot solution)... How is it that the first value
>> is repeated once times, and the remaining values are repeated twice
>> times?
>>
> 
> Because of the way division works. The first number in the range is 200, 
> and 200/2 is 100. The next number is 199, and 199/2 is (as division 
> works right now) 99 (99.5 rounded). Next is 198, and that halved is also 
> 99 (this time with no remainder). Every two sets of numbers thereafter 
> also do the same.

I should also say, to answer your question more directly, that the 
reason it doesn't happen to the first number is because it only works on 
an odd number and the number below it, i.e. 199 and 198 both yield 99. 
If our range had started with 201, then 100 would have been repeated twice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda

2006-04-21 Thread Mel Wilson
[EMAIL PROTECTED] wrote:
> Hello,
> 
> I need your help understanding lambda (and doing it a better way
> without).
> 
> f  = lambda x : x*x
[ ... ]
> # the idea is now to give the definition of the multiplication of
> functions and integers
> # (f * c)(xx) := f(x)*c
> [lambda xx: f(xx)*y for y in range(1,5)][0](1)
> # returns 4
> # I would expect 1*x*x = 1

I think you have to get the value of y at definition time, 
not at call time:

 >>> z=[lambda xx, yy=y: (f(xx)*yy) for y in xrange(1,5)]
 >>> z[0](1)
1

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


Re: win32com.client.constants - AttributeError

2006-04-21 Thread kbperry
Please help!  Anyone else know?

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


Re: how to append to a list twice?

2006-04-21 Thread John Salerno
[EMAIL PROTECTED] wrote:
> I don't get it (the Elliot solution)... How is it that the first value
> is repeated once times, and the remaining values are repeated twice
> times?
> 

Because of the way division works. The first number in the range is 200, 
and 200/2 is 100. The next number is 199, and 199/2 is (as division 
works right now) 99 (99.5 rounded). Next is 198, and that halved is also 
99 (this time with no remainder). Every two sets of numbers thereafter 
also do the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda

2006-04-21 Thread Ben C
On 2006-04-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I need your help understanding lambda (and doing it a better way
> without).
>
> f  = lambda x : x*x
> [...]
> # the idea is now to give the definition of the multiplication of
> functions and integers
> # (f * c)(xx) := f(x)*c
> [lambda xx: f(xx)*y for y in range(1,5)][0](1)
> # returns 4
> # I would expect 1*x*x = 1

If you change the 5 in range(1,5) to a 10, this returns 9.

So it looks like each of the lambda xx : f(xx) * y is getting the last
value of y.

I can do this for example:

f = lambda x : x * x
fns = [lambda xx: f(xx)*y for y in range(1,10)]
for fn in fns:
print fn(1)

And I get 9 printed out 9 times.

It does seem a bit surprising, but I suppose if you think about it
there's only one "y"-- the one in the outer scope. This one variable is
bound 9 times, to a new value each time.

What one would need for it to work would be for each of the functions to
have a variable in its own scope. But you can't, as far as I know,
create local variables in functions defined with lambda.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to append to a list twice?

2006-04-21 Thread callmebill
I don't get it (the Elliot solution)... How is it that the first value
is repeated once times, and the remaining values are repeated twice
times?

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


Re: send cookie on request with urllib2

2006-04-21 Thread John J. Lee
"itay_k" <[EMAIL PROTECTED]> writes:

> ok.
> i will explain what exactly i wanna do.
> 
> i want to simulate the following client-side script with python:
> 
> 
> 
> 
> document.cookie="name=tom";
> document.images["Pic"].src="temp2.html"
> 

Ah!  In which case what you're trying to do is a reasonable hack, but
better (UNTESTED):

import urllib2, cookielib
cj = cookielib.CookieJar
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
request = urllib2.Request(url)
response = opener.open(request)
response["Set-Cookie"] = "name=tom"
cj.extract_cookies(response, request)


If you have HTML-parsing code to extract these JS cookies that you
want to run on every request (e.g. so even cookies set by JS during
redirections get handled), you can make all this transparent very
easily by using a handler similar to HTTPCookieProcessor itself (using
a recent version of package ClientCookie here for (a recent version
of) the response_seek_wrapper class) UNTESTED:


import urllib2, cookielib

class JSHTTPCookieProcessor(urllib2.BaseHandler):
handler_order = 400  # before HTTPCookieProcessor
def process_response(self, request, response):
from ClientCookie import response_seek_wrapper
if not hasattr(response, "seek"):
response = response_seek_wrapper(response)
try:
name, value = get_js_cookie(response)  # your ugly HTML parsing 
code here ;-)
finally:
response.seek(0)
response["Set-Cookie"] = "%s=%s" % (name, value)
return response

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(),
  JSHTTPCookieProcessor())
response = opener.open(url)  # now we're handling JS cookies transparently!



John

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


Recommended IDE for creating GUI?

2006-04-21 Thread Marty Christion
What are some good free or inexpensive (<$50) IDE's for learning how to 
program and create GUI's for Python?  I'm pretty good with the simple 
programming aspect of the language, but I'm a little mystified by the world 
of GUI's, and the options available in python. 


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


Re: how to append to a list twice?

2006-04-21 Thread Edward Elliott
Nick Craig-Wood wrote:
 > That should be
 >
 >   series = [x//2 for x in range(200, 1, -1)]
 >
 > to be "from __future__ import division" safe

from __present__ import gratitude
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda

2006-04-21 Thread Alexis Roda
[EMAIL PROTECTED] escribió:
> Hello,
> 
> # the idea is now to give the definition of the multiplication of
> functions and integers
> # (f * c)(xx) := f(x)*c
> [lambda xx: f(xx)*y for y in range(1,5)][0](1)
> # returns 4

here lambda uses a variable defined outside of the lambda (y). Any 
change made to y will be visible within the lambda. In your example the 
last value for y is 4, so:

[...][0](1) = f(1) * 4 = 4

> # I would expect 1*x*x = 1

you should use a local variable to "protect" y:

[ lambda xx, y=y : f(xx) * y for y in range(1, 5) ]

> # Where is my mistake and what would be the correct way to do this
> without lambdas?

You can emulate callables http://docs.python.org/ref/callable-types.html

class Callable:
   def __init__(self, f, y) :
 self.y = y
 self.f = f
   def __call__(self, x) :
 return self.f(x) * self.y

f = lambda x : x * x

[ Callable(f, y) for y in range(1, 5) ]

if you *absolutely* don't want lambdas you can hard code the x*x in 
__call__ and get rid of self._f, or you can define:

class Monomial:
   def __init__(self, exp, coef) :
 self.exp = exp
 self.coef = coef
   def __call__(self, x) :
 return x ** self.exp * self.coef

[ Monomial(2, y) for y in range(1, 5) ]

Another way, somewhat convoluted, using closures:

def make_list() :
   def make_function(y) :
 def function(x) :
   return x * x * y
 return function
   return [ make_function(y) for i in range(1, 5) ]

is essentially the same as lambda. Mostly didactic.



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


Re: python-mysql on Windows -- How to?

2006-04-21 Thread BartlebyScrivener
Oh, good. Do report back. It comes up often, and I've used only mxODBC.

rd

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


Re: how to append to a list twice?

2006-04-21 Thread Nick Craig-Wood
Edward Elliott <[EMAIL PROTECTED]> wrote:
>  John Salerno wrote:
>  > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...]
>  > (where each item is repeated twice after the first one), how might I do
>  > that most efficiently?
> 
>  Why not just this:
> 
>  series = [x/2 for x in range(200, 1, -1)]

That should be

  series = [x//2 for x in range(200, 1, -1)]

to be "from __future__ import division" safe

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


Re: PyLint results?

2006-04-21 Thread André Malo
* Michael Yanowitz wrote:

>I ran the new pylint and my code and I had a few questions on why those
> are warnings or what I can do to fix them:
> 
> 1) W:  0: Too many lines in module (1587)
>  Why is 1587 considered too many lines? Would there be necessarily be
>  an
>advantage to split it up into 2 or 3 files? Can I up the limit?

not necessarily. It might be considered bad style to put too much stuff into
one module. This depends on the content. You can now raise the limit (which
is 1000 lines by default) with the --max-module-lines command line option
or using a config file (generate one with pylint --generate-rcfile, use it
with pylint --rcfile=).

Alternatively you can disable the message for this module by putting
# pylint: disable-msg = W
on the top (after the # -*- coding -*- line, if any).
The new pylint allows for local disabling also such comments within the
code.

The id can you get if you enable them in the output via cmdline or config
file.

> 2) C:  0: Missing required attribute "__revision__"
>What is this? Is that for CVS? I don't use CVS (we use SVN). I have not
>seen any sample code which includes this tag yet. But if I include
>__revision 1.0  somewhere in the code it will remove that warning?

yeah. But you can list these attributes in the config... ;-)

> 3) W:230:readDiscreteData: Using the global statement
>What is wrong with using the global statement? I know the use of
>Globals should be discouraged, but often they can't be avoided.
>Suppose I have a constant. In C or C++, I could just use a #define and
>it would be known throughout the whole file. In Python, there isn't a
>similar construct, so rather than creating a large parameter list, of
>constants, I like to use globals.

Consider *writing* globals from inside a function as bad style.

> 4) W:261:getDiscreteData: Catch "Exception"
>What is wrong with that?

Typically you do want be more specific, because Exception catches too much.

> 5) R:547:readDiscreteData: Too many branches (28/12)
>Python doesn't have the switch/case statements that C/C++ have. So I
>could have a large block if/elif/else statements.
>Is there any way to avoid that?

Not always. But usually you can restructure your code better (Use more
functions/methods, structure them semantically).

> 6) R:722:waitDiscretes: Too many local variables (38/15)
>That's new to me. What is wrong with too many local variables?
>Can anything be done to improve that besides having too many globals?

One could loose the overview, I guess. 38 local variables are really a lot.
Structure your code :)

> 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer
> scope (line
>What is wrong with using the same variable name in a function that is
> used by its caller?

It might confuse someone else or you in half a year when reading the code
again.

> 8) W:995:sendStringToSocket: Used builtin function 'map'
>Is that a problem?

Not really. You might consider using list comprehensions, though.

>   Plus many other warnings about my naming convention or unused variables
> which I will ignore
> at this time.
> 
>   I did find it to be a very useful too any how in cleaning up my code.
> I raised my code rate from about -8 to about +7.

I personally find the code rate nonsense, YMMV ;-)

Note that all messages from pylint should be taken as hints, not a final
verdict. Think about them (you did, as you asked here ;-). Either correct
or ignore them (typically done by locally or even globally disabling them).

Do some fine-tuning using a config matching your own requirements. The
defaults are, well, just defaults.

nd
-- 
die (eval q-qq[Just Another Perl Hacker
]
;-)
# André Malo,  #
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pythonesque interface.

2006-04-21 Thread Gaz
Yeah, probably i'll be ending doing the front end in Flash and the back
end in Python.

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


Can my python script return a value to the c program executing it?

2006-04-21 Thread vduber6er
I have a C program that calls my python script by

exec_pycode(code);

code =  "import CheckFasta\nCheckFasta.CheckFasta (\"sampledata.txt\",
%d)\n", PyNum);

CheckFasta.py is my python script with a def CheckFasta in it that
returns a string.

Is there a way for my C code to get the return value from CheckFasta?

Example:
If CheckFasta returns "hello world"

can I somehow do something like

returnstring = exec_pycode(code);

where returnstring will contain "hello world" after the line above?

Thanks

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


  1   2   3   >