Re: Getting Local MAC Address

2010-04-06 Thread Lawrence D'Oliveiro
In message
, Booter 
wrote:

> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?

What if you have more than one?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: local variable referenced before assignment

2010-04-06 Thread Steven D'Aprano
On Mon, 05 Apr 2010 10:08:51 -0700, John Nagle wrote:

> Alf P. Steinbach wrote:
> 
>> Best is however to recognize that you have some state (your variable)
>> and some operations on that state (your callback), and that that is
>> what objects are all about. I.e. wrap your logic in a class. Then
>> 'lastModifiedTime' becomes an instance attribute, and 'handler' becomes
>> a method.
>> 
>> It doesn't matter that there will only ever be one object (instance) of
>> that class.
>> 
>> Classes were meant for just this sort of thing, state + operations.
> 
> Yes.  Functions with persistent state are generally a bad idea.


Persistent state is generally a bad idea, unless you need it. If you 
think you need it, you probably don't. But if you do actually need 
persistent state, it is better to hide it in some sort of routine 
(perhaps a function, perhaps a callable instance, perhaps something else) 
that can encapsulate the state, rather than store it in a global.



> Unfortunately, the "signal" module requires a callback parameter
> which is a plain function.  So you have to send it a function, closure,
> or lambda.  Here, it's being sent a closure - "handler" bound to the
> state that existed when "signal.signal" was called.


Help on built-in function signal in module signal:

signal(...)
signal(sig, action) -> action

Set the action for the given signal.  The action can be SIG_DFL,
SIG_IGN, or a callable Python object.  [...]


Doesn't seem like there is any requirement for it to be a regular 
function. Anything callable with the right signature should work, and if 
it doesn't, that's a bug.



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


Re: PIL question

2010-04-06 Thread Peter Otten
Tim Eichholz wrote:

> I'm trying to cut a BMP with 80 adjacent frames down to 40 using the
> Image.copy and .paste functions but I'm getting error "ValueError:
> images do not match" on the paste line.

> newimage.paste(cols[f], (f*framew, 0, (f*framew)+192, 192))

The 4-tuple doesn't match the size of the image you are pasting:

>>> from PIL import Image
>>> image = Image.open("tmp1.png")
>>> image.size
(134, 400)
>>> image.paste(image, (0, 0, 134, 400)) # correct size --> works
>>> image.paste(image, (0, 0, 134, 300)) # wrong size --> raises exception
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1077, in paste
self.im.paste(im, box)
ValueError: images do not match

You can add

for index, image in enumerate(cols):
   print "image %d --> %s" % (index, image.size)
   # image.save("tmp%d.png" % index)

to your code to learn the actual size of your intermediate images.
After you have fixed the size problem and see that the resulting image 
doesn't meet your expectations (likely, don't despair) you can uncomment the 
image.save(...) statement and have a look at the intermediate images.

A hint about counting loops: instead of

x = 0
while x < n:
   ...
   x = x + 1

it is idiomatic python to write

for x in range(n):
...

and

x = 0
while x < total_width:
# ...
x += single_width

is typically expressed as

for x in range(0, total_width, single_width):
   ...

Have a look at the tutorial for more basic tips.

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


Re: folks, what's wrong with this?

2010-04-06 Thread Bruno Desthuilliers

Ani Sinha a écrit :

And now for the most import point: __getattr__ is only called as a
*last* resort. That is, after the attribute lookup mechanism will have
tried *and failed* to find the name in the instance's __dict__.


Thanks you all for all the suggestions and thoughts. So in other
words, this piece of code:

try:
return self.__dict__.__getitem__(item)
except KeyError:
raise AttributeError(item)

in __getattr__ is redundant.


Yeps - this is the default behaviour, and this behaviour is triggered 
before any call to __getattr__ anyway.


FWIW, in your snippet, this whole __getattr__ method is useless at best.
--
http://mail.python.org/mailman/listinfo/python-list


Re: In disGuiodoise?

2010-04-06 Thread Bruno Desthuilliers

r a écrit :
(snip)

* If he feeling like spreading propaganda he fires up the George
Sakkis or Bruno Desthuilliers.


???

Thought most of my posts here were mostly in the "lame joke" category, 
with perhaps sometimes a more technical contribution, but "propaganda" ???


I think you're confusing me with someone else...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Incorrect scope of list comprehension variables

2010-04-06 Thread Alain Ketterlin
Alain Ketterlin  writes:

> d = dict()
> for r in [1,2,3]:
> d[r] = [r for r in [4,5,6]]
> print d

Thanks to Chris and Paul for the details (the list comp. r actually
leaks). I should have found this by myself.

My background is more on functional programming languages, that's why I
thought the list comprehension iterator should be purely local. And yes,
I think a "classical" for-loop iterator should also be local to the
loop, but I understand this may be too counter-intuitive to many :-)

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


Re: Incorrect scope of list comprehension variables

2010-04-06 Thread Alain Ketterlin
Steven D'Aprano  writes:

>> d = dict()
>> for r in [1,2,3]:
>> d[r] = [r for r in [4,5,6]]
>> print d
>
> This isn't directly relevant to your problem, but why use a list 
> comprehension in the first place? [r for r in [4,5,6]] is just [4,5,6], 
> only slower.

Sure. But I've actually spent some time reducing the real code to a
simple illustration of the problem.

>> THe problem is that the "r" in d[r] somehow captures the value of the
>> "r" in the list comprehension, and somehow kills the loop interator. The
>> (unexpected) result is {6: [4, 5, 6]}.
>
> Actually, no it doesn't kill the loop at all. You have misinterpreted 
> what you have seen:

It kills the iterator, not the loop. Sorry, I used 'kill' with the
meaning it has in compiler textbooks: to assign a new value to a
variable.

> It is expected, because list comprehensions leak the variable into the 
> enclosing scope.

Thanks.

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


Re: PIL question

2010-04-06 Thread Tim Eichholz
On Apr 6, 3:05 am, Peter Otten <__pete...@web.de> wrote:
> Tim Eichholz wrote:
> > I'm trying to cut a BMP with 80 adjacent frames down to 40 using the
> > Image.copy and .paste functions but I'm getting error "ValueError:
> > images do not match" on the paste line.
> > newimage.paste(cols[f], (f*framew, 0, (f*framew)+192, 192))
>
> The 4-tuple doesn't match the size of the image you are pasting:
>
> >>> from PIL import Image
> >>> image = Image.open("tmp1.png")
> >>> image.size
> (134, 400)
> >>> image.paste(image, (0, 0, 134, 400)) # correct size --> works
> >>> image.paste(image, (0, 0, 134, 300)) # wrong size --> raises exception
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1077, in paste
>     self.im.paste(im, box)
> ValueError: images do not match
>
> You can add
>
> for index, image in enumerate(cols):
>    print "image %d --> %s" % (index, image.size)
>    # image.save("tmp%d.png" % index)
>
> to your code to learn the actual size of your intermediate images.
> After you have fixed the size problem and see that the resulting image
> doesn't meet your expectations (likely, don't despair) you can uncomment the
> image.save(...) statement and have a look at the intermediate images.
>
> A hint about counting loops: instead of
>
> x = 0
> while x < n:
>    ...
>    x = x + 1
>
> it is idiomatic python to write
>
> for x in range(n):
>     ...
>
> and
>
> x = 0
> while x < total_width:
>     # ...
>     x += single_width
>
> is typically expressed as
>
> for x in range(0, total_width, single_width):
>    ...
>
> Have a look at the tutorial for more basic tips.
>
> Peter

I think maybe I am using the wrong function. I want to paste the
entire 192x192 contents of cols[f] into newimage. I would think it
works like newimage.paste(cols[f], (x, 0, 192+x, 192)) if that's not
it I think I'm missing a function
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL question

2010-04-06 Thread Peter Otten
Tim Eichholz wrote:

> I think maybe I am using the wrong function. I want to paste the
> entire 192x192 contents of cols[f] into newimage. I would think it
> works like newimage.paste(cols[f], (x, 0, 192+x, 192)) if that's not
> it I think I'm missing a function

Don't "think"! Read the documentation or, if that is hard to understand, 
write a tiny script that excercises only the function in question.


I can't test your script because it's not "self-contained" (doesn't run 
without user input), but I'm quite certain that the images that you generate 
with

c = 1
while c <= ncols:
cols += [image.crop((framew*c, 0, frameh*(c+1), frameh*(c+1)))]
c += 1

are not of the size 192x192. Assuming 

>>> framew = frameh = 192
>>> ncols = 3
>>> c = 1
>>> while c <= ncols:
... box = framew*c, 0, frameh*(c+1), frameh*(c+1)
... print "width =", box[2] - box[0], "height =", box[3] - box[1]
... c += 1
...
width = 192 height = 384
width = 192 height = 576
width = 192 height = 768

See? You need to redo the maths and go through every step of your script, 
throw in some diagnostics code to verify that it does what you expect, and 
only then proceed to the next operation.

My hunch is that crop() doesn't do what you want rather than paste(), but to 
be sure you'd have to explain in plain English what the final image should 
look like.

Peter

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


Re: Translation docstrings with gettext

2010-04-06 Thread sapient
Lie Ryan, thank you for your answer!
> Why would you want to translate docstring? Docstring is meant for
> developers not users.
I have mentioned that I want to provide API for existing image-
processing applicaion in Python.
In my case "developers" are "users".
Python provides great possibilities for documenting objects, I want to
use it for things such context help about API modules, classes,
methods, and want to do it in several languages.

> Maintaining a translated docstring is going to be
> a maintenance hell and will either hampers your application's agility or
> you will be left with obsolete docstrings in various languages you don't
> know.
You are right, there are problems here, but there are advantages too
(we are talking about API): developers can write documentation in
thier "cracked" English (like my), but professional translator can
correct it after with Poedit.

> Anyway, my job is to answer questions, not question the economic
> feasibility of your decision, so try this:
>
> #!python
> __doc__ = _("""testmodule docstring""")
>
> class TestClass:
>     __doc__ = _("""testmodule.TestClass docstring""")
>
>     def testClassMethod(self):
>         __doc__ = _("""testmodule.TestClass.testClassMethod docstring""")
>         print _("Call TestClass.testClassMethod()")
Yes, I tried this method, but it does not work with methods and
functions, this line
> __doc__ = _("""testmodule.TestClass.testClassMethod docstring""")
does nothing (There are not output in help()). Is it any way to assign
docstring for function explicity?

> If you want to avoid having the explicit assignment to __doc__, you can
> also try using some metaclass or decorator magic to automatically wraps
> docstring in a _() call.

Yes, it will be better to avoid them, is it any existing tool/lib/
workaround that can do it?
I am follower of aproved, stable solutions, do not like to reinvent
the wheel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: per-function jit compiler

2010-04-06 Thread Luis M . González
On 6 abr, 03:40, Chris Rebert  wrote:
> 2010/4/5 Luis M. González :
>
>
>
>
>
> > This post gave me an 
> > idea:http://groups.google.com/group/comp.lang.python/msg/5d75080707104b76
>
> > What if I write a simple decorator to figure out the types of every
> > function, and then we use it as a base for a simple method-jit
> > compiler for python?
>
> > example:
>
> > def typer(f):
> >        def wrap(*args):
> >            a = f.func_code.co_varnames
> >            b = [type(i) for i in args]
> >            return dict(zip(a,b))
> >        return wrap
>
> > @typer
> > def spam(a, b, c=3, d=4):
> >        pass
>
>  spam(8,'hello',9.9, 10)
> > {'a': , 'c': , 'b': , 'd': > 'int'>}
>
> > So by using this information, we record all the argument types used
> > the first time each function/method is executed, and then we generate
> > optimized code for them.
> > >From this point on, a guard should check if all arguments remain the
> > same and, if so, the optimized code is run.
> > Otherwise, just fall back to the interpreter.
>
> > He! I have no idea how to implement it...
>
> Guido's been lending out his time machine 
> again:http://psyco.sourceforge.net/introduction.html
>
> Cheers,
> Chris
> --http://blog.rebertia.com

Well, psyco is a complex beast. Actually it's a Just-In-Time
Specializer, not really a compiler at all (Guido's machine told me
so).
It's been superseded by pypy, which is a way more complex beast, and
it's a tracing compiler (and many things more).
What I mean is, why not using python's simple introspection
capabilities (instead of partial evaluation, type inference or other
complex mechanism) to gather type information?
I can imagine that this, coupled with pyrex, cython or shedskin could
give some results perhaps... by selectively compiling some function or
all of them.

But probably someone will throw Guido's time machine again at me. If
it was that easier, someone would have done it already...
I just wonder why this simple approach is not feasible.

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


my threaded program hangs after calling Queue.join()

2010-04-06 Thread Babu
I am not an expert in python, so any help is my appreciated.  My
threaded program consumed everything in the queue but is not
exiting... What is the problem with this program?

#!/opt/gspython-2.5/bin/python

""" Intention of this program: given a list of host names in a file,
get the .rhosts file, remove the newline and create a single record or
tuple
for each server.
"""

import paramiko
import os
import sys
import Queue
import threading
import pdb

SPath = "/.rhosts"  #location of .rhosts in Solaris
LPath = "/root/.rhosts" #location of .rhosts in Linux

#Globals starts with Capital letter
Q_in= Queue.Queue()

class   ProcessThreads(threading.Thread):
""" Threaded remote execution and data gathering """
def __init__(self, Q_in):
threading.Thread.__init__(self)
self.Q_in = Q_in


def run(self):
while True:
#grabs host and path from Q_in
host, path = self.Q_in.get()


#print "host = ", host, "file = ", path
if host is None:
break # reached end of queue

ssh_c = paramiko.SSHClient()
ssh_c.load_system_host_keys()
user = 'root'
port = 22
#remotely execute the commands
try:
ssh_c.connect(host, port, user, timeout=20)
except Exception, e:
print "ssh exception %s for %s" %( e, host)
break


stdin, stdout, stderr = ssh_c.exec_command('cat ' + 
path)
output = stdout.readlines()
outputs = ''.join(output).replace('\n',',')
print host,": ", outputs

#signals to queue job is done
self.Q_in.task_done()


def usage():
nargs = len(sys.argv)
if  nargs < 2:
print "USAGE: %s "  % os.path.basename(sys.argv[0])
print " contains records of hostnames, one host per
line"
sys.exit(1)

def load_ssh():
paramiko.util.log_to_file('/var/tmp/paramiko.log')


if __name__ == "__main__":
#pdb.set_trace()
usage()
hostfile = sys.argv[1]
fh = open(hostfile, 'r')
records = fh.readlines()
fh.close()
load_ssh()

#spawn a pool of thread and spawn them queue instance
for i in range(5):
t = ProcessThreads(Q_in)
t.setDaemon(True)
t.start()

#populate queue with data

for recs in records:
hostinfo = recs.strip()
host, os = hostinfo.split()
if os == "Linux":
path = LPath
else:
path = SPath
Q_in.put([host, path])

for i in range(5):
Q_in.put([None, None])  # end of queue signal

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


Re: case insensitive list ?

2010-04-06 Thread Stef Mientki
On 05-04-2010 19:23, Robert Kern wrote:
> On 2010-04-05 12:17 PM, Stef Mientki wrote:
>> hello,
>>
>> AFAIK there's no case insensitive list in Python.
>> By case insentive I mean that that sort and memebr of is case
>> insensitive.
>>
>> Does soeone has a implementation of sucha case insensitive list ?
>
> mylist.sort(key=lambda x: x.lower())
> any(x.lower() == lowercase_query for x in mylist)
>

thanks Robert,
your code works perfectly,
but I was thinking of something more easy to repeat and mor eidentical
to existing lists.
Or in other words, I want to use exactly the same commands and operators
as with normal lists,
like this
_List = NoCase_List ( 'coala', 'donky' )
My_List.append ( 'Aap' )
My_List.append ( 'aapje' )
My_List.append ( 'beerthe' )
My_List.append ( 'BEER' )
print My_List
My_List.sort ()
print My_List
My_List.append ( 'aapJ' )
print My_List
print My_List.index ( 'beer' )
print 'beer' in My_List
print 'beert' in My_List

After some trial and error the code below, gives almost the desired results.

The only problem I see for now,
is that replacing the items-list in wxpython widgets don't work,
so I'l  ask my question to the wxPython list.

cheers,
Stef



class NoCase_List ( list ) :
  """
  Case Insensitive List :
  The methods "sort" and "index" are case insensitive.
  The "in" operator works also case insensitive.
  After the list is sorted once,
  appending a new item keeps the list sorted.
  """
  def __init__ ( self, *args, **kwargs ):
self.Sorted = False
list.__init__ ( self )
if isinstance ( args[0], list ) :
  for item in args [0] :
self.append ( item )
else :
  self.append ( args[0] )

  def append ( self, value ) :
list.append ( self, value )
if self.Sorted :
  self.sort ()

  def sort ( self, *args, **kwargs ) :
self.Sorted = True
def _sort ( a, b ) :
  return cmp ( a.lower(), b.lower() )
return list.sort ( self, _sort )

  def index ( self, value ) :
value = value.lower()
for i, item in enumerate ( self ) :
  if item.lower() == value :
return i
else :
  return -1

  def __contains__ ( self, value ) :
return self.index ( value ) >= 0

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


Re: my threaded program hangs after calling Queue.join()

2010-04-06 Thread Kushal Kumaran
On Tue, Apr 6, 2010 at 5:36 PM, Babu  wrote:
> I am not an expert in python, so any help is my appreciated.  My
> threaded program consumed everything in the queue but is not
> exiting... What is the problem with this program?
>

See the example in the documentation of the queue module.  There must
be a call to task_done for every put.  You put the sentinel [None,
None] value, for which there will be no task_done call (because you
break out of the loop when you hit the sentinel).

> 

-- 
regards,
kushal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my threaded program hangs after calling Queue.join()

2010-04-06 Thread Peter Otten
Babu wrote:

> I am not an expert in python, so any help is my appreciated.  My
> threaded program consumed everything in the queue but is not
> exiting... What is the problem with this program?

Perhaps it's waiting for the task_done() call associated to the (None, None) 
pairs.

> if host is None:
  Q_in.task_done()
> break # reached end of queue

The same problem could occur when an exception is raised.

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


Re: my threaded program hangs after calling Queue.join()

2010-04-06 Thread Babu
On Apr 6, 9:32 pm, Peter Otten <__pete...@web.de> wrote:
> Babu wrote:
> > I am not an expert in python, so any help is my appreciated.  My
> > threaded program consumed everything in the queue but is not
> > exiting... What is the problem with this program?
>
> Perhaps it's waiting for the task_done() call associated to the (None, None)
> pairs.
>
> >                         if host is None:
>
>                                   Q_in.task_done()
>
> >                                 break # reached end of queue
>
> The same problem could occur when an exception is raised.
>
> Peter

Thank you Kushal and Peter.  I have modified my program and added the
task_done() for end of queue and exceptions.  It works great now!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum for sequences?

2010-04-06 Thread Albert van der Horst
In article <559a2ee3-fb2c-477f-a444-7edbb6da8...@r1g2000yqj.googlegroups.com>,
Patrick Maupin   wrote:
>On Mar 29, 10:29=A0pm, Steven D'Aprano
> wrote:
>> On Mon, 29 Mar 2010 19:24:42 -0700, Patrick Maupin wrote:
>> > On Mar 29, 6:19=A0pm, Steven D'Aprano > > cybersource.com.au> wrote:
>> >> How does the existence of math.fsum contradict the existence of sum?
>>
>> > You're exceptionally good at (probably deliberately) mis-interpreting
>> > what people write.
>>
>> I cannot read your mind, I can only interpret the words you choose to
>> write. You said
>>
>> [quote]
>> See, I think the very existence of math.fsum() already violates "there
>> should be one obvious way to do it."
>> [end quote]
>>
>> If sum satisfies the existence of one obvious way, how does math.fsum
>> violate it? sum exists, and is obvious, regardless of whatever other
>> solutions exist as well.
>
>Because sum() is the obvious way to sum floats; now the existence of
>math.fsum() means there are TWO obvious ways to sum floats.  Is that
>really that hard to understand?  How can you misconstrue this so badly
>that you write something that can be (easily) interpreted to mean that
>you think that I think that once math.fsum() exists, sum() doesn't
>even exist any more

To a mathematician sum(set) suggest that the order of summation
doesn't matter. (So I wouldn't use sum for concatenating lists.)
Harshly, sum() should be used only for operator + both associative and
commutative.

Now for floating point numbers the order of summation is crucial,
not commutative  (a+b)+c <> a+(b+c).
So the obvious thing for someone versed in numerical computing
do is looking whether sum() gives any guarantees for order and
whether there may be a special sum() for floating point.
(This is not very realistic, because such a person would have
skimmed the math library a long time ago, but anyway.)

Met vriendelijke groeten,
Albert van der Horst

--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- like all pyramid schemes -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst


--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-06 Thread Albert van der Horst
In article ,
Peter Otten  <__pete...@web.de> wrote:
>Pierre Quentel wrote:
>
>> I'm surprised nobody proposed a solution with itertools ;-)
>
>next(itertools.takewhile(lambda _: a == b, ["yes"]), "no")

I could learn something here, if you explain it?

>
>You spoke to soon :)
>
>Peter

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


pass object or use self.object?

2010-04-06 Thread Tim Arnold
Hi,
I have a few classes that manipulate documents. One is really a
process that I use a class for just to bundle a bunch of functions
together (and to keep my call signatures the same for each of my
manipulator classes).

So my question is whether it's bad practice to set things up so each
method operates on self.document or should I pass document around from
one function to the next?
pseudo code:

class ManipulatorA(object):
def process(self, document):
document = self.do_one_thing(document)
document = self.do_another_thing(document)
# bunch of similar lines
return document

or

class ManipulatorA(object):
def process(self, document):
self.document = document
self.do_one_thing() # operates on self.document
self.do_another_thing()
# bunch of similar lines
return self.document

I ask because I've been told that the first case is easier to
understand. I never thought of it before, so I'd appreciate any
comments.
thanks,
--Tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Loading an imported module (C API)

2010-04-06 Thread booncw
Hi,

I am running a simulation where the python module has already been
imported.   Could you please tell me how to load it?

I've been doing this (importing everytime), but it is too slow:
pModule = PyImport_Import(pName);


Yours,

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


Re: sum for sequences?

2010-04-06 Thread Xavier Ho
On Tue, Apr 6, 2010 at 11:39 PM, Albert van der Horst <
alb...@spenarnc.xs4all.nl> wrote:

> Now for floating point numbers the order of summation is crucial,
> not commutative  (a+b)+c <> a+(b+c).
>

Could you shed some light on why is this?

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


Re: pass object or use self.object?

2010-04-06 Thread Xavier Ho
> So my question is whether it's bad practice to set things up so each
> method operates on self.document or should I pass document around from
> one function to the next?
>

I think this depends on the use case.

If the functions you're calling in between have a chance to be called
independently, then I would probably allow passing the documents in the
arguments, so that other code can utilise this function. On the other
extreme, if this function is only used internally, I would simply use
self.object to avoid copying extra references, and treat them as sub
routines. I would also previx two underscores (__) before the function to
indicate that it's supposed to be interal-use only.

The other use case is, if self.object is useful after the function, I would
keep it as that. Then, other code could use it without processing it again.
On the other hand, if it is useless after created and returned, then I would
not keep a reference in the class object.

All in all, you probably won't find a big performance difference, so it all
boils down to logical placement.

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


Re: sum for sequences?

2010-04-06 Thread Patrick Maupin
On Apr 6, 8:39 am, Albert van der Horst 
wrote:

> To a mathematician sum(set) suggest that the order of summation
> doesn't matter. (So I wouldn't use sum for concatenating lists.)
> Harshly, sum() should be used only for operator + both associative and
> commutative.

That's all well and good, but not every Python user is a
mathematician.  As long as Python doesn't surprise mathematicians in a
way that is too negative (I can see the complaint now: "Hey!  sum()
kept my lists ordered!  I was expecting some randomization!") what is
wrong with it also not surprising the average user in a way that is
too negative?

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-06 Thread Albert van der Horst
In article ,
Steve Holden   wrote:
>kj wrote:
>> In  Steve Holden 
>>  writes:
>>
>>> John Nagle wrote:
 Chris Rebert wrote:
> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone 
> wrote:
>> Hi, how can I write the popular C/JAVA syntax in Python?
>>
>> Java example:
>>return (a==b) ? 'Yes' : 'No'
>>
>> My first idea is:
>>return ('No','Yes')[bool(a==b)]
>>
>> Is there a more elegant/common python expression for this?
> Yes, Python has ternary operator-like syntax:
> return ('Yes' if a==b else 'No')
>
> Note that this requires a recent version of Python.
 Who let the dogs in?  That's awful syntax.

>>> Yes, that's deliberately awful syntax. Guido designed it that way to
>>> ensure that people didn't aver-use it, thereby reducing the readability
>>> of Python applications.
>>
>> Is that for real???  It's the QWERTY rationale all over again.  Swell.
>>
>I may be misrepresenting Guido here. Unlike Tim Peters I have never
>claimed to be able to channel him.
>
>> "Let's preserve readability by making the syntax so ugly that people
>> won't use it."???  That's just perverse.  (It would have been more
>> reassuring if the reason had been simply that Guido has an inexplicable
>> dislike of ternary expressions just like one may have an inexplicable
>> dislike of Broadway musicals.)
>>
>I don't think his dislike of them is inexplicable. They do, when
>over-used, lead to the most impenetrable code, which as a bonus is
>frequently buggy.
>
>> First, I don't understand why ternary expressions are inherently
>> hard to read, and therefore must be discouraged in the name of
>> overall code readability.  Sure, one can write impenetrable ternary
>> expressions, but one can write impenetrable binary expressions or
>> impenetrable anything else, even in Python.  That the expression
>> is ternary has nothing to do with it.
>>
>I think it does - the scope of the expressions is inherently longer when
>three terms are involved rather than just tow.
>
>> Second, sticking the test between the two alternatives goes against
>> a vast tradition in programming languages.  This tradition inevitably
>> fosters habits and expectations when reading code, so going against
>> it automatically makes code less readable to all who were educated
>> in that tradition.  Consider, for example, the readability of the
>> following if statement in some hypothetical language:
>>
>> begin:
>># this branch will be executed if test() (see below) evaluates
>># to true
>>x = y + z
>>a = b * x + c
>>i = j - k
>>p = log(q)
>> if test() else:
>>x = -(y + z)
>>a = b * x + 2 * c
>>i = j + k
>>p = -log(q)
>>
>> If you find this hard to read (I do), the quetion is "why?".  For
>> me it's because, maybe through years of reading code, I've developed
>> a habit that says: when you run into a fork in the logic, first
>> understand what the decision hinges on.  Therefore, my brain will
>> start hunting for that test, and it sucks to have to find it buried
>> somewhere in the middle.  (Sure, one could justify this horrible
>> syntax with an argument reminiscent of the one you gave for "A if
>> X else B".  It goes like this: long blocks of code should be avoided
>> in the name of readability; this syntax discourages long blocks of
>> code because one doesn't want to skip too far ahead to find that
>> test.  Ergo the end result is improved readability.  That's just
>> nuts.)
>>
>It's precisely to avoid that kind of lunacy that the chosen form was
>adopted. Conditional expressions aren't *meant* to be complex enough to
>leave any doubt about their meaning. If you require such complexity
>that's perfectly OK - just use an "if" statement.

Let's look at a c-example.
stamp =  weight>=1000 ? 120 :
 weight>=500  ? 100 :
 weight>=250  ? 80  :
 weight>=100  ? 60  :
 44;

In a glance I see that stamp gets a value.
This wouldn't be so with regular if-statements that defines
numerous path's through the code that each must be tested.
Then I find this eminently suited to compare to a table given
as a specification.

What is akward is the definition of the ternary
operation that is left associative to mean
stamp =  weight>=1000 ? 120 :
 (
 weight>=500  ? 100 :
 (
 weight>=250  ? 80  :
 (
 weight>=100  ? 60  :
  44
 )
 )
 ) ;
And not

stamp =  ( weight>=1000 ? 120 : weight>=500 ) ? 100 : weight>=250 )
 ? 80   ...

Now Python

stamp =( 120 if  weight>=1000 else
 100 if  weight>=500  else
 80  if  weight>=250  else
 60  if  weight>=100  else
 44  )

This has the same advantage as c, plus :
- the

Re: sum for sequences?

2010-04-06 Thread Neil Cerutti
On 2010-04-06, Albert van der Horst  wrote:
> To a mathematician sum(set) suggest that the order of summation
> doesn't matter. (So I wouldn't use sum for concatenating
> lists.) Harshly, sum() should be used only for operator + both
> associative and commutative.
>
> Now for floating point numbers the order of summation is
> crucial, not commutative  (a+b)+c <> a+(b+c). So the obvious
> thing for someone versed in numerical computing do is looking
> whether sum() gives any guarantees for order and whether there
> may be a special sum() for floating point. (This is not very
> realistic, because such a person would have skimmed the math
> library a long time ago, but anyway.)

I'm convinced by this argument. I just have to be a mathematician
and a computer scientist skilled in numerical computing. No
problem! Just a *few more years* of education and I'll be ready
for summing things in Python. ;)

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


Recommend Commercial graphing library

2010-04-06 Thread AlienBaby
Hi,

I'm on the hunt for a good quality commercially licensed graphing /
plotting library and wondered if anyone here had any recomendations.
The work to be done is less scientific, more presentational, (I'm not
going to be dealing with heatmaps / vectors etc.., just the usual
bar / line / bubble / radar / iceberg type graphs) so a good level of
control over how the final output looks would be a key point.

I'd be grateful for any suggestions / pointers to something useful,

thanks,

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


Re: pass object or use self.object?

2010-04-06 Thread Bruno Desthuilliers

Tim Arnold a écrit :

Hi,
I have a few classes that manipulate documents. One is really a
process that I use a class for just to bundle a bunch of functions
together (and to keep my call signatures the same for each of my
manipulator classes).

So my question is whether it's bad practice to set things up so each
method operates on self.document or should I pass document around from
one function to the next?


As far as I'm concerned, I strongly prefer passing the document around. 
Makes thing clear, avoids useless preconditions (is self.document set 
???) and race conditions (if two threads have to share the Manipulator 
instance), makes the code easier to understand / maintain / refactor IMHO.


Also remember that modules are objects too, so - depending on parts of 
your code we don't see here - you may even maintain your API without 
having to use a "class as module".


My 2 cents
--
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread Pablo Recio Quijano
Why must be commercial, when there is open and free alternatives? Like GNU
Plot.

2010/4/6 AlienBaby 

> Hi,
>
> I'm on the hunt for a good quality commercially licensed graphing /
> plotting library and wondered if anyone here had any recomendations.
> The work to be done is less scientific, more presentational, (I'm not
> going to be dealing with heatmaps / vectors etc.., just the usual
> bar / line / bubble / radar / iceberg type graphs) so a good level of
> control over how the final output looks would be a key point.
>
> I'd be grateful for any suggestions / pointers to something useful,
>
> thanks,
>
> Matt.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Pablo Recio Quijano

Estudiante de Ingeniería Informática (UCA)
Alumno colaborador del Departamento de Lenguajes y Sistemas Informáticos
Participante del IV Concurso Universitario de Software Libre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pass object or use self.object?

2010-04-06 Thread Jean-Michel Pichavant

Tim Arnold wrote:

Hi,
I have a few classes that manipulate documents. One is really a
process that I use a class for just to bundle a bunch of functions
together (and to keep my call signatures the same for each of my
manipulator classes).

So my question is whether it's bad practice to set things up so each
method operates on self.document or should I pass document around from
one function to the next?
pseudo code:

class ManipulatorA(object):
def process(self, document):
document = self.do_one_thing(document)
document = self.do_another_thing(document)
# bunch of similar lines
return document

or

class ManipulatorA(object):
def process(self, document):
self.document = document
self.do_one_thing() # operates on self.document
self.do_another_thing()
# bunch of similar lines
return self.document

I ask because I've been told that the first case is easier to
understand. I never thought of it before, so I'd appreciate any
comments.
thanks,
--Tim
  
Usually, when using classes as namespace, functions are declared as 
static (or as classmethod if required).

e.g.


class Foo:
   @classmethod
   def process(cls, document):
   print 'process of'
   cls.foo(document)

   @staticmethod
   def foo(document):
   print document

In [5]: Foo.process('my document')
process of
my document


There is no more question about self, 'cause there is no more self. You 
don't need to create any instance of Foo neither.


JM

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


Re: Recommend Commercial graphing library

2010-04-06 Thread Jean-Michel Pichavant

Pablo Recio Quijano wrote:
Why must be commercial, when there is open and free alternatives? Like 
GNU Plot.


Gnuplot is ugly. I'm using it because I don't care if it's ugly but it 
clearly lacks of look & feel for presentations, as requested by the OP.


You have
http://matplotlib.sourceforge.net/

which is free and looks better than gnuplot. I'm not sure it's well 
suited for presentation though.


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


Re: per-method jit compiler

2010-04-06 Thread Florian Ludwig
On Mon, 2010-04-05 at 22:45 -0700, Luis M. González wrote:
> The above post gave me an idea (very naive, of couse).
> What if I write a simple decorator to figure out the types of every
> function, and then we use it as a base for a simple method-jit
> compiler for python? 
I think its what done before by psyco:
http://psyco.sourceforge.net/

No need for a decorator though.

-- 
Florian Ludwig 

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


Re: pass object or use self.object?

2010-04-06 Thread Xavier Ho
On Wed, Apr 7, 2010 at 1:19 AM, Jean-Michel Pichavant <
jeanmic...@sequans.com> wrote:

> Usually, when using classes as namespace, functions are declared as static
> (or as classmethod if required).
> e.g.
>
>
> class Foo:
>   @classmethod
>   def process(cls, document):
>   print 'process of'
>   cls.foo(document)
>
>   @staticmethod
>   def foo(document):
>   print document
>
> In [5]: Foo.process('my document')
> process of
> my document
>
>
> There is no more question about self, 'cause there is no more self. You
> don't need to create any instance of Foo neither.



JM, I beg to differ. If many functions are static inside a class, I would
simply put those methods right under a module instead.

My 2c,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Incorrect scope of list comprehension variables

2010-04-06 Thread Lie Ryan
On 04/06/10 18:42, Alain Ketterlin wrote:
> Alain Ketterlin  writes:
> 
>> d = dict()
>> for r in [1,2,3]:
>> d[r] = [r for r in [4,5,6]]
>> print d
> 
> Thanks to Chris and Paul for the details (the list comp. r actually
> leaks). I should have found this by myself.
> 
> My background is more on functional programming languages, that's why I
> thought the list comprehension iterator should be purely local. And yes,
> I think a "classical" for-loop iterator should also be local to the
> loop, but I understand this may be too counter-intuitive to many :-)

Actually in other programming languages, loop counter is usually local:

for (int i = 0; i < something; i++) {

}
foo(i); // illegal

The reason why python's loop counter leaks is for implementation
simplicity because otherwise python will have to deal with multi-layered
local namespace. Currently in python, the local namespace is just sugar
for an array access (a bit of hand-waving here). In other languages, a
{} block is a namespace and nested {} block means nested namespace even
if they're still in a single function; in python there is only a flat
local namespace and the names resolver becomes a thousand times simpler
(and faster).
-- 
http://mail.python.org/mailman/listinfo/python-list


Python script error when using print

2010-04-06 Thread Robbie
Hi all,

So, I'm trying to use Python with an apache2 server to create some web
pages.  The web server is configured and seems to work correctly, but
only with a certain type of script.

For instance, this script works fine

#!/usr/bin/env python
def index():
s = "Hello World"
return s

But, a script like this, does not.
#!/usr/bin/env python
print "hello world"

When I try to use the script with print, the server returns a broken
link error.  There is nothing in the apache error log to help me
understand why it won't work.

Any help?

thanks

robbie

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-06 Thread Lie Ryan
On 04/07/10 00:16, Albert van der Horst wrote:
> In article ,
> Peter Otten  <__pete...@web.de> wrote:
>> Pierre Quentel wrote:
>>
>>> I'm surprised nobody proposed a solution with itertools ;-)
>>
>> next(itertools.takewhile(lambda _: a == b, ["yes"]), "no")
> 
> I could learn something here, if you explain it?

The signature for next() is:
next(iterator[, default])

In particular, pay attention the `default` parameter.

next() returns `default` if StopIteration is raised else it returns
iterator.__next__().

takewhile(predicate, ["yes"]).__next__() return the string "yes" if
predicate("yes") returns True else it raises StopIteration.

The predicate (lambda _: a == b) returns True if (a == b) is True
otherwise it returns False.

Put the next(), takewhile(), and the predicate together and you get an a
monster that returns `default` if a == b is False else "yes".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: per-function jit compiler

2010-04-06 Thread Gabriel Genellina
En Tue, 06 Apr 2010 07:23:19 -0300, Luis M. González   
escribió:



On 6 abr, 03:40, Chris Rebert  wrote:

2010/4/5 Luis M. González :





> This post gave me an  
idea:http://groups.google.com/group/comp.lang.python/msg/5d75080707104b76


> What if I write a simple decorator to figure out the types of every
> function, and then we use it as a base for a simple method-jit
> compiler for python?

> example:

> def typer(f):
>def wrap(*args):
>a = f.func_code.co_varnames
>b = [type(i) for i in args]
>return dict(zip(a,b))
>return wrap

> @typer
> def spam(a, b, c=3, d=4):
>pass

 spam(8,'hello',9.9, 10)
> {'a': , 'c': , 'b': , 'd': 'int'>}

> So by using this information, we record all the argument types used
> the first time each function/method is executed, and then we generate
> optimized code for them.
> >From this point on, a guard should check if all arguments remain the
> same and, if so, the optimized code is run.
> Otherwise, just fall back to the interpreter.

> He! I have no idea how to implement it...

Guido's been lending out his time machine  
again:http://psyco.sourceforge.net/introduction.html




Well, psyco is a complex beast. Actually it's a Just-In-Time
Specializer, not really a compiler at all (Guido's machine told me
so).
It's been superseded by pypy, which is a way more complex beast, and
it's a tracing compiler (and many things more).
What I mean is, why not using python's simple introspection
capabilities (instead of partial evaluation, type inference or other
complex mechanism) to gather type information?
I can imagine that this, coupled with pyrex, cython or shedskin could
give some results perhaps... by selectively compiling some function or
all of them.


That *is* exactly what psyco does. A specialized function (or block) is a  
pre-compiled block with a known combination of variable types, detected at  
runtime.
psyco has not been superseded by pypy, they're two separate projects.  
(psyco's author focus has migrated, though).


--
Gabriel Genellina

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


Re: Recommend Commercial graphing library

2010-04-06 Thread AlienBaby
On Apr 6, 4:24 pm, Jean-Michel Pichavant 
wrote:
> Pablo Recio Quijano wrote:
> > Why must be commercial, when there is open and free alternatives? Like
> > GNU Plot.
>
> Gnuplot is ugly. I'm using it because I don't care if it's ugly but it
> clearly lacks of look & feel for presentations, as requested by the OP.
>
> You havehttp://matplotlib.sourceforge.net/
>
> which is free and looks better than gnuplot. I'm not sure it's well
> suited for presentation though.
>
> JM

Hi,

The requirement for a commercial license comes down to being
restricted to not using any open source code. If it's an open source
license it can't be used in our context.

Until now I have actually been using matplotlib, but now that has to
change.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread Grant Edwards
On 2010-04-06, Jean-Michel Pichavant  wrote:
> Pablo Recio Quijano wrote:
>> Why must be commercial, when there is open and free alternatives? Like 
>> GNU Plot.
>
> Gnuplot is ugly. I'm using it because I don't care if it's ugly but it 
> clearly lacks of look & feel for presentations, as requested by the OP.
  ^^
  
In other words, Gnuplot presents information in a clear, obfuscated
manner.  Definitely not the thing for presentations.

Nothing hides that unpleasant, inconvenient data better than adding a
lot of colors, drop-shadows, and of course the unneeded "3d" look
complete with a weird perspective.

> You have
> http://matplotlib.sourceforge.net/
>
> which is free and looks better than gnuplot. I'm not sure it's well 
> suited for presentation though.

Agreed. It's almost as bad at data-obfuscation as Gnuplot.

-- 
Grant Edwards   grant.b.edwardsYow! Used staples are good
  at   with SOY SAUCE!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread Ed Keith
--- On Tue, 4/6/10, AlienBaby  wrote:

> From: AlienBaby 
> Subject: Re: Recommend Commercial graphing library
> To: python-list@python.org
> Date: Tuesday, April 6, 2010, 12:05 PM
> On Apr 6, 4:24 pm, Jean-Michel
> Pichavant 
> wrote:
> > Pablo Recio Quijano wrote:
> > > Why must be commercial, when there is open and
> free alternatives? Like
> > > GNU Plot.
> >
> > Gnuplot is ugly. I'm using it because I don't care if
> it's ugly but it
> > clearly lacks of look & feel for presentations, as
> requested by the OP.
> >
> > You havehttp://matplotlib.sourceforge.net/
> >
> > which is free and looks better than gnuplot. I'm not
> sure it's well
> > suited for presentation though.
> >
> > JM
> 
> Hi,
> 
> The requirement for a commercial license comes down to
> being
> restricted to not using any open source code. If it's an
> open source
> license it can't be used in our context.
> 
> Until now I have actually been using matplotlib, but now
> that has to
> change.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

>From The Matplotlib documentation: "Matplotlib only uses BSD compatible code, 
>and its license is based on the PSF license."

BSD and PSF both allow commercial use. There is no "copyleft" restriction.

-EdK

Ed Keith
e_...@yahoo.com

Blog: edkeith.blogspot.com



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


Re: Recommend Commercial graphing library

2010-04-06 Thread Paul McGuire
On Apr 6, 11:05 am, AlienBaby  wrote:
> The requirement for a commercial license comes down to being
> restricted to not using any open source code. If it's an open source
> license it can't be used in our context.

You may be misunderstanding this issue, I think you are equating "open
source" with "GPL", which is the open source license that requires
applications that use it to also open their source.  There are many
other open source licenses, such as Berkeley, MIT, and LGPL, that are
more permissive in what they allow, up to and in some cases including
full inclusion within a closed-source commercial product.  You might
also contact the supplier of the open source code you are interested,
and perhaps pay a modest fee to obtain a commercial license.

-- Paul

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


Re: Recommend Commercial graphing library

2010-04-06 Thread Grant Edwards
On 2010-04-06, Grant Edwards  wrote:
> On 2010-04-06, Jean-Michel Pichavant  wrote:
>> Pablo Recio Quijano wrote:
>>> Why must be commercial, when there is open and free alternatives? Like 
>>> GNU Plot.
>>
>> Gnuplot is ugly. I'm using it because I don't care if it's ugly but it 
>> clearly lacks of look & feel for presentations, as requested by the OP.
>   ^^
>   
> In other words, Gnuplot presents information in a clear, obfuscated
   
That should be:   unobsuscated

stupid spell-checker...
   
Seriously, most of the graphs I've seen in "presentations" would make
Ed Tufte spin in his grave.

If it's 2D data, you don't need to use a 3D graph.
  
-- 
Grant Edwards   grant.b.edwardsYow! Is it 1974?  What's
  at   for SUPPER?  Can I spend
  gmail.commy COLLEGE FUND in one
   wild afternoon??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translation docstrings with gettext

2010-04-06 Thread Gabriel Genellina
En Tue, 06 Apr 2010 06:52:57 -0300, sapient   
escribió:



Lie Ryan, thank you for your answer!

Why would you want to translate docstring? Docstring is meant for
developers not users.

I have mentioned that I want to provide API for existing image-
processing applicaion in Python.
In my case "developers" are "users".
Python provides great possibilities for documenting objects, I want to
use it for things such context help about API modules, classes,
methods, and want to do it in several languages.


There were some efforts in this direction in the past (like the -D option  
of pygettext; and there was even a .po file for Python itself and the  
standard library) but they seem to have been abandoned long time ago.



Yes, it will be better to avoid them, is it any existing tool/lib/
workaround that can do it?


The turtle module contains a *very* basic translation mechanism; see  
turtle.write_docstringdict() and read_docstringdict(). They don't use  
gettext.



I am follower of aproved, stable solutions, do not like to reinvent
the wheel.


I'm afraid this particular kind of wheel has not been invented yet.
You may find more interested people in the i18n SIG - but it does not  
appear to have a lot of traffic lately:

http://mail.python.org/mailman/listinfo/i18n-sig

--
Gabriel Genellina

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


Re: Recommend Commercial graphing library

2010-04-06 Thread Benjamin Kaplan
On Tue, Apr 6, 2010 at 9:05 AM, AlienBaby  wrote:
> On Apr 6, 4:24 pm, Jean-Michel Pichavant 
> wrote:
>> Pablo Recio Quijano wrote:
>> > Why must be commercial, when there is open and free alternatives? Like
>> > GNU Plot.
>>
>> Gnuplot is ugly. I'm using it because I don't care if it's ugly but it
>> clearly lacks of look & feel for presentations, as requested by the OP.
>>
>> You havehttp://matplotlib.sourceforge.net/
>>
>> which is free and looks better than gnuplot. I'm not sure it's well
>> suited for presentation though.
>>
>> JM
>
> Hi,
>
> The requirement for a commercial license comes down to being
> restricted to not using any open source code. If it's an open source
> license it can't be used in our context.
>
> Until now I have actually been using matplotlib, but now that has to
> change.
> --

Just out of curiosity, where does this requirement come from?
Matplotlib (like Python itself) is offered under a license that
basically says "here's the source code. Do whatever you want with it".
Any policy that prevented you from using Matplotlib would prevent you
from using Python too.

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


Re: Incorrect scope of list comprehension variables

2010-04-06 Thread Stephen Hansen

On 2010-04-06 09:34:04 -0700, Lie Ryan said:

 in python there is only a flat
local namespace and the names resolver becomes a thousand times simpler
(and faster).


This hasn't been true for a long time. Yes, local variables are 
optimized to be indexed in an array, but Python has nested scopes for 
functions. But it does not have true lexical scoping, no.


--
--S

... p.s: change the ".invalid" to ".com" in email address to reply privately.

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


Re: Recommend Commercial graphing library

2010-04-06 Thread Michael Torrie
On 04/06/2010 10:05 AM, AlienBaby wrote:
> The requirement for a commercial license comes down to being
> restricted to not using any open source code. If it's an open source
> license it can't be used in our context.

Python itself and all its standard libraries are open source, under the
PSF license, if I recall.  Doesn't look like you can use python at all.
 You simply cannot write a python program without some open source code
being used.

I don't understand the propensity of companies and individuals to think
of open source code as different than proprietary.  It's not at all.
All code that you use that was not written by you or owned by you has to
be used under license from the copyright holder.

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


Re: Recommend Commercial graphing library

2010-04-06 Thread superpollo

Grant Edwards ha scritto:

On 2010-04-06, Grant Edwards  wrote:

On 2010-04-06, Jean-Michel Pichavant  wrote:

Pablo Recio Quijano wrote:
Why must be commercial, when there is open and free alternatives? Like 
GNU Plot.
Gnuplot is ugly. I'm using it because I don't care if it's ugly but it 
clearly lacks of look & feel for presentations, as requested by the OP.

  ^^
  
In other words, Gnuplot presents information in a clear, obfuscated
   
That should be:   unobsuscated


stupid spell-checker...
   
Seriously, most of the graphs I've seen in "presentations" would make

Ed Tufte spin in his grave.


didn't know he died.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python script error when using print

2010-04-06 Thread superpollo

Robbie ha scritto:

Hi all,

So, I'm trying to use Python with an apache2 server to create some web
pages.  The web server is configured and seems to work correctly, but
only with a certain type of script.

For instance, this script works fine

#!/usr/bin/env python
def index():
s = "Hello World"
return s

But, a script like this, does not.
#!/usr/bin/env python
print "hello world"

When I try to use the script with print, the server returns a broken
link error.  There is nothing in the apache error log to help me
understand why it won't work.

Any help?


looks like some cgi issue to me...
--
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-06 Thread Duncan Booth
Albert van der Horst  wrote:

> Old hands would have ...
> stamp =( weight>=1000 and  120 or
>  weight>=500  and  100 or
>  weight>=250  and  80  or
>  weight>=100  and  60  or
>44  )
> 
> (Kind of a brain twister, I think, inferior to C, once the c-construct
> is accepted as idiomatic.)

I doubt many old hands would try to join multiple and/or operators that 
way. Most old hands would (IMHO) write the if statements out in full, 
though some might remember that Python comes 'batteries included':

 from bisect import bisect
 WEIGHTS = [100, 250, 500, 1000]
 STAMPS = [44, 60, 80, 100, 120]

 ...
 stamp = STAMPS[bisect(WEIGHTS,weight)]

>>> map(lambda weight: STAMPS[bisect(WEIGHTS, weight)], [20, 100, 150, 999, 
1000, 1100])
[44, 60, 60, 100, 120, 120]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread Duncan Booth
Grant Edwards  wrote:

> Seriously, most of the graphs I've seen in "presentations" would make
> Ed Tufte spin in his grave.

http://flowingdata.com/2010/03/20/powerpoint-and-dying-kittens/
-- 
http://mail.python.org/mailman/listinfo/python-list


upcoming Python training in Florida, April 27-29

2010-04-06 Thread Mark Lutz
Greetings Python fans,

Don't miss your chance to attend our upcoming Florida
Python training seminar later this month. This 3-day
public class will be held on April 27-29, in Sarasota,
Florida.  It is open to both individuals and groups.

For more details on the class, as well as registration
instructions, please visit the class web page:

http://learning-python.com/2010-public-classes.html

If you are unable to attend in April, our next Sarasota
class is already scheduled for July 13-15.

Thanks, and we hope to see you at a Python class in
Florida soon.

--Mark Lutz (lutz at learning-python.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread AlienBaby
I am just looking at the PSF license now as it goes. It does appear
that we should be able to continue using matplotlib. - the
restrictions on open-source that have been imposed specifically state
it is fine to use the python language, and if matplotlib has the same
license I personally can't see any issue. However, the decision is not
mine.

The company I am with is unsure, and while they will pursue the
possible use of matplotlib with the PSF license, they would prefer I
continued to look into any commercially licensed libraries that could
be used.


...and as it goes, the first thing I fired back at them when I was
told 'no open source can be used' was basically 'What on earth are we
going to use to code it in...' and that the 'no open source'
restriciton as given was overly broad when you think about it.





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


Re: Is there a standard name for this tree structure?

2010-04-06 Thread egbert
On Sun, Apr 04, 2010 at 12:10:02PM +, Steven D'Aprano wrote:
 
> I can implement this tree using a flat dict:
> 
> root = object()
> data = {root: ['Mammal', 'Reptile'], 

What is the advantage, or thougth behind, using an instance
of object as the root of your flat tree ?
egbert

-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Pickle problem while loading a class instance.

2010-04-06 Thread gerardob

Hello, I am new to python and i have a problem using the pickle load
function.
I have an object m of the class MarkovModel and i want to copy it to a file
and load it onto another class:

l=[1,2,3]
m = markov_model.MarkovModel()
m.load_observations(l)
file = open("prueba.txt", 'w')
pickle.dump(m,file,2)
file.close()

#m2 = markov_model.MarkovModel()

file = open("prueba.txt", 'rb')
m2 = pickle.load(file) (THIS IS LINE 36)

The error below appears. In the case i remove the comment to initialize m2,
the same thing happens. Any ideas on how to fix this?

Thanks.

Traceback (most recent call last):
File "C:\Users\gberbeglia\Documents\python\scripting\mycodes\main.py", line
36, in 
m2 = pickle.load(file)
File "C:\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "C:\Python26\lib\pickle.py", line 1124, in find_class
__import__(module)
ImportError: No module named markov_model
-- 
View this message in context: 
http://old.nabble.com/Pickle-problem-while-loading-a-class-instance.-tp28154964p28154964.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


imports again

2010-04-06 Thread Alex Hall
Sorry this is a forward (long story involving a braille notetaker's
bad copy/paste and GMail's annoying mobile site). Basically, I am
getting errors when I run the project at
http://www.gateway2somewhere.com/sw.zip
and I do not understand why. The bad line was working until I added
more import statements. I know my setup is not good, but I cannot seem
to get my own packages to work (putting files in a folder along with
__init__.py). If anyone can explain what I did and how I can fix it, I
would very much appreciate it!! Requires Windows, tested on Vista/xp/7
with python2.6.

-- Forwarded message --
From: Alex Hall 
Date: Tue, 6 Apr 2010 13:06:24 -0400
Subject: imports again
To: python-us...@python.org

Hello all,
My project is stalled because of an import problem. I know my imports
are a tangled mess (1 imports 2 3 and 4, 2 imports 1 and 3, 3 imports
2 and 4, and so on). I would very much appreciate it if someone could
look at the setup and recommend a fix. Right now, an exception is
being thrown when I import a file, even though this import was working
until I added some different import statements. The entire thing,
intended for Windows xp+ and Python2.6, is at
http://www.gateway2somewhere.com/sw.zip
Thanks in advance for any help or suggestions!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap



-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pass object or use self.object?

2010-04-06 Thread Lie Ryan
On 04/06/10 23:52, Tim Arnold wrote:
> Hi,
> I have a few classes that manipulate documents. One is really a
> process that I use a class for just to bundle a bunch of functions
> together (and to keep my call signatures the same for each of my
> manipulator classes).
> 
> So my question is whether it's bad practice to set things up so each
> method operates on self.document or should I pass document around from
> one function to the next?
> pseudo code:
> 
> class ManipulatorA(object):
> def process(self, document):
> document = self.do_one_thing(document)
> document = self.do_another_thing(document)
> # bunch of similar lines
> return document
> 
> or
> 
> class ManipulatorA(object):
> def process(self, document):
> self.document = document
> self.do_one_thing() # operates on self.document
> self.do_another_thing()
> # bunch of similar lines
> return self.document

Since in function in python is a first-class object, you can instead do
something like:

def process(document):
# note: document should encapsulate its own logic
document.do_one_thing()
document.do_another_thing()

And when you need some complex logic, you can easily elevate your
function to a class:

class Appender(object):
def __init__(self, text):
self.text = text
def __call__(self, document):
mtext = self.manipulate(document, text)
document.append(mtext)

and I think for your purpose, the mixin pattern could cleanly separate
manipulation and document while still obeying object-oriented pattern
that document is self-sufficient:

# language with only single-inheritance can only dream to do this
class Appendable(object):
def append(self, text):
self.text += text
class Savable(object):
def save(self, fileobj):
fileobj.write(self.text)
class Openable(object):
def open(self, fileobj):
self.text = fileobj.read()
class Document(Appendable, Savable, Openable):
def __init__(self):
self.text = ''
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pickle problem while loading a class instance.

2010-04-06 Thread Peter Otten
gerardob wrote:

> Hello, I am new to python and i have a problem using the pickle load
> function.
> I have an object m of the class MarkovModel and i want to copy it to a
> file and load it onto another class:
> 
> l=[1,2,3]
> m = markov_model.MarkovModel()
> m.load_observations(l)
> file = open("prueba.txt", 'w')

Remember to open the file in binary mode.

> pickle.dump(m,file,2)
> file.close()
> 
> #m2 = markov_model.MarkovModel()
> 
> file = open("prueba.txt", 'rb')
> m2 = pickle.load(file) (THIS IS LINE 36)
> 
> The error below appears. In the case i remove the comment to initialize
> m2, the same thing happens. Any ideas on how to fix this?

Add the directory containing the markov_model module to your PYTHONPATH 
environment variable or move the module into a directory where Python is 
already looking (C:/Python26/lib/site-packages or the per-user equivalent).

See also http://docs.python.org/using/windows.html#finding-modules

> Traceback (most recent call last):
> File "C:\Users\gberbeglia\Documents\python\scripting\mycodes\main.py",
> line 36, in 
> m2 = pickle.load(file)
> File "C:\Python26\lib\pickle.py", line 1370, in load
> return Unpickler(file).load()
> File "C:\Python26\lib\pickle.py", line 858, in load
> dispatch[key](self)
> File "C:\Python26\lib\pickle.py", line 1090, in load_global
> klass = self.find_class(module, name)
> File "C:\Python26\lib\pickle.py", line 1124, in find_class
> __import__(module)
> ImportError: No module named markov_model

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


Re: Pickle problem while loading a class instance.

2010-04-06 Thread Lie Ryan
On 04/07/10 03:23, gerardob wrote:

> The error below appears. In the case i remove the comment to initialize m2,
> the same thing happens. Any ideas on how to fix this?
> 

When unpickling a user-defined class, you unpickling module must have
access to the original class definition. This means if you do this:

# model.py
class MyClass(object):
pass

# saver.py

import pickle
import model

m = model.MyClass()
pickle.dump(m, open('...', 'w'))



Then the loader.py must be able to import model. If you do not
explicitly import model, pickle will automatically try to `import model`
from the standard module search path.

# loader.py

# the import must succeed, or pickle cannot find Foo's definition
#
# import model

pickle.load(open('...'))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python script error when using print

2010-04-06 Thread Albert W. Hopkins
On Tue, 2010-04-06 at 08:38 -0700, Robbie wrote:
> Hi all,
> 
> So, I'm trying to use Python with an apache2 server to create some web
> pages.  The web server is configured and seems to work correctly, but
> only with a certain type of script.
> 
> For instance, this script works fine
> 
> #!/usr/bin/env python
> def index():
> s = "Hello World"
> return s
> 
> But, a script like this, does not.
> #!/usr/bin/env python
> print "hello world"
> 
> When I try to use the script with print, the server returns a broken
> link error.  There is nothing in the apache error log to help me
> understand why it won't work.

Is this a CGI script?  You need to return headers (like Content-type):

e.g. (untested)

print "Content-type: text/plain"
print
print "hello world"

See also
http://docs.python.org/library/cgi.html

-a


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


Performance of list vs. set equality operations

2010-04-06 Thread Gustavo Narea
Hello!

Could you please confirm whether my understanding of equality
operations in sets and lists is correct? This is how I think things
work, partially based on experimentation and the online documentation
for Python:

When you compare two lists, *every* element of one of the lists is
compared against the element at the same position in the other list;
that comparison is done by the __eq__() method (or the equivalent for
builtin types). This is interrupted when a result is False.

When you compare two sets, there's a loop over all the elements of the
first set, where the hash for that element is looked up in the second
set:
 - If this hash matches the hash for one or more elements in the
second set, the element in the first set is compared (with __eq__ or
equivalent) against the elements in the second set which have the same
hash. When a result is True, nothing else is done on that element and
the loop takes the next element in the first set; when all the results
are False, the loop ends and the two sets are not equivalent.
 - If the hash doesn't match that of an element in the second set,
then the loop ends and the two sets are not equivalent.

So this means that:
 1.- When you have two collections which have the same elements, the
equality operation will *always* be faster with lists.
 2.- When you have two collections with different elements, the
equality operation *may* be faster with sets.

For example, if you have two collections of 1,000 elements each and
998 of them are equivalent, comparing both collections as sets will be
slower than doing it with lists. But if you have two collections of
1,000 elements each and 998 of them are not equivalent, then comparing
both collections as lists will be slower than doing it with sets.

The performance of equality operations on sets is directly
proportional to the amount of different elements in both sets, while
the performance of equality operations on lists is simply proportional
to the cardinality of the collection.

In other words: The more different elements two collections have, the
faster it is to compare them as sets. And as a consequence, the more
equivalent elements two collections have, the faster it is to compare
them as lists.

Is this correct?

This is why so many people advocate the use of sets instead of lists/
tuples in similar situations, right?

Cheers,

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


Re: Recommend Commercial graphing library

2010-04-06 Thread Robert Kern

On 2010-04-06 11:44 AM, superpollo wrote:

Grant Edwards ha scritto:

On 2010-04-06, Grant Edwards  wrote:

On 2010-04-06, Jean-Michel Pichavant  wrote:

Pablo Recio Quijano wrote:

Why must be commercial, when there is open and free alternatives?
Like GNU Plot.

Gnuplot is ugly. I'm using it because I don't care if it's ugly but
it clearly lacks of look & feel for presentations, as requested by
the OP.

^^
In other words, Gnuplot presents information in a clear, obfuscated

That should be: unobsuscated

stupid spell-checker...
Seriously, most of the graphs I've seen in "presentations" would make
Ed Tufte spin in his grave.


didn't know he died.


He hasn't.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Recommend Commercial graphing library

2010-04-06 Thread Grant Edwards
On 2010-04-06, superpollo  wrote:
> Grant Edwards ha scritto:
>> On 2010-04-06, Grant Edwards  wrote:
>>> On 2010-04-06, Jean-Michel Pichavant  wrote:
 Pablo Recio Quijano wrote:
> Why must be commercial, when there is open and free alternatives? Like 
> GNU Plot.
 Gnuplot is ugly. I'm using it because I don't care if it's ugly but it 
 clearly lacks of look & feel for presentations, as requested by the OP.
>>>   ^^
>>>   
>>> In other words, Gnuplot presents information in a clear, obfuscated
>>
>> That should be:   unobsuscated
>> 
>> stupid spell-checker...
>>
>> Seriously, most of the graphs I've seen in "presentations" would make
>> Ed Tufte spin in his grave.
>
> didn't know he died.

If'd seen some of those graphs he would have.

-- 
Grant Edwards   grant.b.edwardsYow! I'm having an
  at   emotional outburst!!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list vs. set equality operations

2010-04-06 Thread Chris Colbert
the proof is in the pudding:

In [1]: a = range(1)

In [2]: s = set(a)

In [3]: s2 = set(a)

In [5]: b = range(1)

In [6]: a == b
Out[6]: True

In [7]: s == s2
Out[7]: True

In [8]: %timeit a == b
1000 loops, best of 3: 204 us per loop

In [9]: %timeit s == s2
1 loops, best of 3: 124 us per loop


On Tue, Apr 6, 2010 at 2:11 PM, Gustavo Narea  wrote:
> Hello!
>
> Could you please confirm whether my understanding of equality
> operations in sets and lists is correct? This is how I think things
> work, partially based on experimentation and the online documentation
> for Python:
>
> When you compare two lists, *every* element of one of the lists is
> compared against the element at the same position in the other list;
> that comparison is done by the __eq__() method (or the equivalent for
> builtin types). This is interrupted when a result is False.
>
> When you compare two sets, there's a loop over all the elements of the
> first set, where the hash for that element is looked up in the second
> set:
>  - If this hash matches the hash for one or more elements in the
> second set, the element in the first set is compared (with __eq__ or
> equivalent) against the elements in the second set which have the same
> hash. When a result is True, nothing else is done on that element and
> the loop takes the next element in the first set; when all the results
> are False, the loop ends and the two sets are not equivalent.
>  - If the hash doesn't match that of an element in the second set,
> then the loop ends and the two sets are not equivalent.
>
> So this means that:
>  1.- When you have two collections which have the same elements, the
> equality operation will *always* be faster with lists.
>  2.- When you have two collections with different elements, the
> equality operation *may* be faster with sets.
>
> For example, if you have two collections of 1,000 elements each and
> 998 of them are equivalent, comparing both collections as sets will be
> slower than doing it with lists. But if you have two collections of
> 1,000 elements each and 998 of them are not equivalent, then comparing
> both collections as lists will be slower than doing it with sets.
>
> The performance of equality operations on sets is directly
> proportional to the amount of different elements in both sets, while
> the performance of equality operations on lists is simply proportional
> to the cardinality of the collection.
>
> In other words: The more different elements two collections have, the
> faster it is to compare them as sets. And as a consequence, the more
> equivalent elements two collections have, the faster it is to compare
> them as lists.
>
> Is this correct?
>
> This is why so many people advocate the use of sets instead of lists/
> tuples in similar situations, right?
>
> Cheers,
>
>  - Gustavo.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread Grant Edwards
On 2010-04-06, Duncan Booth  wrote:
> Grant Edwards  wrote:
>
>> Seriously, most of the graphs I've seen in "presentations" would make
>> Ed Tufte spin in his grave.
>
> http://flowingdata.com/2010/03/20/powerpoint-and-dying-kittens/

:)

Years ago I was walking past a marketing guy's cube, and on his cube
wall he had Minard's famous "Napolean's March" graph that Tufte so
admired.  I asked him if he had read Tufte's book "The Visual Display
of Quantitative Information" (in which the graph appears).  He replied
that no he hadn't read Tufte's book -- he'd gotten that graph from a
power-point-driven lecture in some MBA class or other.

-- 
Grant Edwards   grant.b.edwardsYow! I'm rated PG-34!!
  at   
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translation docstrings with gettext

2010-04-06 Thread Lie Ryan
On 04/06/10 19:52, sapient wrote:
> Lie Ryan, thank you for your answer!
>> Why would you want to translate docstring? Docstring is meant for
>> developers not users.
> I have mentioned that I want to provide API for existing image-
> processing applicaion in Python.
> In my case "developers" are "users".
> Python provides great possibilities for documenting objects, I want to
> use it for things such context help about API modules, classes,
> methods, and want to do it in several languages.
> 
>> Maintaining a translated docstring is going to be
>> a maintenance hell and will either hampers your application's agility or
>> you will be left with obsolete docstrings in various languages you don't
>> know.
> You are right, there are problems here, but there are advantages too
> (we are talking about API): developers can write documentation in
> thier "cracked" English (like my), but professional translator can
> correct it after with Poedit.

Fair enough.

>> Anyway, my job is to answer questions, not question the economic
>> feasibility of your decision, so try this:
>>
>> #!python
>> __doc__ = _("""testmodule docstring""")
>>
>> class TestClass:
>> __doc__ = _("""testmodule.TestClass docstring""")
>>
>> def testClassMethod(self):
>> __doc__ = _("""testmodule.TestClass.testClassMethod docstring""")
>> print _("Call TestClass.testClassMethod()")
> Yes, I tried this method, but it does not work with methods and
> functions, this line
>> __doc__ = _("""testmodule.TestClass.testClassMethod docstring""")
> does nothing (There are not output in help()). 

Ah, my bad; I didn't notice.

> Is it any way to assign
> docstring for function explicity?

Yes there is, you will need to reassign the (translated) __doc__ from
*outside* the function definition, a decorator will provide nice
wrapper. This works:

__doc__ = _("""testmodule docstring""")__doc__ = _("""testmodule
docstring""")

def tdoc(obj):
obj.__doc__ = _(obj.__doc__)
return obj

@tdoc
class TestClass:
"""testmodule.TestClass docstring"""
@tdoc
def testClassMethod(self):
"""testmodule.TestClass.testClassMethod docstring"""
print _("Call TestClass.testClassMethod()")

# the decorator is equivalent to:
# def testClassMethod(self):
# print _("Call TestClass.testClassMethod()")
# testClassMethod.__doc__ = _(testClassMethod.__doc__)


as I said, you probably will want to use some metaclass magic to
automatically apply tdoc to all classes and methods. If just mandating
that tdoc must decorate everything works for you, then great.

>> If you want to avoid having the explicit assignment to __doc__, you can
>> also try using some metaclass or decorator magic to automatically wraps
>> docstring in a _() call.
> 
> Yes, it will be better to avoid them, is it any existing tool/lib/
> workaround that can do it?
> I am follower of aproved, stable solutions, do not like to reinvent
> the wheel.

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


python as pen and paper substitute

2010-04-06 Thread Manuel Graune
Hello everyone,

I am looking for ways to use a python file as a substitute for simple
pen and paper calculations. At the moment I mainly use a combination
of triple-quoted strings, exec and print (Yes, I know it's not exactly
elegant). To clarify, I just start an editor, write a file that
might look something like this:

-snip-
code="""
a = 1
b = 2
c = 3
result = a + b
"""
exec(code)
print(code)
print("result =\t", result)
print("result + c =\t", result + c)
-snip--

and feed this to python.

For what it's worth, this approach achieves what it's supposed to,
which is to get some basic control over the output and
to avoid to much redundant typing.

Now I'm wondering if there is a more elegant method to achieve this which
e. g. does not mess up the syntax-hightlighting, does not use exec()
and avoids the redundant mentioning of the variable that holds the
acutal code. Since I have complete control over the input and the files
are not supposed to be shared, security should not a problem and
simplicity is criterion #1.


So, does anyone have tips?

Regards,

Manuel

P.S.: I know Ipython. In the cases where I use the hack shown above
it just does not fit my workflow




-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Simplify Python

2010-04-06 Thread ja1lbr3ak
I'm trying to teach myself Python, and so have been simplifying a
calculator program that I wrote. The original was 77 lines for the
same functionality. Problem is, I've hit a wall. Can anyone help?

loop = input("Enter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: ")
while loop < 3 and loop > 0:
if loop == 1:
print input("\nPut in an equation: ")
if loop == 2:
a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
go to? "))
while n > 0:
print a
a, b, n = b, a+b, n-1
loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: ")

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


Impersonating a Different Logon

2010-04-06 Thread Kevin Holleran
Hello,

I am sweeping some of our networks to find devices.  When I find a
device I try to connect to the registry using _winreg and then query a
specific key that I am interested in.  This works great for machines
that are on our domain, but there are left over machines that are
stand alone and the credentials fail.  I understand you cannot pass in
credentials with _winreg but is there a way to simulate a logon of
another user (the machine's local admin) to query the registry?

Thanks for your help.

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


plotting in python 3

2010-04-06 Thread Rolf Camps
Hi,

What's the easiest way to plot graphs in python 3.x? Ís there a package?
Quality doesn't really matter.

Thanks,

Rolf


signature.asc
Description: Dit berichtdeel is digitaal ondertekend
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: per-method jit compiler

2010-04-06 Thread Irmen de Jong

On 6-4-2010 8:22, Luis M. González wrote:

The above post gave me an idea (very naive, of couse).
What if I write a simple decorator to figure out the types of every
function, and then we use it as a base for a simple method-jit
compiler for python?
example:
def typer(f):
 def wrap(*args):
 a = f.func_code.co_varnames
 b = [type(i) for i in args]
 return dict(zip(a,b))
 return wrap
@typer
def spam(a, b, c=3, d=4):
 pass

spam(8,'hello',9.9, 10)


{'a':, 'c':, 'b':, 'd':
}
So by using this information, we record all the argument types used
the first time each function/method is executed, and then we generate
optimized code for them.
 From this point on, a guard should check if all arguments remain the
same and, if so, the optimized code is run.
Otherwise, just fall back to the interpreter.
He! I have no idea how to implement it...
Any guru out there?
Luis


Isn't this what Psyco (http://psyco.sourceforge.net/) does?

-irmen


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


Re: plotting in python 3

2010-04-06 Thread Christopher Choi
On Tue, 06 Apr 2010 21:23:34 +0200, Rolf Camps wrote:

> Hi,
> 
> What's the easiest way to plot graphs in python 3.x? Ís there a package?
> Quality doesn't really matter.
> 
> Thanks,
> 
> Rolf
> Hi,
> 
> What's the easiest way to plot graphs in python 3.x? Ís there a package?
> Quality doesn't really matter.
> 
> Thanks,
> 
> Rolf

I would like to think you have done some home work yourself 
but anyways... gnuplot with python seems easy..

http://gnuplot-py.sourceforge.net/doc/

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


Re: Simplify Python

2010-04-06 Thread Christopher Choi
On Tue, 06 Apr 2010 12:04:20 -0700, ja1lbr3ak wrote:

> I'm trying to teach myself Python, and so have been simplifying a
> calculator program that I wrote. The original was 77 lines for the same
> functionality. Problem is, I've hit a wall. Can anyone help?
> 
> loop = input("Enter 1 for the calculator, 2 for the Fibonacci sequence,
> or something else to quit: ") while loop < 3 and loop > 0:
> if loop == 1:
> print input("\nPut in an equation: ")
> if loop == 2:
> a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
> go to? "))
> while n > 0:
> print a
> a, b, n = b, a+b, n-1
> loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: ")

I'm fairly confused here. 

But I would do this instead:

UserInput1 = input("Enter 1 for the calculator, 2 for the Fibonacci 
sequence, or something else to quit: ")

While quit = 0: 
if UserInput1 == 1:
print input("\nPut in an equation: ")
else if UserInput1 == 2:
a, b, n = 1, 1, (input("\nWhat Fibonacci number do you 
want to go to? "))
while n > 0:
print a
a, b, n = b, a+b, n-1
UserInput2 = input("\nEnter 1 for the calculator, 
2 for the Fibonacci sequence, or something else to quit: ")

else 
quit = 1


the above is not finished... but without actually knowing what your trying 
to do.. the above code I just did would make a lot more sense.. I hope... 
You hit a wall cause the first while loop you had before never ends..

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


Re: Impersonating a Different Logon

2010-04-06 Thread Tim Golden

On 06/04/2010 20:26, Kevin Holleran wrote:

Hello,

I am sweeping some of our networks to find devices.  When I find a
device I try to connect to the registry using _winreg and then query a
specific key that I am interested in.  This works great for machines
that are on our domain, but there are left over machines that are
stand alone and the credentials fail.  I understand you cannot pass in
credentials with _winreg but is there a way to simulate a logon of
another user (the machine's local admin) to query the registry?


The simplest may well be to use WMI (example from here):

http://timgolden.me.uk/python/wmi/cookbook.html#list-registry-keys


import wmi

reg = wmi.WMI (
  "machine",
  user="machine\admin",
  password="Secret",
  namespace="DEFAULT"
).StdRegProv

result, names = reg.EnumKey (
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName="Software"
)
for name in names:
  print name



I can't try it out at the moment but in principle it should work.

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


Re: Simplify Python

2010-04-06 Thread ja1lbr3ak
On Apr 6, 4:06 pm, Christopher Choi  wrote:
> On Tue, 06 Apr 2010 12:04:20 -0700, ja1lbr3ak wrote:
> > I'm trying to teach myself Python, and so have been simplifying a
> > calculator program that I wrote. The original was 77 lines for the same
> > functionality. Problem is, I've hit a wall. Can anyone help?
>
> > loop = input("Enter 1 for the calculator, 2 for the Fibonacci sequence,
> > or something else to quit: ") while loop < 3 and loop > 0:
> >     if loop == 1:
> >         print input("\nPut in an equation: ")
> >     if loop == 2:
> >         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
> > go to? "))
> >         while n > 0:
> >             print a
> >             a, b, n = b, a+b, n-1
> >     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> > sequence, or something else to quit: ")
>
> I'm fairly confused here.
>
> But I would do this instead:
>
> UserInput1 = input("Enter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: ")
>
> While quit = 0:
>         if UserInput1 == 1:
>                 print input("\nPut in an equation: ")
>         else if UserInput1 == 2:
>                 a, b, n = 1, 1, (input("\nWhat Fibonacci number do you
> want to go to? "))
>                 while n > 0:
>                         print a
>                         a, b, n = b, a+b, n-1
>                         UserInput2 = input("\nEnter 1 for the calculator,
> 2 for the Fibonacci sequence, or something else to quit: ")
>
>         else
>                 quit = 1
>
> the above is not finished... but without actually knowing what your trying
> to do.. the above code I just did would make a lot more sense.. I hope...
> You hit a wall cause the first while loop you had before never ends..

The while loop is my main program loop. There at the end is the "loop
= input" part again. If you type in something other than 1 or 2, it
exits the while loop and ends the program. I also merged the "quit"
and "UserInput1" variables in your program into one "loop" variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing command line arguments to executable

2010-04-06 Thread Bror Johansson

On 2010-04-03 18:09, mcanjo wrote:

I have an executable (I don't have access to the source code) that
processes some data. I double click on the icon and a Command prompt
window pops up. The program asks me for the input file, I hit enter,
and then it asks me for and output filename, I hit enter a second time
and it goes off and does its thing and when it is finished running the
Command Prompt goes away and I have my new output file in the same
directory as my executable and input file. I would like to be able to
batch process a group of files. I thought about using "os.spawnv()" in
a loop and at each iteration of the loop passing in the file in and
out names but that didn't work. Does anyone have any ideas?


It's been quite a while since I had to solve problems like the one you 
have. Sometimes I used a Python implementation of 'expect' successfully.

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


Re: Simplify Python

2010-04-06 Thread Christopher Choi
On Tue, 06 Apr 2010 13:14:44 -0700, ja1lbr3ak wrote:

> On Apr 6, 4:06 pm, Christopher Choi  wrote:
>> On Tue, 06 Apr 2010 12:04:20 -0700, ja1lbr3ak wrote:
>> > I'm trying to teach myself Python, and so have been simplifying a
>> > calculator program that I wrote. The original was 77 lines for the
>> > same functionality. Problem is, I've hit a wall. Can anyone help?
>>
>> > loop = input("Enter 1 for the calculator, 2 for the Fibonacci
>> > sequence, or something else to quit: ") while loop < 3 and loop > 0:
>> >     if loop == 1:
>> >         print input("\nPut in an equation: ")
>> >     if loop == 2:
>> >         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you
>> >         want to
>> > go to? "))
>> >         while n > 0:
>> >             print a
>> >             a, b, n = b, a+b, n-1
>> >     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
>> > sequence, or something else to quit: ")
>>
>> I'm fairly confused here.
>>
>> But I would do this instead:
>>
>> UserInput1 = input("Enter 1 for the calculator, 2 for the Fibonacci
>> sequence, or something else to quit: ")
>>
>> While quit = 0:
>>         if UserInput1 == 1:
>>                 print input("\nPut in an equation: ")
>>         else if UserInput1 == 2:
>>                 a, b, n = 1, 1, (input("\nWhat Fibonacci number
>>                 do you
>> want to go to? "))
>>                 while n > 0:
>>                         print a
>>                         a, b, n = b, a+b, n-1
>>                         UserInput2 = input("\nEnter 1 for
>>                         the calculator,
>> 2 for the Fibonacci sequence, or something else to quit: ")
>>
>>         else
>>                 quit = 1
>>
>> the above is not finished... but without actually knowing what your
>> trying to do.. the above code I just did would make a lot more sense..
>> I hope... You hit a wall cause the first while loop you had before
>> never ends..
> 
> The while loop is my main program loop. There at the end is the "loop =
> input" part again. If you type in something other than 1 or 2, it exits
> the while loop and ends the program. I also merged the "quit" and
> "UserInput1" variables in your program into one "loop" variable.


Can you post it please?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python as pen and paper substitute

2010-04-06 Thread Johan Grönqvist

Manuel Graune skrev:

To clarify, I just start an editor, write a file that
might look something like this:

-snip-
code="""
a = 1
b = 2
c = 3
result = a + b
"""
exec(code)
print(code)
print("result =\t", result)
print("result + c =\t", result + c)
-snip--

and feed this to python.



I do not understand your use-case, but as one way of performing the same 
task as the above code, without sacrificing syntax-highlighting, I would 
suggest:


-
from __future__ import with_statement
import sys

def print_source():
print sys.argv
with open(sys.argv[0]) as file:
for line in file:
print line,

a = 1
b = 2
c = 3
result = a + b

print_source()
print("result =\t", result)
print("result + c =\t", result + c)




Does that help towards a solution of your problem?

/ johan

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


Re: Python script error when using print

2010-04-06 Thread Pierre Quentel
On 6 avr, 20:14, "Albert W. Hopkins"  wrote:
> On Tue, 2010-04-06 at 08:38 -0700, Robbie wrote:
> > Hi all,
>
> > So, I'm trying to use Python with an apache2 server to create some web
> > pages.  The web server is configured and seems to work correctly, but
> > only with a certain type of script.
>
> > For instance, this script works fine
>
> > #!/usr/bin/env python
> > def index():
> >     s = "Hello World"
> >     return s
>
> > But, a script like this, does not.
> > #!/usr/bin/env python
> > print "hello world"
>
> > When I try to use the script with print, the server returns a broken
> > link error.  There is nothing in the apache error log to help me
> > understand why it won't work.
>
> Is this a CGI script?  You need to return headers (like Content-type):
>
> e.g. (untested)
>
> print "Content-type: text/plain"
> print
> print "hello world"
>
> See alsohttp://docs.python.org/library/cgi.html
>
> -a

Hi,

Are you trying to use some Python web framework behind Apache ? (as
suggested by the fact that your first script "runs", i.e. probably
prints "Hello World"). In this case the "not found" error in the
second script would mean that the framework requires a function in the
script

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


Re: Simplify Python

2010-04-06 Thread ja1lbr3ak
On Apr 6, 4:17 pm, Christopher Choi  wrote:
> On Tue, 06 Apr 2010 13:14:44 -0700, ja1lbr3ak wrote:
> > On Apr 6, 4:06 pm, Christopher Choi  wrote:
> >> On Tue, 06 Apr 2010 12:04:20 -0700, ja1lbr3ak wrote:
> >> > I'm trying to teach myself Python, and so have been simplifying a
> >> > calculator program that I wrote. The original was 77 lines for the
> >> > same functionality. Problem is, I've hit a wall. Can anyone help?
>
> >> > loop = input("Enter 1 for the calculator, 2 for the Fibonacci
> >> > sequence, or something else to quit: ") while loop < 3 and loop > 0:
> >> >     if loop == 1:
> >> >         print input("\nPut in an equation: ")
> >> >     if loop == 2:
> >> >         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you
> >> >         want to
> >> > go to? "))
> >> >         while n > 0:
> >> >             print a
> >> >             a, b, n = b, a+b, n-1
> >> >     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> >> > sequence, or something else to quit: ")
>
> >> I'm fairly confused here.
>
> >> But I would do this instead:
>
> >> UserInput1 = input("Enter 1 for the calculator, 2 for the Fibonacci
> >> sequence, or something else to quit: ")
>
> >> While quit = 0:
> >>         if UserInput1 == 1:
> >>                 print input("\nPut in an equation: ")
> >>         else if UserInput1 == 2:
> >>                 a, b, n = 1, 1, (input("\nWhat Fibonacci number
> >>                 do you
> >> want to go to? "))
> >>                 while n > 0:
> >>                         print a
> >>                         a, b, n = b, a+b, n-1
> >>                         UserInput2 = input("\nEnter 1 for
> >>                         the calculator,
> >> 2 for the Fibonacci sequence, or something else to quit: ")
>
> >>         else
> >>                 quit = 1
>
> >> the above is not finished... but without actually knowing what your
> >> trying to do.. the above code I just did would make a lot more sense..
> >> I hope... You hit a wall cause the first while loop you had before
> >> never ends..
>
> > The while loop is my main program loop. There at the end is the "loop =
> > input" part again. If you type in something other than 1 or 2, it exits
> > the while loop and ends the program. I also merged the "quit" and
> > "UserInput1" variables in your program into one "loop" variable.
>
> Can you post it please?

It's what I posted before, but I'll add some documentation.

loop = input("Enter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: ") #sets what loop is equal to
while loop < 3 and loop > 0: #if the input is less than 3 and greater
than 0, it continues. otherwise, it exits
if loop == 1: #it has to be 1 or 2 because of the last line, so if
it's 1...
print input("\nPut in an equation: ") #it asks for an
equation, does it, then prints the result
if loop == 2: #if it's 2...
a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
go to? ")) #it sets a + b to 1, and n to the input
while n > 0: #for as long as n is greater than 0
print a #it prints a
a, b, n = b, a+b, n-1 #then sets a = b, b = a+b, and n =
n-1
loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: ") #finally, it asks for the
input again. if it's 1 or 2, the loop starts over. otherwise, it
exits.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: plotting in python 3

2010-04-06 Thread Rolf Camps
Op dinsdag 06-04-2010 om 14:55 uur [tijdzone -0500], schreef Christopher
Choi:
> On Tue, 06 Apr 2010 21:23:34 +0200, Rolf Camps wrote:
> 
> > Hi,
> > 
> > What's the easiest way to plot graphs in python 3.x? Ís there a package?
> > Quality doesn't really matter.
> > 
> > Thanks,
> > 
> > Rolf
> > Hi,
> > 
> > What's the easiest way to plot graphs in python 3.x? Ís there a package?
> > Quality doesn't really matter.
> > 
> > Thanks,
> > 
> > Rolf
> 
> I would like to think you have done some home work yourself 
> but anyways... gnuplot with python seems easy.

> .
> 
> http://gnuplot-py.sourceforge.net/doc/


It was after the homework I asked my question. All plot solutions i
found where for python2.x. gnuplot_py states on its homepage you need a
'working copy of numpy'. I don't think numpy is ported to python 3.x. Or
is it? 
> 
> Chris



signature.asc
Description: Dit berichtdeel is digitaal ondertekend
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simplify Python

2010-04-06 Thread Joaquin Abian
On Apr 6, 9:04 pm, ja1lbr3ak  wrote:
> I'm trying to teach myself Python, and so have been simplifying a
> calculator program that I wrote. The original was 77 lines for the
> same functionality. Problem is, I've hit a wall. Can anyone help?
>
> loop = input("Enter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: ")
> while loop < 3 and loop > 0:
>     if loop == 1:
>         print input("\nPut in an equation: ")
>     if loop == 2:
>         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
> go to? "))
>         while n > 0:
>             print a
>             a, b, n = b, a+b, n-1
>     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: ")

You could structure it a bit better but something to start with could
be(it works):

def calc(n):
print n

def fibo(n):
a=b=1
while n > 0:
print a
a, b, n = b, a+b, n-1


NOTE = """Enter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: """

while True:

loop = raw_input(NOTE)

if loop == '1':
forcalc = raw_input("\nPut in an equation: ")
calc(forcalc)
elif loop == '2':
forfibo = raw_input("\nWhat Fibonacci number do you want to go
to? ")
n = int(forfibo)
fibo(n)
else:
break


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


Re: python as pen and paper substitute

2010-04-06 Thread Manuel Graune
Thanks for your reply.

Johan Grönqvist  writes:
> Manuel Graune skrev:
>> To clarify, I just start an editor, write a file that
>> might look something like this:
>>
>> -snip-
>> code="""
>> a = 1
>> b = 2
>> c = 3
>> result = a + b
>> """
>> exec(code)
>> print(code)
>> print("result =\t", result)
>> print("result + c =\t", result + c)
>> -snip--
>>
>> and feed this to python.
>>
>
> I do not understand your use-case, but as one way of performing the
> same task as the above code, without sacrificing syntax-highlighting,

The use-case is acually fairly simple. The point is to use a python
source-file as subsitute for scrap-paper (with the opportunity to
edit what is already written and without illegible handwriting).
The output should  1) show manually selected python code and comments
(whatever I think is important), 2) show selected results (final and
intermediate) and 3) *not* show python code that for someone only
interested in the calculation and the results (and probably not
knowing python) would just be "noise" (e. g. "import"-statements,
actual "print()"-functions, etc.). 

> from __future__ import with_statement
> import sys
>
> def print_source():
> print sys.argv
> with open(sys.argv[0]) as file:
> for line in file:
> print line,
>
> [...]
>
> print_source()
> print("result =\t", result)
> print("result + c =\t", result + c)


As far as I understand this code, all of this would be printed as well,
which is exactly what I do not want.

Regards,

Manuel


-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simplify Python

2010-04-06 Thread ja1lbr3ak
On Apr 6, 4:56 pm, Joaquin Abian  wrote:
> On Apr 6, 9:04 pm, ja1lbr3ak  wrote:
>
>
>
>
>
> > I'm trying to teach myself Python, and so have been simplifying a
> > calculator program that I wrote. The original was 77 lines for the
> > same functionality. Problem is, I've hit a wall. Can anyone help?
>
> > loop = input("Enter 1 for the calculator, 2 for the Fibonacci
> > sequence, or something else to quit: ")
> > while loop < 3 and loop > 0:
> >     if loop == 1:
> >         print input("\nPut in an equation: ")
> >     if loop == 2:
> >         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
> > go to? "))
> >         while n > 0:
> >             print a
> >             a, b, n = b, a+b, n-1
> >     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> > sequence, or something else to quit: ")
>
> You could structure it a bit better but something to start with could
> be(it works):
>
> def calc(n):
>     print n
>
> def fibo(n):
>     a=b=1
>     while n > 0:
>         print a
>         a, b, n = b, a+b, n-1
>
> NOTE = """Enter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: """
>
> while True:
>
>     loop = raw_input(NOTE)
>
>     if loop == '1':
>         forcalc = raw_input("\nPut in an equation: ")
>         calc(forcalc)
>     elif loop == '2':
>         forfibo = raw_input("\nWhat Fibonacci number do you want to go
> to? ")
>         n = int(forfibo)
>         fibo(n)
>     else:
>         break
>
> Cheers
> Joaquin

Actually, when I tried yours the calculator just spits out the input
again, which is why I used input instead of raw_input.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list vs. set equality operations

2010-04-06 Thread Gustavo Narea
On Apr 6, 7:28 pm, Chris Colbert  wrote:
> the proof is in the pudding:
>
> In [1]: a = range(1)
>
> In [2]: s = set(a)
>
> In [3]: s2 = set(a)
>
> In [5]: b = range(1)
>
> In [6]: a == b
> Out[6]: True
>
> In [7]: s == s2
> Out[7]: True
>
> In [8]: %timeit a == b
> 1000 loops, best of 3: 204 us per loop
>
> In [9]: %timeit s == s2
> 1 loops, best of 3: 124 us per loop


I think you meant to set "s2 = set(b)":
=
In [1]: a = range(1)

In [2]: b = range(1)

In [3]: s1 = set(a)

In [4]: s2 = set(a)

In [5]: s3 = set(b)

In [6]: %timeit a == b
1 loops, best of 3: 191 us per loop

In [7]: %timeit s1 == s2
1 loops, best of 3: 118 us per loop

In [8]: %timeit s1 == s3
1000 loops, best of 3: 325 us per loop
=

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


Re: python as pen and paper substitute

2010-04-06 Thread Manuel Graune
Manuel Graune  writes:
>
> The use-case is acually fairly simple. The point is to use a python
> source-file as subsitute for scrap-paper (with the opportunity to
> edit what is already written and without illegible handwriting).
> The output should  1) show manually selected python code and comments
> (whatever I think is important), 2) show selected results (final and
> intermediate) and 3) *not* show python code that for someone only
> interested in the calculation and the results (and probably not
> knowing python) would just be "noise" (e. g. "import"-statements,
> actual "print()"-functions, etc.). 
>

Just as an additional example, let's assume I'd want to add the area of
to circles.

The source-file would look something like this:
-->snip  source.py   snip<--
#! /usr/bin/python3
from math import pi as PI

code1="""
d1= 3.0
A1= d1**2 * PI / 4.0
"""
exec(code1)
print(code1)
print("Area of Circle 1:\t", A1)

code2="""
d2= 5.0
A2= d1**2 * PI / 4.0
"""
exec(code2)
print(code2)
print("Area of Circle 2:\t", A2)

code3="""
Sum_Of_Areas= A1 + A2
"""
exec(code3)
print(code3)
print("Sum of areas:\t", Sum_Of_Areas)
--->snip<--

And the output is:

d1= 3.0
A1= d1**2 * PI / 4.0

Area of Circle 1:7.06858347058

d2= 5.0
A2= d1**2 * PI / 4.0

Area of Circle 2:7.06858347058

Sum_Of_Areas= A1 + A2

Sum of areas:14.1371669412

which can be explained to anyone who knows
basic math and is not at all interested in
python.


> Regards,
>
> Manuel

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python as pen and paper substitute

2010-04-06 Thread Manuel Graune
Manuel Graune  writes:
>
> The use-case is acually fairly simple. The point is to use a python
> source-file as subsitute for scrap-paper (with the opportunity to
> edit what is already written and without illegible handwriting).
> The output should  1) show manually selected python code and comments
> (whatever I think is important), 2) show selected results (final and
> intermediate) and 3) *not* show python code that for someone only
> interested in the calculation and the results (and probably not
> knowing python) would just be "noise" (e. g. "import"-statements,
> actual "print()"-functions, etc.). 
>

Just as an additional example, let's assume I'd want to add the area of
to circles.

The source-file would look something like this:
-->snip  source.py   snip<--
#! /usr/bin/python3
from math import pi as PI

code1="""
d1= 3.0
A1= d1**2 * PI / 4.0
"""
exec(code1)
print(code1)
print("Area of Circle 1:\t", A1)

code2="""
d2= 5.0
A2= d2**2 * PI / 4.0
"""
exec(code2)
print(code2)
print("Area of Circle 2:\t", A2)

Sum_Of_Areas= A1 + A2
print("Sum of areas:\t", Sum_Of_Areas)
--->snip<--

And the output is:

d1= 3.0
A1= d1**2 * PI / 4.0

Area of Circle 1:7.06858347058

d2= 5.0
A2= d1**2 * PI / 4.0

Area of Circle 2:19.6349540849

Sum of areas:26.703537

which can be explained to anyone who knows
basic math and is not at all interested in
python.


> Regards,
>
> Manuel

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python as pen and paper substitute

2010-04-06 Thread Johan Grönqvist

Manuel Graune skrev:

Thanks for your reply.


The output should  1) show manually selected python code and comments
(whatever I think is important), 2) show selected results (final and
intermediate) and 3) *not* show python code that for someone only
interested in the calculation and the results (and probably not
knowing python) would just be "noise" (e. g. "import"-statements,
actual "print()"-functions, etc.). 



Here is my second attempt. This version introduces what I might 
optimistically call a very simple markup language in the code.
Printing of source can selectively be turned on and off by inserting 
lines beginning with "## Ignore" or "## Show" into the source file.



--
## Ignore
from __future__ import with_statement
import sys

def print_selected_source():
is_printing = True
with open(sys.argv[0]) as file:
for line in file:
if line.startswith("## Ignore"):
is_printing = False
elif line.startswith("## Show"):
is_printing = True
elif is_printing:
print line,


## Show
a = 1
b = 2
c = 3
result = a + b

## Ignore
print_selected_source()
print("result =\t", result)
print("result + c =\t", result + c)
--

Is this getting closer?

/ johan

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


Re: Simplify Python

2010-04-06 Thread Joaquin Abian
On Apr 6, 11:04 pm, ja1lbr3ak  wrote:
> On Apr 6, 4:56 pm, Joaquin Abian  wrote:
>
>
>
> > On Apr 6, 9:04 pm, ja1lbr3ak  wrote:
>
> > > I'm trying to teach myself Python, and so have been simplifying a
> > > calculator program that I wrote. The original was 77 lines for the
> > > same functionality. Problem is, I've hit a wall. Can anyone help?
>
> > > loop = input("Enter 1 for the calculator, 2 for the Fibonacci
> > > sequence, or something else to quit: ")
> > > while loop < 3 and loop > 0:
> > >     if loop == 1:
> > >         print input("\nPut in an equation: ")
> > >     if loop == 2:
> > >         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
> > > go to? "))
> > >         while n > 0:
> > >             print a
> > >             a, b, n = b, a+b, n-1
> > >     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> > > sequence, or something else to quit: ")
>
> > You could structure it a bit better but something to start with could
> > be(it works):
>
> > def calc(n):
> >     print n
>
> > def fibo(n):
> >     a=b=1
> >     while n > 0:
> >         print a
> >         a, b, n = b, a+b, n-1
>
> > NOTE = """Enter 1 for the calculator, 2 for the Fibonacci
> > sequence, or something else to quit: """
>
> > while True:
>
> >     loop = raw_input(NOTE)
>
> >     if loop == '1':
> >         forcalc = raw_input("\nPut in an equation: ")
> >         calc(forcalc)
> >     elif loop == '2':
> >         forfibo = raw_input("\nWhat Fibonacci number do you want to go
> > to? ")
> >         n = int(forfibo)
> >         fibo(n)
> >     else:
> >         break
>
> > Cheers
> > Joaquin
>
> Actually, when I tried yours the calculator just spits out the input
> again, which is why I used input instead of raw_input.

I see. input evaluates your input string while raw_input just yields
the string as a string. I tried to encapsulate the calculator in the
function calc in order for you to implement the logic, making no
assumption about how the calculator should work.
If what you actually want to do is to evaluate strings containing
valid python code you can either use input for the 'Put in an
equation' line or better modify function calc to do the job:

def calc(n):
print eval(n)

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


Re: Performance of list vs. set equality operations

2010-04-06 Thread Chris Colbert
:slaps forehead:

good catch.

On Tue, Apr 6, 2010 at 5:18 PM, Gustavo Narea  wrote:
> On Apr 6, 7:28 pm, Chris Colbert  wrote:
>> the proof is in the pudding:
>>
>> In [1]: a = range(1)
>>
>> In [2]: s = set(a)
>>
>> In [3]: s2 = set(a)
>>
>> In [5]: b = range(1)
>>
>> In [6]: a == b
>> Out[6]: True
>>
>> In [7]: s == s2
>> Out[7]: True
>>
>> In [8]: %timeit a == b
>> 1000 loops, best of 3: 204 us per loop
>>
>> In [9]: %timeit s == s2
>> 1 loops, best of 3: 124 us per loop
>
>
> I think you meant to set "s2 = set(b)":
> =
> In [1]: a = range(1)
>
> In [2]: b = range(1)
>
> In [3]: s1 = set(a)
>
> In [4]: s2 = set(a)
>
> In [5]: s3 = set(b)
>
> In [6]: %timeit a == b
> 1 loops, best of 3: 191 us per loop
>
> In [7]: %timeit s1 == s2
> 1 loops, best of 3: 118 us per loop
>
> In [8]: %timeit s1 == s3
> 1000 loops, best of 3: 325 us per loop
> =
>
> Cheers.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python as pen and paper substitute

2010-04-06 Thread Johan Grönqvist

Manuel Graune skrev:

Manuel Graune  writes:

Just as an additional example, let's assume I'd want to add the area of
to circles.
[...]
which can be explained to anyone who knows
basic math and is not at all interested in
python.



Third attempt. The markup now includes tagging of different parts of the 
code, and printing parts of the source based on a tag.


(Sorry about the mixture of python 2.X and python 3.X print statements, 
I use 2.5)


-
## Ignore
from __future__ import with_statement
import sys

def print_selected_source(tag = ""):
is_printing = True
with open(sys.argv[0]) as file:
for line in file:
if line.startswith("## Ignore"):
is_printing = False
elif line.startswith("## Show") and tag in line:
is_printing = True
elif is_printing:
print line,



from math import pi as PI

## Show Code1
d1= 3.0
A1= d1**2 * PI / 4.0

## Ignore
print_selected_source(tag = "Code1")
print ("Area of Circle 1:\t", A1)

## Show Code2
d2= 5.0
A2= d2**2 * PI / 4.0


## Ignore
print_selected_source(tag = "Code2")
print ("Area of Circle 2:\t", A2)

Sum_Of_Areas= A1 + A2
print ("Sum of areas:\t", Sum_Of_Areas)
-


/ johan

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


Re: Simplify Python

2010-04-06 Thread Dave Angel

ja1lbr3ak wrote:

I'm trying to teach myself Python, and so have been simplifying a
calculator program that I wrote. The original was 77 lines for the
same functionality. Problem is, I've hit a wall. Can anyone help?

loop = input("Enter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: ")
while loop < 3 and loop > 0:
if loop == 1:
print input("\nPut in an equation: ")
if loop == 2:
a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
go to? "))
while n > 0:
print a
a, b, n = b, a+b, n-1
loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
sequence, or something else to quit: ")


  
Since this is apparently some form of self-imposed contest, it'd be nice 
to know the rules.  Usual rule of thumb is to make the program correct 
before trying to optimize it.  For example, this program doesn't guard 
against user error, like entering  AAA+5 for the equation, nor against 
maliciousness, such as entering  range(10**8).


Also, it refers to 'equation' when a better term would be 'expression.'

So, are you trying to minimize line count?  Or character count?  Or 
variables?  Or readability (look up obfuscation contest) ?


You could eliminate the redundant parens around the call to input().
You could eliminate the loop variable and the extra call to input() by 
using break, and moving the test to the beginning of a while-True loop.  
And if you used elif clauses, you wouldn't need the separate if test.
You could probably obfuscate the fibonacci loop by some kind of list 
comprehension.
You could simplify processing n by using range() instead of while.  Then 
no increment is needed.
You could use semicolons to pack multiple statements on each line if 
line count matters, and character count does not.
You could use tab for indenting (yecch) if characters matter.  And use 
one-character variable names (yecch).


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


Re: python as pen and paper substitute

2010-04-06 Thread Dave Angel



Johan Gr wrote:

Manuel Graune skrev:

Thanks for your reply.


The output should  1) show manually selected python code and comments
(whatever I think is important), 2) show selected results (final and
intermediate) and 3) *not* show python code that for someone only
interested in the calculation and the results (and probably not
knowing python) would just be "noise" (e. g. "import"-statements,
actual "print()"-functions, etc.).


Here is my second attempt. This version introduces what I might 
optimistically call a very simple markup language in the code.
Printing of source can selectively be turned on and off by inserting 
lines beginning with "## Ignore" or "## Show" into the source file.



--
## Ignore
from __future__ import with_statement
import sys

def print_selected_source():
is_printing = True
with open(sys.argv[0]) as file:
for line in file:
if line.startswith("## Ignore"):
is_printing = False
elif line.startswith("## Show"):
is_printing = True
elif is_printing:
print line,


## Show
a = 1
b = 2
c = 3
result = a + b

## Ignore
print_selected_source()
print("result =\t", result)
print("result + c =\t", result + c)
--

Is this getting closer?

/ johan

How about simply importing the file with the calculations?  Printing the 
imported file is quite straightforward, and except for maybe skipping 
the import lines that may be at the top (eg. import math), the rest of 
the file could be meaningful for the end user.



That has the advantage that it's easy to have multiple "notepads", but 
only one set of code that runs them.


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


Re: In disGuiodoise?

2010-04-06 Thread Andreas Waldenburger
On Mon, 05 Apr 2010 22:03:00 +0200 News123  wrote:

> Andreas Waldenburger wrote:
> > On Mon, 05 Apr 2010 13:48:15 +0200 News123  wrote:
> > 
> >> Martin P. Hellwig wrote:
> >>> On 04/05/10 00:05, r wrote:
> >>> 
>  However i have also considered that maybe *all* the "well knowns"
>  are in fact the many colorful personalities of Guido.
> 
> >>> 
> >>>
> >>> De vraag is dan natuurlijk of al zijn persoonlijkheden nog steeds
> >>> nederlands machtig zijn.
> >>>
> >> Good sock puppets would at least pretend to understand no Dutch
> >> even if they would.
> >>
> > Is that in reference to the contents of Martins comment, in whatever
> > language that was? Because I, for one, don't understand a word of
> > it.
> >
> 
> Yes indeed:
> 
> Freely (and as far as I understand) translated:
> "Question is of course whether all his personalities would still be
> knowledgable in dutch"

Sigh, again text-based communication proves insufficient.

I guess I should have included a ;) in my post. Sorry. Thanks for your
time though. :)

/W

-- 
INVALID? DE!

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


Re: python as pen and paper substitute

2010-04-06 Thread Chris Colbert
you may have a look at sage:

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


Re: Incorrect scope of list comprehension variables

2010-04-06 Thread Gregory Ewing

Lie Ryan wrote:

in python there is only a flat
local namespace and the names resolver becomes a thousand times simpler


No, it doesn't. The compiler already has to deal with multiple
scopes for nested functions. There may be some simplification,
but not a lot.

The main reason is linguistic. Having nested blocks create new
scopes does not fit well with lack of variable declarations.

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


Re: Incorrect scope of list comprehension variables

2010-04-06 Thread Rolando Espinoza La Fuente
On Sun, Apr 4, 2010 at 5:20 PM, Paul Rubin  wrote:
[...]
>
>    d[r] = list(r for r in [4,5,6])
>

This have a slightly performance difference. I think mainly the
generator's next() call.

In [1]: %timeit list(r for r in range(1))
100 loops, best of 3: 2.78 ms per loop

In [2]: %timeit [r for r in range(1)]
100 loops, best of 3: 1.93 ms per loop

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


s-expression parser in python

2010-04-06 Thread James Stroud

Hello All,

I want to use an s-expression based configuration file format for a 
python program I'm writing. Does anyone have a favorite parser?


I'm currently using sexpy.parse() (http://pypi.python.org/pypi/sexpy) 
which works very well but I don't know how secure it is. Does anyone 
have experience with sexpy or another parser? I'm mostly concerned with 
 safety when the parser evaluates scalar data types. Sexpy is not well 
documented in this regard.


Also, I don't want a lisp/scheme interpreter, just the parser.

For example,

   """
   (and
 (or (> uid 1000)
 (!= gid 20)
 )
 (> quota 5.0e+03)
   )
   """

Should be parsed to

   ["and",
 ["or", ["=", "uid", 1405],
["!=", "gid", 20]],
 [">", "quota", 5000.0]
   ]

Note proper parsing of ints, floats, etc.

I've already wrote the evaluator for the parsed lists, so I'm not 
interested in alternatives to S-expressions. Also, I'm really not 
interested in json, yaml, etc., for the configuration format because I'm 
quite fond of the brevity and clarity of S-expressions (your opinion may 
vary).


Thanks in advance for any insight.

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


Re: python as pen and paper substitute

2010-04-06 Thread James Stroud

Manuel Graune wrote:

Hello everyone,

I am looking for ways to use a python file as a substitute for simple
pen and paper calculations. At the moment I mainly use a combination
of triple-quoted strings, exec and print (Yes, I know it's not exactly
elegant). To clarify, I just start an editor, write a file that
might look something like this:


I wrote a module called pylave, which is meant to be a 
parser-evaluator-solver for scratch paper-like calculations. It has 
strict operator precedence, knows a variety of common operations, and 
respects parenthetic grouping. It is designed to evaluate ini files, 
which can have syntax highlighting depending on your text editor. 
Pyparsing is required.



Here is a pylave example:


% cat test.ini
factor = 2
   = minor_axis / 2
www= 69.69 + 
height = 10
apex   = epicenter // height
major_axis = epicenter + 2*radius / sin big
minor_axis = epicenter + (total / 14) % (length-1)
epicenter  = 44
radius = ((14 + length)/2 + height)*breadth
length = width + 5
width  = 2**2 - factor
total  = big*(radius + 14)
big= abs (sin (5e+8))
breadth= 2*length + height
overlap= abs (1 + 1)
nexus  = sin (5e-8)
plexus = sin (5e8)


% ./pylave.py test.ini
breadth : 24
www : 93.8350093235
nexus : 5e-08
big : 0.284704073238
major_axis : 3547.35712408
height : 10
radius : 492.0
plexus : -0.284704073238
total : 144.060261058
epicenter : 44
apex : 4
overlap : 2
 : 24.1450093235
width : 2
length : 7
factor : 2
minor_axis : 48.290018647


It is not perfect but if it will help, I'll cheeseshop it.

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


Re: s-expression parser in python

2010-04-06 Thread Patrick Maupin
On Apr 6, 7:02 pm, James Stroud 
wrote:

I have a parser/emitter I wrote about 4 years ago for EDIF.  Take a
look at the wikipedia article http://en.wikipedia.org/wiki/EDIF

If that is close to you want, I can send it to you.  The whole parser/
emitter/XML round-tripper etc. is only 500 lines, which includes a
bunch of comments.  Tiny.

I've never made a project out of it, but it worked fine for me and a
friend.  (I have a testbench, but unfortunately the test data is
proprietary.)

But, I have to take this opportunity to put in a plug for a file
format I created for configuration files.  It's secure (no eval
statements), it's much lighter weight than YAML, and it looks better
too:

http://code.google.com/p/rson/wiki/Manual

Please let me know if you'd like the edif code.

Best regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python as pen and paper substitute

2010-04-06 Thread Ethan Furman

Manuel Graune wrote:

Manuel Graune  writes:

The use-case is acually fairly simple. The point is to use a python
source-file as subsitute for scrap-paper (with the opportunity to
edit what is already written and without illegible handwriting).
The output should  1) show manually selected python code and comments
(whatever I think is important), 2) show selected results (final and
intermediate) and 3) *not* show python code that for someone only
interested in the calculation and the results (and probably not
knowing python) would just be "noise" (e. g. "import"-statements,
actual "print()"-functions, etc.). 


How about a decorator that turns your function into an object with the 
results?  Your code would then look like this:


8<--
#! /usr/bin/python3
from sp import ScratchPad
from math import pi as PI

@ScratchPad
def code1():
d1= 3.0
A1= d1**2 * PI / 4.0

print("Area of Circle 1:\t", code1.A1)

@ScratchPad
def code2():
d2= 5.0
A2= d2**2 * PI / 4.0

print("Area of Circle 2:\t", code2.A2)

Sum_Of_Areas= code1.A1 + code2.A2
print("Sum of areas:\t", Sum_Of_Areas)

8<--

and the printout like so:

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> import sp_test

d1= 3.0
A1= d1**2 * PI / 4.0

Area of Circle 1:7.06858347058

d2= 5.0
A2= d2**2 * PI / 4.0

Area of Circle 2:19.6349540849
Sum of areas:26.703537

Here's the code for the decorator:

8<--
import inspect

class PropertyObj():
"""lookup using . notation"""

def ScratchPad(func):
source = inspect.getsourcelines(func)[0][2:]
lead_space = 0
for char in source[0]:
if char == ' ':
lead_space += 1
else:
break
source = ''.join([line[lead_space:] for line in source])
print('\n' + source)
intermed_result = {}
final_result = PropertyObj()
exec(source, func.__globals__, intermed_result)
for key, value in intermed_result.items():
setattr(final_result, key, value)
return final_result
8<--

Hope this helps!

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


Re: s-expression parser in python

2010-04-06 Thread Paul McGuire
On Apr 6, 7:02 pm, James Stroud 
wrote:
> Hello All,
>
> I want to use an s-expression based configuration file format for a
> python program I'm writing. Does anyone have a favorite parser?
>

The pyparsing wiki includes this parser on its Examples page:
http://pyparsing.wikispaces.com/file/view/sexpParser.py.  This parser
is also described in more detail in the pyparsing e-book from
O'Reilly.

This parser is based on the BNF defined here:http://
people.csail.mit.edu/rivest/Sexp.txt.  I should think Ron Rivest would
be the final authority on S-expression syntax, but this BNF omits '!',
'<', and '>' as valid punctuation characters, and does not support
free-standing floats and ints as tokens.

Still, you can extend the pyparsing parser (such is the goal of
pyparsing, to make these kinds of extensions easy, as the source
material or BNF or requirements change out from underneath you) by
inserting these changes:

real = Regex(r"[+-]?\d+\.\d*([eE][+-]?\d+)?").setParseAction(lambda
tokens: float(tokens[0]))
token = Word(alphanums + "-./_:*+=!<>")
simpleString = real | decimal | raw | token | base64_ | hexadecimal |
qString

And voila!  Your test string parses as:

[['and',
  ['or', ['>', 'uid', 1000], ['!=', 'gid', 20]],
  ['>', 'quota', 5000.0]]]

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


  1   2   >