Re: Need help with Python scoping rules

2009-08-26 Thread Ulrich Eckhardt
Jean-Michel Pichavant wrote:
> class Color:
> def __init__(self, r, g,b):
>   pass
> BLACK = Color(0,0,0)
> 
> It make sens from a design point of view to put BLACK in the Color
> namespace. But I don't think it's possible with python.

class Color:
...

setattrib(Color, "BLACK", Color(0,0,0))

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]

2009-08-26 Thread Diez B. Roggisch

Evan Driscoll schrieb:

On Aug 25, 3:47 pm, Evan Driscoll  wrote:

So here is my simplified version that only works for globals:


So I think this works if (1) you only use changed_value in the same
module as it's defined in (otherwise it picks up the globals from the
module it's defined in, which is almost certainly not what you want),
and (2) the value you want to change is just a simple variable and not
either something like "os.path" or a builtin.

I have worked on this a bit more and have something that addresses
these issues in at least the cases I've tested. I'm not going to post
the code here, but it is up at
  http://pages.cs.wisc.edu/~driscoll/python/utils.py
and there are a few unit tests at
  http://pages.cs.wisc.edu/~driscoll/python/utils_test.py

I solved issue (1) by reintroducing the use of inspect to walk back up
the stack a couple frames, but I pulled out the f_globals member
instead of f_locals.

Issue (2a) I fixed by splitting the variable name at periods and
walking through successive dictionaries with each component. Issue
(2b) I fixed by looking for a '__builtins__' entry if the name I'm
looking up doesn't exist.

Right now it's sort of hackish... it probably doesn't respond
particularly well if things go unexpectedly (e.g. a bad variable name
is given) and I should probably verify that the value is unchanged
during the with statement and throw an exception otherwise, but it
probably works well enough for my purposes for now.

Comments are appreciated... a couple of the things in there it seems
like there could very well be reimplementations of things that are
already done.



I'd still won't use it :) instead, something like this might be 
something I'd use, if I need a local "rebound". Or, again, just use a 
different *name* alltogether.


foo = "bar"


@apply
def f(foo="baz"):
...



Other than that, for your original use-case, I have a context-manager I 
call "safe modifier" that


 - takes an object, key and value
 - stores the old value of the key on the object
 - sets the new value
 - on exit, restores the old value

This is for e.g. temporary config-changes in tests.

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


Re: PyObject_CallFunction and writable memory

2009-08-26 Thread Diez B. Roggisch

Christopher Nebergall schrieb:

I'm working a patch to a hex editor (frhed) written in c++ so it can
load python scripts. Internally the c++ code has a unsigned char * of
possibly serveral hundred megs which I want to send into the python
code to modify.What is the best way to send the unsigned char * as
writable memory into the python code, so I don't have to duplicate the
memory in order to return a modified copy?   I'm currently using
"PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to
send an immutable string but I haven't seen what I need to set in the
format string which makes the data writable to python.The solution
can be for either python 2.6 or 3.1.


Take a look at the buffer-protocol.

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


Re: PyObject_CallFunction and writable memory

2009-08-26 Thread Benjamin Peterson
Christopher Nebergall  gmail.com> writes:

> 
> I'm currently using
> "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to
> send an immutable string but I haven't seen what I need to set in the
> format string which makes the data writable to python.The solution
> can be for either python 2.6 or 3.1.

Have a look at the buffer interface: 
http://docs.python.org/3.1/c-api/buffer.html




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


Re: Python, qt, and lgpl

2009-08-26 Thread Diez B. Roggisch

sturlamolden schrieb:

On 25 Aug, 21:45, Terry Reedy  wrote:


Will be good news if realized.


Good news for everyone except Riverbank.



And only if LGPL is something you can live with. Some projects require 
more liberal licenses.



Or is there a commercial license available, too?



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


Re: conditional for-statement

2009-08-26 Thread seb
On Aug 25, 11:57 pm, Piet van Oostrum  wrote:
> You can also say:
> [x+y for x in range(3) for y in range(4) if x < y]
> If you want to write this as a loop you have to put the for's on
> separate lines separated by colons, so why not the if also? Or would you
> also like to have the for's on one line?

indeed, we could have the for's on one line too. In fact, if you have
a double loop without any body that is specific to the outer loop, you
can merge the two lines. Similarly, if you have a loop with a if (ie
filter) without any body having to be executed outside the if, having
them on the same line is also clearer.

|  for x in range(3):
|  for x in range(3) for y in range(4):
|for y in range(4):   could be written as
|body
|  body
and
|  for x in range(3):
|  for x in range(3) if cond(x):
|if cond(x):  could be written as
|body
|  body

Such loops are in fact mentally just one loop over the cartesian
product (product set) of the two iterators or over the filter set of
the iterator respectively in these examples.

Moreover, for 'body' longer than a couple of lines, it is quite useful
to see immediately that there is no additional code that could be only
specific to the outher loop
ie, when writing all in one line, we can be sure that we do not have
this situation
|  for x in range(3):
|for y in range(4):
|  long body
|  ...
|  long body
|body related to outer loop

The naturalness of iteration in the various comprehensions and the
generator expressions can be smoothly extended to the standard code
iteration.

BTW, I noticed this inconsistency when, coming back to python after a
couple of weeks of no python programming, I started coding loops like

for obj in list_obj if obj.Size > 100:
  print(obj)

and got an error message about syntax.

> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: [email protected] Hide quoted text -
>
> - Show quoted text -

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


Re: break unichr instead of fix ord?

2009-08-26 Thread Vlastimil Brom
2009/8/25  :
> In Python 2.5 on Windows I could do [*1]:
>
>  # Create a unicode character outside of the BMP.
>  >>> a = u'\U00010040'
>
>  # On Windows it is represented as a surogate pair.
>  >>> len(a)
>  2
>  >>> a[0],a[1]
>  (u'\ud800', u'\udc40')
>
>  # Create the same character with the unichr() function.
>  >>> a = unichr (65600)
>  >>> a[0],a[1]
>  (u'\ud800', u'\udc40')
>
>  # Although the unichr() function works fine, its
>  # inverse, ord(), doesn't.
>  >>> ord (a)
>  TypeError: ord() expected a character, but string of length 2 found
>
> On Python 2.6, unichr() was "fixed" (using the word
> loosely) so that it too now fails with characters outside
> the BMP.
>
>  >>> a = unichr (65600)
>  ValueError: unichr() arg not in range(0x1) (narrow Python build)
>
> Why was this done rather than changing ord() to accept a
> surrogate pair?
>
> Does not this effectively make unichr() and ord() useless
> on Windows for all but a subset of unicode characters?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hi,
I'm not sure about the exact reasons for this behaviour on narrow
builds either (maybe the consistency of the input/ output data to
exactly one character?).

However, if I need these functions for higher unicode planes, the
following rather hackish replacements seem to work. I presume, there
might be smarter ways of dealing with this, but anyway...

hth,
   vbr

 not (systematically) tested #

import sys

def wide_ord(char):
try:
return ord(char)
except TypeError:
if len(char) == 2 and 0xD800 <= ord(char[0]) <= 0xDBFF and
0xDC00 <= ord(char[1]) <= 0xDFFF:
return (ord(char[0]) - 0xD800) * 0x400 + (ord(char[1]) -
0xDC00) + 0x1
else:
raise TypeError("invalid character input")


def wide_unichr(i):
if i <= sys.maxunicode:
return unichr(i)
else:
return ("\U"+str(hex(i))[2:].zfill(8)).decode("unicode-escape")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for professsional Windows GUI apps?

2009-08-26 Thread Simon Brunning
2009/8/26 geekworking :
> If you are planning a database driven app, you should first settle on
> a DB server. Any real enterprise DB system will put all of the
> business logic in the database server. The choice of a front end
> should be secondary.

The trend for some years now has been to get behavior out of the
database and into the application, where it belongs. True, we tend to
keep the presentation tier separate too, but we really don't "put all
of the business logic in the database server".

Going back to the OP's question, it would be worth taking a look at
what the resolver boys are up to: .

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


Getting the current PyCFunction while in a python function

2009-08-26 Thread Prémon Nom
Hi

I would like to get the PyCFunction object which corresponds to the current 
function which is executed. I call PyFrameObject* frame = PyEval_GetFrame()

I try to parse frame->f_valuestack, but I don't know how to get the index of 
the function in the stack or event the size of the stack to be able to parse it 
(from end to begin and to stop on the first PyCFunctionObject).
There is a member call stack size (frame->f_valuestack->f_code->co_stacksize) 
but it doesn't correspond to the frame->f_valuestack size :-(
In fact i know that when i call "print(myFunctionPrintNumber(123))
There is PyCfunctionObject corresponding to myFunctionPrintNumber but i don't 
know how to acces it :/ because i don't know how to get/compute 
frame->f_valuestack size or to get/compute directly
 the index where the current executed function is.

Please help me!!!

Regards



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


Re: Python on the Web

2009-08-26 Thread Bruno Desthuilliers

Phil a écrit :

I've seen lots of web sites explaining everything, but for whatever
reason I seem to not be picking something up.
I am a graphical person, which is probably the reason I haven't found
my answer.
May somebody please confirm if my diagram accurately represents the
stack, generally speaking.

http://i26.tinypic.com/1fe82x.png


Seems correct.


Even if that is the case, I'm having a hard time understanding the
differences. I guess wsgiref has absolutely nothing to do with FCGI/
SCGI/CGI and simply receives and responds to HTTP requests following
the WSGI specification?


Yeps.


Does it just spawn a new thread for each
request?


Not AFAICT.



The way I am understanding the 'Production' side of that picture is
that the web server (eg. lighttpd) creates a single FCGI process. The
FCGI process is actually the entry point of the Framework/Application
which sets up Flup's WSGIServer, being the interface between FCGI and
the Framework/Application? What I mean is, it is just the code that
the web server loads to start with, example...
from flup.server.fcgi import WSGIServer
from app import application
WSGIServer(application).run()
... Then for each HTTP request, Flup's WSGIServer creates a new thread
to handle the request?


I didn't bother reading Flup's source code, but I suppose this might be 
the case.



As I've read elsewhere, "These days, FastCGI is never used directly.
Just like mod_python it is only used for the deployment of WSGI
applications." As far as I understand, the main (or only?) reasoning
for this is because WSGI makes Python applications easier to deploy
without having to worry about whether using FCGI/SCGI/CGI.


Nor about which web server you use (Apache, lighthttpd, whatever).


What would be involved to run Python on the web using FCGI without
WSGI? I can feel the flames already. This isn't the only reason I want
to know, but one reason is that I want to use Python 3.1 and as I
understand, this will have to wait for the WSGI 2.0 specification to
ensure time isn't wasted.


My humble opinion (based on years of experience in both Python and web 
programming) is that you're taking the wrong approach. I can only second 
 Robert Kern here: use an existing, well maintained wsgi-compliant 
framework like Django, Pylons etc, and wait for the framework to be 
ported to python 3.x. Any other solution will almost certainly end up 
needing a complete rewrite anytime soon.



I apologize if the questions are ridiculous. I've just recently got
into web programming and it seems that in order for me to use Python,
I need a deep understanding of web servers, HTTP, FCGI, etc.


Programming for the web - whatever the language & techno - indeed 
require a deep (or at least correct) understanding of HTTP and web 
servers, yes. Even with the abstraction layers provided by frameworks, 
you still need to understand how the whole damn thing works, what's an 
HTTP resquest & response and quite a few other things as well.


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


Move dictionary from instance to class level

2009-08-26 Thread Frank Millman
Hi all

I have a class that uses a dictionary to map message numbers to methods.

Here is a simple example -

class MyClass(object):
def __init__(self):
self.method_dict = {}
self.method_dict[0] = self.method_0
self.method_dict[1] = self.method_1

def on_message_received(self, msg):
self.method_dict[msg]()

def method_0(self):
print 'in method_0'

def method_1(self):
print 'in method_1'

I have quite a few methods, so the dictionary is growing - up to 28 methods 
so far. To avoid
having to recreate the dictionary every time I create an instance of the 
class, I tried to move it
up to the class level. Unfortunately it does not work. This is what I 
tried -

class MyClass(object):
method_dict = {}
method_dict[0] = method_0  # this gives an error
method_dict[1] = method_1

def on_message_received(self, msg):
self.method_dict[msg]()

def method_0(self):
print 'in method_0'

def method_1(self):
print 'in method_1'

As written above, I get the following error -
NameError: name 'method_0' is not defined

If I try self.method_0, I get 'self' is not defined.

If I try __class__.method_0, I get '__class__' is not defined.

If I try MyClass.method_0, I get 'MyClass' is not defined.

Is there any variation on this theme that will work?

#

Ok, I found a variation that seems to work.

Is this the preferred way, or is there a better alternative?

class MyClass(object):

def on_message_received(self, msg):
#self.method_dict[msg]()  # had to change this to get it to work
self.method_dict[msg](self)

def method_0(self):
print 'in method_0'

def method_1(self):
print 'in method_1'

MyClass.method_dict = {}
MyClass.method_dict[0] = MyClass.method_0
MyClass.method_dict[1] = MyClass.method_1

As you can see, I had to add 'self' to the method arguments when calling the 
method.

Any comments?

Thanks

Frank Millman


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


Re: Python for professsional Windows GUI apps?

2009-08-26 Thread erikj
Hi,

You could have a look at Camelot, to see if it fits
your needs : http://www.conceptive.be/projects/camelot/

it was developed with cross platform business apps in
mind.  when developing Camelot, we tried to build it using
wxWidgets first (because of the licensing at that time),
but it turned out that developing with QT proved to be
much more straightforward.  QT is documented very well
and you seldom encounter 'strange' issues that cost hours
of time to pinpoint and fix.

the datagrid was developed to be able to handle millions
of database records without glitches and is flexible thanks
to QT's model-view-delegate framework.

we do print barcodes with this app (even directly to
zebra printers)

if you have questions regarding Camelot, please feel free
to post on our mailing list : http://groups.google.com/group/project-camelot

Regards,

Erik

On Aug 24, 2:08 pm, Gilles Ganault  wrote:
> Hello
>
>         I was wondering if some people in this ng use Python and some GUI
> toolkit (PyWin32, wxWidgets, QT, etc.) to build professional
> applications, and if yes, what it's like, the pros and cons, etc.
>
> I'm especially concerned about the lack of controls, the lack of
> updates (lots of controls in wxWidgets are 1.0 deadware), and problems
> linked to how to update users' PC remotely when I build a new version
> using eg. Py2exe.
>
> I need controls for business apps like access to databases, good data
> grid, printing reports (with or without barcodes), etc.
>
> Thank you.

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


Re: print() and unicode strings (python 3.1)

2009-08-26 Thread Piet van Oostrum
> 7stud  (7) wrote:

>7> Thanks for the response.  My OS is mac osx 10.4.11.  I'm not really
>7> sure how to check my locale settings.  Here is some stuff I tried:

>7> $ echo $LANG

>7> $ echo $LC_ALL

>7> $ echo $LC_CTYPE

>7> $ locale
>7> LANG=
>7> LC_COLLATE="C"
>7> LC_CTYPE="C"
>7> LC_MESSAGES="C"
>7> LC_MONETARY="C"
>7> LC_NUMERIC="C"
>7> LC_TIME="C"
>7> LC_ALL="C"

IIRC, Mac OS X 10.4 does not set LANG or LC_* automatically. In 10.5
Terminal has an option in the preferences to set LANG according to the
encoding chosen (and presumably the language of the user).

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Move dictionary from instance to class level

2009-08-26 Thread Chris Rebert
On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote:
> Hi all
>
> I have a class that uses a dictionary to map message numbers to methods.
>
> Here is a simple example -
>
>    class MyClass(object):
>        def __init__(self):
>            self.method_dict = {}
>            self.method_dict[0] = self.method_0
>            self.method_dict[1] = self.method_1
>
>        def on_message_received(self, msg):
>            self.method_dict[msg]()
>
>        def method_0(self):
>            print 'in method_0'
>
>        def method_1(self):
>            print 'in method_1'
>
> I have quite a few methods, so the dictionary is growing - up to 28 methods
> so far. To avoid
> having to recreate the dictionary every time I create an instance of the
> class, I tried to move it
> up to the class level. Unfortunately it does not work. This is what I
> tried -
>
>    class MyClass(object):
>        method_dict = {}
>        method_dict[0] = method_0  # this gives an error
>        method_dict[1] = method_1
>
>        def on_message_received(self, msg):
>            self.method_dict[msg]()
>
>        def method_0(self):
>            print 'in method_0'
>
>        def method_1(self):
>            print 'in method_1'
>
> As written above, I get the following error -
>    NameError: name 'method_0' is not defined
>
> If I try self.method_0, I get 'self' is not defined.

Right, because you're in the *class* body; there's no "current
instance" to be "self"; in fact, there's not even any class for there
to be instances of yet.

> If I try __class__.method_0, I get '__class__' is not defined.

Right, because the class isn't created until its body has finished executing

> If I try MyClass.method_0, I get 'MyClass' is not defined.

See previous note. The class name can't be bound to anything until the
class itself has been created.

> Is there any variation on this theme that will work?
>
> #
>
> Ok, I found a variation that seems to work.
>
> Is this the preferred way, or is there a better alternative?

A

class MyClass(object):
def on_message_received(self, msg):
self.method_dict[msg](self)

def method_0(self):
print 'in method_0'

def method_1(self):
print 'in method_1'
method_dict

method_dict = {0: method_0, 1: method_1}
#note this comes *after* the methods in question have been defined

Is there some reason you aren't using a list instead of a dict?
e.g. method_dict = [method_0, method_1, method_2, etc]

For that matter, why are you associating methods with integers in the
first place?

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Q: multiprocessing.Queue size limitations or bug...

2009-08-26 Thread Michael Riedel
Sorry for being not more specific but I'm not absolutely certain whether
I encountered a bug or did anything wrong:

The (stupid) code below results in a stall forever or not at 'p0.join()'
depending on the value of TROUBLE_MAKER.

Any help, thoughts, comments?

Thank you for your time.

Michael

# --

from multiprocessing import Process, Queue

# bit vector size
BVS=8

#
TROUBLE_MAKER=12  # for greater values p0.join() is never satisfied...

def evaluate(q, id, start=0, stop=2**BVS):

cmin = {0: []}

for mask0 in range(start, stop):
for mask1 in range(0, 2**BVS):
for mask2 in range(mask1, TROUBLE_MAKER):
cmin[0].append((mask0, mask1, mask2))

print 'process %d finished (dict layout: %d/%d)...' % (id,
len(cmin), len(cmin[0]))
q.put(cmin.copy())
q.close()


if __name__ == '__main__':

q0 = Queue()
q1 = Queue()
q2 = Queue()
q3 = Queue()

part = 2**BVS/4
p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part),
name='worker_0')
p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part),
name='worker_1')
p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part),
name='worker_2')
p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part),
name='worker_3')
p0.start()
print 'process 0 started...'
p1.start()
print 'process 1 started...'
p2.start()
print 'process 2 started...'
p3.start()
print 'process 3 started...'
# main process stalls at p0.join() for bigger TROUBLE_MAKER
p0.join()
p1.join()
p2.join()
p3.join()
res0 = q0.get()
res1 = q1.get()
res2 = q2.get()
res3 = q3.get()
print 'results fetched...'

# --

-- 

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


Re: Move dictionary from instance to class level

2009-08-26 Thread Frank Millman
On Aug 26, 10:54 am, Chris Rebert  wrote:
> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote:
>
> A
>
> class MyClass(object):
> def on_message_received(self, msg):
> self.method_dict[msg](self)
>
> def method_0(self):
> print 'in method_0'
>
> def method_1(self):
> print 'in method_1'
> method_dict
>
> method_dict = {0: method_0, 1: method_1}
> #note this comes *after* the methods in question have been defined
>

Thanks, Chris. This is much better.

> Is there some reason you aren't using a list instead of a dict?
> e.g. method_dict = [method_0, method_1, method_2, etc]
>
> For that matter, why are you associating methods with integers in the
> first place?
>

I actually use constants to define my messages, like this -

(MESSAGE_ONE
,MESSAGE_TWO
,MESSAGE_THREE
) = xrange(3)

I can then refer to the messages by their description, but internally it 
uses integers.

Frank


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


Re: Move dictionary from instance to class level

2009-08-26 Thread Frank Millman
On Aug 26, 10:54 am, Chris Rebert  wrote:
> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote:
>
> A
>
> class MyClass(object):
> def on_message_received(self, msg):
> self.method_dict[msg](self)
>
> def method_0(self):
> print 'in method_0'
>
> def method_1(self):
> print 'in method_1'
> method_dict
>
> method_dict = {0: method_0, 1: method_1}
> #note this comes *after* the methods in question have been defined
>

Thanks, Chris. This is much better.

> Is there some reason you aren't using a list instead of a dict?
> e.g. method_dict = [method_0, method_1, method_2, etc]
>
> For that matter, why are you associating methods with integers in the
> first place?
>

I actually use constants to define my messages, like this -

(MESSAGE_ONE
,MESSAGE_TWO
,MESSAGE_THREE
) = xrange(3)

I can then refer to the messages by their description, but internally it
uses integers.

Frank



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


Re: Move dictionary from instance to class level

2009-08-26 Thread Frank Millman
On Aug 26, 10:54 am, Chris Rebert  wrote:
> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote:
>
> A
>
> class MyClass(object):
> def on_message_received(self, msg):
> self.method_dict[msg](self)
>
> def method_0(self):
> print 'in method_0'
>
> def method_1(self):
> print 'in method_1'
> method_dict
>
> method_dict = {0: method_0, 1: method_1}
> #note this comes *after* the methods in question have been defined
>

Thanks, Chris. This is much better.

> Is there some reason you aren't using a list instead of a dict?
> e.g. method_dict = [method_0, method_1, method_2, etc]
>
> For that matter, why are you associating methods with integers in the
> first place?
>

I actually use constants to define my messages, like this -

(MESSAGE_ONE
,MESSAGE_TWO
,MESSAGE_THREE
) = xrange(3)

I can then refer to the messages by their description, but internally it
uses integers.

Frank



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


Re: Help with arrays

2009-08-26 Thread Stephen Fairchild
Dave Angel wrote:

> With this change the best solution changes from a random shuffle to a
> binary search.

Which is not what the OP asked for. Anyway, I think whatever solution is
chosen it's probably best written as a generator. The new pushback syntax
may prove useful.
-- 
Stephen Fairchild
-- 
http://mail.python.org/mailman/listinfo/python-list


all possible matchings of elements of two lists

2009-08-26 Thread Sandy
Hi all,
I basically want all possible matchings of elements from two lists,
Ex: [1,2] [a,b,c]

Required:
   [ [(1,a),(2,b)]
 [(1,b),(2,c)]
 [(1,c),(2,b)]
 [(1,b),(2,a)]
 [(1,c),(2,a)]
 [(1,a),(2,c)]
   ]

My thought is to get all possible permutations of two lists given and
select any combination and use zip to get the tuples. Repeat this for
all possible combinations.

Any other ideas?
Sandy


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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In  John Posner 
 writes:
>Stephen Hansen said:
>> This sounds like a fundamental confusion -- a namespace is not 
>> equivalent to a scope, really, I think.
>> ...


Hmm.  I can't find Stephen Hansen's original post anywhere.  Where
did you come across it?

Is there an *official* write-up where these issues are discussed?
To put it differently, where exactly in the Python docs would
someone learning Python go to answer my original query?

TIA!

kynn

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


Re: Python, qt, and lgpl

2009-08-26 Thread Carl Banks
On Aug 25, 5:04 pm, sturlamolden  wrote:
> On 25 Aug, 21:45, Terry Reedy  wrote:
>
> > Will be good news if realized.
>
> Good news for everyone except Riverbank.

Oh well, Riverbank could have played ball but they didn't, so I guess
I don't care if it's bad news for them.


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


Re: Python Processor

2009-08-26 Thread manish
Hi,

I am also wondering about how to implement a soft core reconfigurable
processor in a FPGA
which would directly execute the compiled python bytecode.

I am trying to understand the bytecode format but apart from
http://docs.python.org/library/dis.html
there is hardly any documentation on the python bytecodes.

Before going through the one of the existing VM implementations, i want to
know if there is there any informaition
available which elaborates on the structure of the bytecodes. Like details
regarding co_names, co_cellvars,
co_freevars, the concept of frames, global, local, objects, functions etc
with respect to the bytecode.


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


ubuntu dist-packages

2009-08-26 Thread Robin Becker
I was surprised a couple of days ago when trying to assist a colleage with his 
python setup on a ubuntu 9.04 system.


We built our c-extensions and manually copied them into place, but site-packages 
wasn't there. It seems that ubuntu now wants stuff to go into 
lib/python2.6/dist-packages.


What is the relation between dist-packages/site-packages if any? Is this just a 
name change or is there some other problem being addressed?


For developers is it best just to create one's own private installations from 
the original tarballs?

--
Robin Becker

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


Re: all possible matchings of elements of two lists

2009-08-26 Thread dksr
Ok this is how I do it:
l1 = [1,2]
l2= ['a','b','c']
res = []
l2 = permute(l2)
for i in l2:
lis = [l1,l2]
res.append(zip(*lis))
# or use map depending on what u want
res.append(map(None,*lis))

print res

On Aug 26, 11:05 am, Sandy  wrote:
> Hi all,
> I basically want all possible matchings of elements from two lists,
> Ex: [1,2] [a,b,c]
>
> Required:
>    [ [(1,a),(2,b)]
>      [(1,b),(2,c)]
>      [(1,c),(2,b)]
>      [(1,b),(2,a)]
>      [(1,c),(2,a)]
>      [(1,a),(2,c)]
>    ]
>
> My thought is to get all possible permutations of two lists given and
> select any combination and use zip to get the tuples. Repeat this for
> all possible combinations.
>
> Any other ideas?
> Sandy

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


TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile

2009-08-26 Thread Ryniek90



[snip]

Here's my script code:
*http://paste.ubuntu.com/259310/

*Shouldn't that bug be patched already  :-?

Are you giving it the contents of the file when it's actually expecting
the filename?



Of course the content of the file:

[snip]

See? *backup_obj.add(read_obj.read())*
In previous pasted Traceback you can see 
*backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the 
*read_obj.read()* .



The documentation lists the methods "add" and "addfile". Pick one and
provide the values it's expecting. For example, if you choose "add" then
provide the filename, not the contents of the file.

Do only I have this problem or Python programming under Windows is 
nightmare?


It's only a nightmare if you don't follow the documentation. :-)



Hahah right. My fault. Must remember to read documentation so many times 
until I find the solution.  Thanks, now works fine.  :-)

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


Re: ubuntu dist-packages

2009-08-26 Thread Diez B. Roggisch
Robin Becker wrote:

> I was surprised a couple of days ago when trying to assist a colleage with
> his python setup on a ubuntu 9.04 system.
> 
> We built our c-extensions and manually copied them into place, but
> site-packages wasn't there. It seems that ubuntu now wants stuff to go
> into lib/python2.6/dist-packages.
> 
> What is the relation between dist-packages/site-packages if any? Is this
> just a name change or is there some other problem being addressed?
> 
> For developers is it best just to create one's own private installations
> from the original tarballs?

I don't know much about the atrocities distributions commit to
python-installations (ripping out distutils "because it's a developer-only
thing", trying to save a few bytes here and there by unifying
install-locations between interpreter versions and whatnot), but I think
the main problem is that you don't use distutils - or setuptools (that gets
often a bad rap even if for most cases it works flawless)

If you'd use that to build & install your extension, it would figure out
where to place the resulting package (or egg) by itself. 

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


Re: all possible matchings of elements of two lists

2009-08-26 Thread Mark Dickinson
On Aug 26, 11:05 am, Sandy  wrote:
> Hi all,
> I basically want all possible matchings of elements from two lists,
> Ex: [1,2] [a,b,c]
>
> Required:
>    [ [(1,a),(2,b)]
>      [(1,b),(2,c)]
>      [(1,c),(2,b)]
>      [(1,b),(2,a)]
>      [(1,c),(2,a)]
>      [(1,a),(2,c)]
>    ]

If you're using Python 2.6 (or 3.1), you might find the itertools
module helpful:

Python 2.6.2 (r262:71600, Aug 26 2009, 09:40:44)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> for p in itertools.permutations('abc', 2): print zip([1,2], p)
...
[(1, 'a'), (2, 'b')]
[(1, 'a'), (2, 'c')]
[(1, 'b'), (2, 'a')]
[(1, 'b'), (2, 'c')]
[(1, 'c'), (2, 'a')]
[(1, 'c'), (2, 'b')]



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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In <[email protected]> "Diez B. Roggisch"  
writes:

>Classes are not scopes.

This looks to me like a major wart, on two counts.

First, one of the goals of OO is encapsulation, not only at the
level of instances, but also at the level of classes.  Your comment
suggests that Python does not fully support class-level encapsulation.

Second, my example shows that Python puts some peculiar restrictions
on recursion.  Recursion!  One of the central concepts in the theory
of functions!  This is shown most clearly by the following elaboration
of my original example:

class Demo(object):
def fact_rec(n):
if n < 2:
return 1
else:
return n * fact_rec(n - 1)

def fact_iter(n):
ret = 1
for i in range(1, n + 1):
ret *= i
return ret

classvar1 = fact_iter(5)
classvar2 = fact_rec(5)

This code won't compile as shown, but it does compile if the last
line (the call to the recursive fact_rec) is commented out.  There
is no justification for discriminating against recursive functions
in this context.  Recursive functions should be OK wherever functions
are OK.  I can't think of any other language that allows recursion
but not anywhere.

Is there any good reason (from the point of view of Python's overall
design) for not fixing this?

kynn

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


Re: multiprocessing managers and socket connection.

2009-08-26 Thread Chris
On Aug 25, 9:11 pm, Terry  wrote:
> On Aug 25, 10:14 pm, Chris  wrote:
>
>
>
> > I've been using multiprocessing managers and I really like the
> > functionality.
>
> > I have a question about reconnecting to a manager. I have a situation
> > where I start on one machine (A) a manager that is listening and then
> > on another machine (B) connects to that manager and uses its proxy
> > object to call functions on the manager's computer; this all works as
> > expected. But, if the manager from A shuts down, B's application won't
> > notice because in the MP code it ignores socket error
> > errno.ECONNREFUSED. If A becomes available again or is restarted, B
> > doesn't automatically reconnect either and continue its operation.
> > It's function is basically stopped.
>
> > Here is the code from connection.py:
> > while 1:
> >         try:
> >             s.connect(address)
> >         except socket.error, e:
> >             if e.args[0] != errno.ECONNREFUSED: # connection refused
> >                 debug('failed to connect to address %s', address)
> >                 raise
> >             time.sleep(0.01)
> >         else:
> >             break
>
> > How can I have B automatically reconnect to A and continue its work
> > once A is available again?
>
> I think you need to retry repeatedly until successfully connected.
>
> br, Terry

I'm having issue after once connected. If the server goes down during
a long-running connection. I would want to be notified so I could try
to reconnect. I'm doing more experimenting now and will try to post an
example.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with Python scoping rules

2009-08-26 Thread Ulrich Eckhardt
Ulrich Eckhardt wrote:
> Jean-Michel Pichavant wrote:
>> class Color:
>> def __init__(self, r, g,b):
>>   pass
>> BLACK = Color(0,0,0)
>> 
>> It make sens from a design point of view to put BLACK in the Color
>> namespace. But I don't think it's possible with python.
> 
> class Color:
> ...
> 
> setattrib(Color, "BLACK", Color(0,0,0))

Apart from it being "setattr" and not "setattrib", a simple

  Color.BLACK = Color(0,0,0)

should have done the job here. However, what I had in mind was this:

  class Color:
  _colors = [ ("BLACK", (0,0,0)),
  ("WHITE", (1,1,1))
]

  def __str__(self):
  # try to locate a name
  for name, rgb in Color._colors:
  if self.rgb==rgb:
  return name
  # no name found, just format as a triplet
  return "(%s, %s, %s)" % self.rgb

  # add symbolic names
  for name, rgb in Color._colors:
  setattr(Colors, name, Color(rgb))


...which I got as suggestion on my question how to model C enumeration
lookalikes.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Usefull python tutorial

2009-08-26 Thread gentlestone
Can somebody give me an advise where I can found a really good online
tutorial? All I found are useless. For example no tutorial I found
explains this piece of code:

someList = [element for element in otherList if element is not
None]

or this example:

a = a or []

There are only stupid elementary examples in the tutorials I found.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with Python scoping rules

2009-08-26 Thread Carl Banks
On Aug 26, 3:57 am, kj  wrote:
> In <[email protected]> "Diez B. Roggisch" 
>  writes:
>
> >Classes are not scopes.
>
> This looks to me like a major wart, on two counts.

Class statements *are* scopes, they are just not accessible from
scopes nested within them.


> First, one of the goals of OO is encapsulation, not only at the
> level of instances, but also at the level of classes.  Your comment
> suggests that Python does not fully support class-level encapsulation.

I can't answer this, I don't even know what you are talking about.
The OO notion of encapsulation that I'm familar means that an object
can seal off access to private data.  This has nothing to do with
class statement scoping.


> Second, my example shows that Python puts some peculiar restrictions
> on recursion.  Recursion!  One of the central concepts in the theory
> of functions!  This is shown most clearly by the following elaboration
> of my original example:
>
> class Demo(object):
>     def fact_rec(n):
>         if n < 2:
>             return 1
>         else:
>             return n * fact_rec(n - 1)
>
>     def fact_iter(n):
>         ret = 1
>         for i in range(1, n + 1):
>             ret *= i
>         return ret
>
>     classvar1 = fact_iter(5)
>     classvar2 = fact_rec(5)
>
> This code won't compile as shown, but it does compile if the last
> line (the call to the recursive fact_rec) is commented out.  There
> is no justification for discriminating against recursive functions
> in this context.  Recursive functions should be OK wherever functions
> are OK.  I can't think of any other language that allows recursion
> but not anywhere.

Inside class statements are not the place for this kind of thing.
Define functions like fact_rec outside the class statement.


> Is there any good reason (from the point of view of Python's overall
> design) for not fixing this?

I suspect that no reason, however profound, would satisfy you.
Therefore I will merely answer your question without fanfare, and you
can take it as you will.

1. One of the key aspects of Python's design is that attributes must
be accessed explicitly with dot notation.  Accessing class scopes from
nested functions would (seemingly) allow access to class attributes
without the dotted notation.  Therefore it is not allowed.

2. This is considered more important that your ability to define
recursive functions in the class statement.


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


Re: Usefull python tutorial

2009-08-26 Thread Chris Rebert
On Wed, Aug 26, 2009 at 4:44 AM, gentlestone wrote:
> Can somebody give me an advise where I can found a really good online
> tutorial? All I found are useless. For example no tutorial I found
> explains this piece of code:
>
>    someList = [element for element in otherList if element is not
> None]

See http://docs.python.org/tutorial/datastructures.html#list-comprehensions

> or this example:
>
>    a = a or []

That's a bit more obscure, and I'm not entirely surprised it's not in
a tutorial:
http://docs.python.org/reference/expressions.html#boolean-operations


You might want to try the official tutorial (unless it's the one
you're complaining about):
http://docs.python.org/tutorial/index.html

I've also heard good things about Dive Into Python:
http://diveintopython.org/

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Division and right shift in python

2009-08-26 Thread Cevahir Demirkıran
The previous one was slower but now it is faster.
How can I make this more consistent?
Why cannot I control it?

Where can I find  the algorithms implemented under for example pow, /, %,
etc.?
I could not see them in python documentation?

f2(281367918279371279712863756486284619792197836426862028028824908239084023984967328564836783686836834628136791827937127971286375648628461979219783642686202802882490823908402398496732856483678368683683462813679182793712797128637564862846197921978364268620280288249082390840239849673285648367836868368346,9)

8.3809534317e-06
6.70476276809e-06
512

Thanks in advance,


26 Ağustos 2009 13:53 tarihinde Cevahir Demirkıran yazdı:

> Thanks for the answer.
> Run it with a big number:
>
> f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9)
>
> I had this result:
>
> 8.1015883211e-06
> 1.06158743591e-05
> 512
>
> 2009/8/26 Mark Tolonen 
> >
>
>
>> "Cevahir Demirkiran"  wrote in message
>> news:[email protected]...
>>
>>  Hi,
>>>
>>> I would like to do a floor division by a power of 2 in python to make it
>>> faster than / (modular division in 2.x).
>>> However, it is slower.
>>> What is the reason of that?
>>> I checked them via:
>>>
>>> def f2(x,n):
>>>   t1 = clock()
>>>   r = x/pow(2,n)
>>>   t2 = clock()
>>>   print (t2-t1)
>>>   print r
>>>   t2 = clock()
>>>   r = x>>n
>>>   t3 = clock()
>>>   print (t3-t2)
>>>   print r
>>>
>>>
>> It's not slower on my system, but note the inconsistent results also:
>>
>>  f2(1024,5)
>
 3.47396033483e-06
>> 32
>> 2.19077375482e-06
>> 32
>>
>>>  f2(1024,5)
>
 4.84135603429e-06
>> 32
>> 3.08499440393e-06
>> 32
>>
>>>  f2(1024,5)
>
 4.6782844052e-06
>> 32
>> 3.77604384028e-06
>> 32
>>
>> Time it with timeit...
>>
>> C:\>python -m timeit -n 1000 -s x=1024 "x>>5"
>> 1000 loops, best of 3: 0.113 usec per loop
>>
>> C:\>python -m timeit -n 1000 -s x=1024 "x/pow(2,5)"
>> 1000 loops, best of 3: 0.468 usec per loop
>>
>> Right-shift is over 4x faster.
>>
>> -Mark
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> Cevahir Demirkiran
>



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


Re: Usefull python tutorial

2009-08-26 Thread Simon Brunning
2009/8/26 gentlestone :
> Can somebody give me an advise where I can found a really good online
> tutorial? All I found are useless.

 is really good, as I remember, as
is .

 For example no tutorial I found
> explains this piece of code:
>
>    someList = [element for element in otherList if element is not
> None]


or 

> or this example:
>
>    a = a or []

Strangely not in the tutorial:
.

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


Re: Division and right shift in python

2009-08-26 Thread Dave Angel

Mark Tolonen wrote:


"Cevahir Demirkiran"  wrote in message 
news:[email protected]...

Hi,

I would like to do a floor division by a power of 2 in python to make it
faster than / (modular division in 2.x).
However, it is slower.
What is the reason of that?
I checked them via:

def f2(x,n):
   t1 = clock()
   r = x/pow(2,n)
   t2 = clock()
   print (t2-t1)
   print r
   t2 = clock()
   r = x>>n
   t3 = clock()
   print (t3-t2)
   print r



It's not slower on my system, but note the inconsistent results also:


f2(1024,5)

3.47396033483e-06
32
2.19077375482e-06
32

f2(1024,5)

4.84135603429e-06
32
3.08499440393e-06
32

f2(1024,5)

4.6782844052e-06
32
3.77604384028e-06
32

Time it with timeit...

C:\>python -m timeit -n 1000 -s x=1024 "x>>5"
1000 loops, best of 3: 0.113 usec per loop

C:\>python -m timeit -n 1000 -s x=1024 "x/pow(2,5)"
1000 loops, best of 3: 0.468 usec per loop

Right-shift is over 4x faster.

-Mark





There have been languages and processors in which right shift has been 
notably faster than divide.  But with Python on a Pentium, you're both 
just measuring overhead.  The actual divide or shift is probably less 
than 5% of the time measured.


And that overhead will vary between versions of the interpreter.  I 
measured with Python 2.6.2 on Windows XP, and got


C:\>python -m timeit -n 1000 -s x=1024 "x>>5"
1000 loops, best of 3: 0.112 usec per loop

C:\>python -m timeit -n 1000 -s x=1024 "x/pow(2,5)"
1000 loops, best of 3: 0.384 usec per loop

But the real overhead is in the function call to pow().  If that had 
been precalculated, then the time for divide is nearly as fast as for 
right shift.


C:\>python -m timeit -n 1000 -s x=1024 "x/32"
1000 loops, best of 3: 0.135 usec per loop

And I suspect that some other implementation might well show this 
quicker than the right shift.


I would use whichever code most clearly represents the problem being 
solved.  There are undoubtedly other ways to speed up the code, without 
trying to micro-optimize one expression.


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


Re: Division and right shift in python

2009-08-26 Thread Cevahir Demirkıran
Thanks for the answer.
Run it with a big number:
f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9)

I had this result:

8.1015883211e-06
1.06158743591e-05
512

2009/8/26 Mark Tolonen 
>

>
> "Cevahir Demirkiran"  wrote in message
> news:[email protected]...
>
>  Hi,
>>
>> I would like to do a floor division by a power of 2 in python to make it
>> faster than / (modular division in 2.x).
>> However, it is slower.
>> What is the reason of that?
>> I checked them via:
>>
>> def f2(x,n):
>>   t1 = clock()
>>   r = x/pow(2,n)
>>   t2 = clock()
>>   print (t2-t1)
>>   print r
>>   t2 = clock()
>>   r = x>>n
>>   t3 = clock()
>>   print (t3-t2)
>>   print r
>>
>>
> It's not slower on my system, but note the inconsistent results also:
>
>  f2(1024,5)

>>> 3.47396033483e-06
> 32
> 2.19077375482e-06
> 32
>
>> f2(1024,5)

>>> 4.84135603429e-06
> 32
> 3.08499440393e-06
> 32
>
>> f2(1024,5)

>>> 4.6782844052e-06
> 32
> 3.77604384028e-06
> 32
>
> Time it with timeit...
>
> C:\>python -m timeit -n 1000 -s x=1024 "x>>5"
> 1000 loops, best of 3: 0.113 usec per loop
>
> C:\>python -m timeit -n 1000 -s x=1024 "x/pow(2,5)"
> 1000 loops, best of 3: 0.468 usec per loop
>
> Right-shift is over 4x faster.
>
> -Mark
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: Need help with Python scoping rules

2009-08-26 Thread Dave Angel

Ulrich Eckhardt wrote:

Jean-Michel Pichavant wrote:
  

class Color:
def __init__(self, r, g,b):
  pass
BLACK = Color(0,0,0)

It make sens from a design point of view to put BLACK in the Color
namespace. But I don't think it's possible with python.



class Color:
...

setattrib(Color, "BLACK", Color(0,0,0))

Uli

  

Or instead of setattrib,

Color.BLACK = Color(0,0,0)

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


pygtk - What is the best way to change the mouse pointer

2009-08-26 Thread Ido Levy
Hello All,

I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( 
let's assume widget in the example below is its instance )
When the user select one of the values from the gtk.ComboBoxEntry I need 
to run some calculations that takes a few seconds.
In order to reflect calculation time to the user I want to switch the 
mouse pointer to an hour glass and back to arrow what it finish the 
calculation.

I use the following code but it doesn't seems to work in a deterministic 
way. From time to time it skips the last line and keep the mouse pointer 
as an hour glass.

watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
widget.window.set_cursor(watch)

calculation code

widget.window.set_cursor(None)

I would appreciate your advice on the right way to implement this.

Thanks

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


Re: Move dictionary from instance to class level

2009-08-26 Thread MRAB

Frank Millman wrote:

On Aug 26, 10:54 am, Chris Rebert  wrote:

On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote:

A

class MyClass(object):
def on_message_received(self, msg):
self.method_dict[msg](self)

def method_0(self):
print 'in method_0'

def method_1(self):
print 'in method_1'
method_dict

method_dict = {0: method_0, 1: method_1}
#note this comes *after* the methods in question have been defined



Thanks, Chris. This is much better.


Is there some reason you aren't using a list instead of a dict?
e.g. method_dict = [method_0, method_1, method_2, etc]

For that matter, why are you associating methods with integers in the
first place?



I actually use constants to define my messages, like this -

(MESSAGE_ONE
,MESSAGE_TWO
,MESSAGE_THREE
) = xrange(3)

I can then refer to the messages by their description, but internally it 
uses integers.



An alternative is:

>>> class MyClass(object):
... def on_message_received(self, msg):
... try:
... getattr(self, "method_%d" % msg)()
... except AttributeError:
... raise Exception("Unknown message")
... def method_0(self):
... print 'in method_0'
... def method_1(self):
... print 'in method_1'
...
>>> my_obj = MyClass()
>>> my_obj.on_message_received(0)
in method_0
>>> my_obj.on_message_received(1)
in method_1
>>> my_obj.on_message_received(2)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 6, in on_message_received
Exception: Unknown message
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: ubuntu dist-packages

2009-08-26 Thread Ben Finney
Robin Becker  writes:

> What is the relation between dist-packages/site-packages if any? Is
> this just a name change or is there some other problem being
> addressed?

The problem being addressed is to maintain the distinction between
OS-vendor-managed files versus sysadmin-managed files. That is, the
distinction between:

* Python packages installed by the operating system package manager (the
  OS “distribution”, as distinct from the Python-specific meaning of
  that term); versus

* Python packages installed by the site administrator, outside the
  purview of the OS package manager.

This distinction is important in operating systems with a functioning
package manager.

> For developers is it best just to create one's own private
> installations from the original tarballs?

Developers should be making changes as neither the system administrator
nor the OS package manager, but as a regular user of the system. So
installing to a user-specific package location seems best.

-- 
 \  “Holy rising hemlines, Batman!” —Robin |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Object's nesting scope

2009-08-26 Thread zaur
Hi folk!

What do you think about idea of "object's nesting scope" in python?

Let's imaging this feature, for example, in this syntax:

obj=:
 

or

:
   

That's means that result object of  evaluation is used as
nested scope for  evaluation.

So is this idea useful?

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


Re: Need help with Python scoping rules

2009-08-26 Thread Martin P. Hellwig

kj wrote:


First, one of the goals of OO is encapsulation, not only at the
level of instances, but also at the level of classes.

Who says?
Anyway, you could be right (I am not capable to judge it) and Python 
should change on this issue but from what I gathered, Pythons OO is 
inspired by the following:

- Don't repeat yourself
- Containing code into logical units makes it easier to understand and 
maintain.


Note the absence of 'OO is defined as X so we are going to do X without 
thinking if X is actually the best way to do it'


Your comment suggests that Python does not fully support 
class-level encapsulation.
Probably right too, but being intrigued, why is that necessary, and 
given an example is that the best way to do it?



Second, my example shows that Python puts some peculiar restrictions
on recursion.  Recursion!  One of the central concepts in the theory
of functions!  


It is also one of the best ways to shoot yourself in the foot, but I ask 
you again, is the reason why you encountered this 'limitation' actually 
the best way to solve your problem?


Please forgive my incompetence if this reply sounds harsh and patronizing.

--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code formatting question: conditional expression

2009-08-26 Thread Jorgen Grahn
On Wed, 26 Aug 2009 16:47:33 +1000, Ben Finney
 wrote:
> "Nicola Larosa (tekNico)"  writes:
>
>> Nicola Larosa wrote:
>> > Here's my take:
>> >
>> >     excessblk = Block(total - P.BASE, srccol,
>> > carry_button_suppress=True
>> >         ) if total > P.BASE else None
>>
>> Oops, it got shortened out: line longer than 72 chars, acceptable in
>> code, but not in email. I'll try again.
>
> Fine in email; just munged on your behalf (and probably without your
> knowledge) by your email service provider. If you don't want that
> happening, it's probably best to avoid Google Mail.

But this is Usenet (or at least it gets gatewayed there) and there
are such limits here (either by common agreement or by RFC).
Probably not Google's fault.

/Jorgen

-- 
  // Jorgen GrahnO  o   .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object's nesting scope

2009-08-26 Thread Diez B. Roggisch
zaur wrote:

> Hi folk!
> 
> What do you think about idea of "object's nesting scope" in python?
> 
> Let's imaging this feature, for example, in this syntax:
> 
> obj=:
>  
> 
> or
> 
> :
>
> 
> That's means that result object of  evaluation is used as
> nested scope for  evaluation.
> 
> So is this idea useful?

Whom am we to judge? Sure if you propose this, you have some usecases in
mind - how about you present these?

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


Re: Need help with Python scoping rules

2009-08-26 Thread 7stud
On Aug 25, 7:26 pm, Dave Angel  wrote:
> Stephen Fairchild wrote:
> > You are trying to run code in a class that does not exist yet.
>
> > def Demo():
> >     def fact(n):
> >         if n < 2:
> >             return 1
> >         else:
> >             return n * fact(n - 1)
> >     return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar":
> > fact(5)})
> > Demo = Demo()
>
> > d = Demo()
> > print d._classvar    # prints 120
> > print d.fact(7)      # prints 5040
> > print Demo           # prints 
>
>
>
> In all these messages, something I haven't seen pointed out is that
> fact() has no self argument.  
>

An "argument" is something that is specified in the the function
call.  I assume you are trying to state something like, "fact() is not
defined with a parameter variable named self".  However, that has
never been a requirement in python:


class A(object):

def fact(n):
print n

fact("hello")


a = A()
a.fact()

--output:--
hello
<__main__.A object at 0x7faf0>



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


"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot

2009-08-26 Thread Jawad Alam
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in
alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/
"JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN
ALASKA" "jobs

Re: print() and unicode strings (python 3.1)

2009-08-26 Thread 7stud
On Aug 25, 6:34 am, Nobody  wrote:
> The underlying OS primitive can only handle bytes. If you read or write a
> (unicode) string, Python needs to know which encoding is used. For Python
> file objects created by the user (via open() etc), you can specify the
> encoding; for those created by the runtime (e.g. sys.stdin), Python uses
> the locale's LC_CTYPE category to select an encoding.
>
> Data written to or read from text streams is encoded or decoded using the
> stream's encoding. Filenames are encoded and decoded using the
> filesystem encoding (sys.getfilesystemencoding()). Anything else uses the
> default encoding (sys.getdefaultencoding()).
>
> In Python 3, text streams are handled using io.TextIOWrapper:
>
>        http://docs.python.org/3.1/library/io.html#text-i-o
>
> This implements a stream which can read and/or write text data on top of
> one which can read and/or write binary data. The sys.std{in,out,err}
> streams are instances of TextIOWrapper. You can get the underlying
> binary stream from the "buffer" attribute, e.g.:
>
>         sys.stdout.buffer.write(b'hello world\n')
>
> If you need to force a specific encoding (e.g. if the user has specified
> an encoding via a command-line option), you can detach the existing
> wrapper and create a new one, e.g.:
>
>         sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 
> new_encoding)

Thanks for the details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with arrays

2009-08-26 Thread Mart.
On Aug 26, 3:02 am, Dave Angel  wrote:
> Stephen Fairchild wrote:
> > Philip Semanchuk wrote:
>
> >> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote:
>
> >>> Hello! I'm working on an exercise wherein I have to write a Guess The
> >>> Number game, but it's the computer who's guessing MY number. I can get
> >>> it to work, but there's one obvious problem: the computer generates
> >>> random numbers until one of them corresponds to my number, but it will
> >>> often generate one number (eg. 4) numerous times, meaning it doesn't
> >>> know that this number is invalid. What I mean is, it will sometimes
> >>> use 37 tries to guess a number out of 1 - 9, which makes no sense,
> >>> since it should only take 9 tries, at most. I was trying to find a way
> >>> to make a dynamic list of all the numbers the computer generates in
> >>> the loop and then make it re-generate the number if the previous
> >>> number is present in the list, so it doesn't keep on generating 4 (as
> >>> an example). I don't know if that makes sense... Basically, we humans
> >>> know that once something is incorrect, there's no point in trying to
> >>> use it as the answer next time, because we already know it's
> >>> incorrect. How do I go about coding this in Python? I'm still quite
> >>> new to the language so any help will be appreciated...
>
> >> One cheap way to do it (not necessarily efficient) is to make a list
> >> of your possible guesses (e.g. range(1,10)), use random.shuffle() to
> >> put them in random order and then run through the guesses one at a time.
>
> > import random
> > import time
>
> > l = range(1, 10)
>
> > while l:
> > print l.pop(random.randint(0, len(l) - 1))
> > time.sleep(2)
>
> While both of these will work well, I'd point out that a direct
> translation of your question is to use a set.  Define an empty set, and
> each time you try a number unsuccessfully, add it to the set.  Then just use
>while x in myset:
>x = newguess()
>
> to find the next guess.  This approach isn't as efficient, but it's a
> useful paradigm to understand.
>
> A separate question is whether the human is supposed to tell the
> computer whether the guess is high or low.  If so, you can eliminate
> many numbers on each guess.   For example, suppose the solution is 8.  A
> guess of 5 would say "too low."  Then you'd cross off now only 5 but 1-4
> as well.
>
> With this change the best solution changes from a random shuffle to a
> binary search.
>
> DaveA

That's a good point if you can define whether the computer has guessed
too low/high, then you could use the previous guess to set a bounds
and rescale the next random guess.

min + (random_number * max)

although I think random.randomint does this for you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In  "Martin P. Hellwig" 
 writes:

>kj wrote:
>
>> First, one of the goals of OO is encapsulation, not only at the
>> level of instances, but also at the level of classes.
>Who says?

Python itself: it already offers a limited form of class encapsulation
(e.g. class variables).  It would be nice if it went all the way
and gave classes their own bona fide scope.  (But I hasten to add:
I *still* don't understand the Python scope model, and not for lack
of trying.  I've only succeeded in finding fragments of this model
explained here and there, like pottery shards: a bit lost in a
tutorial, or some comment in a newsgroup thread, etc.  Maybe the
full, authoritative documentation of Python's scope model got lost
somewhere, and will be found by archaeologists in the 25th century...)

>Anyway, you could be right (I am not capable to judge it) and Python 
>should change on this issue but from what I gathered, Pythons OO is 
>inspired by the following:
>- Don't repeat yourself
>- Containing code into logical units makes it easier to understand and 
>maintain.

...except, apparently, when that code is a recursive function, in
which case one's out of luck.

>> Second, my example shows that Python puts some peculiar restrictions
>> on recursion.  Recursion!  One of the central concepts in the theory
>> of functions!  
>
>It is also one of the best ways to shoot yourself in the foot...

If recursion is so evil, and Python so intent in saving us from
shooting ourselves in the foot, why does it allow recursion at all?

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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In <16b72319-8023-471c-ba40-8025aa6d4...@a26g2000yqn.googlegroups.com> Carl 
Banks  writes:


>> First, one of the goals of OO is encapsulation, not only at the
>> level of instances, but also at the level of classes. =A0Your comment
>> suggests that Python does not fully support class-level encapsulation.

>I can't answer this, I don't even know what you are talking about.

Yes, you do.  As I said in another post, Python offers some degree
of class-level encapsulation (e.g. class variables).  But it is
limited by the fact that these class-encapsulated elements can't
always be accessed from within the class itself, which is kind of
silly.

>1. One of the key aspects of Python's design is that attributes must
>be accessed explicitly with dot notation.  Accessing class scopes from
>nested functions would (seemingly) allow access to class attributes
>without the dotted notation.  Therefore it is not allowed.

It would be trivial to define a keyword (e.g. this, or if you
prefer, __this__), valid only within a class statement, and that
the interpreter would recognize as "the current class", even before
this class is full defined.

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


Zlib: correct checksum but error decompressing

2009-08-26 Thread Andre
I have been trying to solve this issue for a while now. I receive data
from a TCP connection which is compressed. I know the correct checksum
for the data and both the client and server generate the same
checksum. However, in Python when it comes to decompressing the data I
get the exception: "Error -5 while decompressing data"! I would assume
that if the string in python is equivalent to the correct checksum
than the decompress function should also work on the same string, but
that's clearly not the case.

# convert data to a byte array
data = array('b', raw_data)
# print checksum for visual inspection
print zlib.crc32(data.tostring())
# try to decompress, but fails!
str = zlib.decompress(data.tostring())

Does anyone know what's going on?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.popen output different from native shell output

2009-08-26 Thread Nobody
On Tue, 25 Aug 2009 11:42:31 -0700, nickname wrote:

> The reason why I want to do this is because I am going to do a little
> project. I will write a python script called ls which will log the
> time and username and then will show the actual ls output. I want this
> to be transparent and so want to throw the ls output (via python)
> exactly as it will be in native shell execution.

If your script doesn't need the "ls" output for its own purposes, just run
"ls" with its output to the terminal, rather than into a pipe. I.e. don't
use os.popen(), but use os.spawnvp(), os.execvp() or subprocess.call().

If running "ls" is the very last thing which your script does, use
os.execvp(). This causes the program to be executed in the existing
process, rather than spawning a child process and waiting for it to exit.

Because they replace the existing program (the Python interpreter), the
various os.exec* functions don't return (unless there's an error). If you
need to perform any action after the command completes (e.g. log the
execution time), you need to use one of the other functions instead.

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


Re: Need help with Python scoping rules

2009-08-26 Thread Dave Angel

7stud wrote:

On Aug 25, 7:26 pm, Dave Angel  wrote:
  

Stephen Fairchild wrote:


You are trying to run code in a class that does not exist yet.
  
def Demo():

def fact(n):
if n < 2:
return 1
else:
return n * fact(n - 1)
return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar":
fact(5)})
Demo =emo()
  
d =emo()

print d._classvar# prints 120
print d.fact(7)  # prints 5040
print Demo   # prints 
  


In all these messages, something I haven't seen pointed out is that
fact() has no self argument.  




An "argument" is something that is specified in the the function
call.  I assume you are trying to state something like, "fact() is not
defined with a parameter variable named self".  However, that has
never been a requirement in python:


class A(object):

def fact(n):
print n

fact("hello")


a =()
a.fact()

--output:--
hello
<__main__.A object at 0x7faf0>



  
You're good at nitpicking.  I concede the distinction between argument 
and formal parameter.   And self is a convention, not a requirement.   
But the fact is that the method as written would never have worked, when 
called from outside the class, since you'd have to call it with either 
the class name or an instance, and in either case, the method was then 
trying to do arithmetic on one of those.


Thanks for diluting my point.  The OP is chasing the wrong problem.  Who 
cares whether a class initializer can call a method, if the method 
doesn't meet its original requirements, to be callable outside the class?


And the arguments about how recursion is restricted are ridiculous.  
Nothing wrong with a method calling itself, once it's got a proper 
signature.  You just have to make the call agree with the signature.  
The problem is only that the method may not be actually called until the 
class definition is complete.


DaveA

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


Re: Need help with Python scoping rules

2009-08-26 Thread Mel
kj wrote:

> Is there any good reason (from the point of view of Python's overall
> design) for not fixing this?

Python is not a compiled language, in the sense that a compiler can go back 
and forth over the program, filling in the details that make the program 
runnable.  Python is an interpreted language in a sense that makes a `class` 
statement an executable statement, with a start time and an end time.  
Before the start time, the affected class doesn't exist.  After the start 
time, the class does exist.  In between, while the `class` statement is 
executing, it's best to make no promises so as not to constrain present and 
future implementations.


Mel.

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


Re: Move dictionary from instance to class level

2009-08-26 Thread Frank Millman

"MRAB"  wrote in message 
news:[email protected]...
> An alternative is:
>
> >>> class MyClass(object):
> ... def on_message_received(self, msg):
> ... try:
> ... getattr(self, "method_%d" % msg)()
> ... except AttributeError:
> ... raise Exception("Unknown message")
> ... def method_0(self):
> ... print 'in method_0'
> ... def method_1(self):
> ... print 'in method_1'
> ...
> >>> my_obj = MyClass()
> >>> my_obj.on_message_received(0)
> in method_0
> >>> my_obj.on_message_received(1)
> in method_1
> >>> my_obj.on_message_received(2)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 6, in on_message_received
> Exception: Unknown message

I like the idea. Unfortunately my real-world situation is a little more 
complex than my simple example implied.

This is a more typical example -

(EVT_GETLOGIN
,EVT_LOGOUT
,EVT_GETMENUOPT
,EVT_GOTFOCUS
,EVT_LOSTFOCUS
,EVT_BUTTONCLICKED
,EVT_CHECKBOX
...
) = xrange(28)

method_dict = {}
method_dict[EVT_GETLOGIN] = onGetLogin
method_dict[EVT_LOGOUT] = onLogout
method_dict[EVT_GETMENUOPT] = onGetMenuOpt
method_dict[EVT_GOTFOCUS] = onGotFocus
method_dict[EVT_LOSTFOCUS] = onLostFocus
method_dict[EVT_BUTTONCLICKED] = onButtonClicked
method_dict[EVT_CHECKBOX] = onCheckBox

You can probably figure out from my method names what I am doing here - the 
messages are sent by a thin client (wxPython), and processed by a server.I 
am anticipating some "don't do that" responses, but I like the concept, and 
so far it is very fast and responsive, so I will pursue it for now.

Thanks for the input.

Frank


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


Re: Need help with Python scoping rules

2009-08-26 Thread Carl Banks
On Aug 26, 7:09 am, kj  wrote:
> In <16b72319-8023-471c-ba40-8025aa6d4...@a26g2000yqn.googlegroups.com> Carl 
> Banks  writes:
>
> >> First, one of the goals of OO is encapsulation, not only at the
> >> level of instances, but also at the level of classes. =A0Your comment
> >> suggests that Python does not fully support class-level encapsulation.
> >I can't answer this, I don't even know what you are talking about.
>
> Yes, you do.  As I said in another post, Python offers some degree
> of class-level encapsulation (e.g. class variables).  But it is
> limited by the fact that these class-encapsulated elements can't
> always be accessed from within the class itself, which is kind of
> silly.

Nope, you're wrong.  Class variables are accessible wherever a class
exists.  The apparent silliness of this is because you are confusing
classes with class statements.

You know that the class isn't created until the class statement exits,
don't you?

Yeah, it's a little surprising that you can't access class scope from
a function, but that has nothing to do with encapsulation.

> >1. One of the key aspects of Python's design is that attributes must
> >be accessed explicitly with dot notation.  Accessing class scopes from
> >nested functions would (seemingly) allow access to class attributes
> >without the dotted notation.  Therefore it is not allowed.
>
> It would be trivial to define a keyword (e.g. this, or if you
> prefer, __this__), valid only within a class statement, and that
> the interpreter would recognize as "the current class", even before
> this class is full defined.

Your solution to this "problem" is to add a keyword to Python.
Laughable.  (BTW, it's not trivial.)


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


Re: Need help with Python scoping rules

2009-08-26 Thread Dave Angel

kj wrote:

In <[email protected]> "Diez B. Roggisch"  
writes:

  

Classes are not scopes.



This looks to me like a major wart, on two counts.

First, one of the goals of OO is encapsulation, not only at the
level of instances, but also at the level of classes.  Your comment
suggests that Python does not fully support class-level encapsulation.

Second, my example shows that Python puts some peculiar restrictions
on recursion.  Recursion!  One of the central concepts in the theory
of functions!  This is shown most clearly by the following elaboration
of my original example:

class Demo(object):
def fact_rec(n):
if n < 2:
return 1
else:
return n * fact_rec(n - 1)

  
Why not fix the call?  The correct way to call a method is with either 
the class name or an instance object, depending on whether it's a 
instance method or not.  By default, a method is unbound, and its first 
argument is by convention called self.  If you want to recurse, then add 
self in the appropriate places.


As you have it, neither of the methods can be called outside the class:

class Demo(object):
   def fact_rec(n):
   if n < 2:
   return 1
   else:
   return n * fact_rec(n - 1)


obj = Demo()
print obj.fact_rec(5)

gives error:

Traceback (most recent call last):
 File "M:\Programming\Python\sources\dummy\stuff2.py", line 20, in 
   print obj.fact_rec(5)
TypeError: fact_rec() takes exactly 1 argument (2 given)

To fix it, you need to either change the signature (add in 'self' 
argument before the n argument) or do some form of decorator to the 
function.  If I assume you never intended this method to use 'self'  
(ie. it's a static method), then declare it so.  And call it accordingly.



class Demo(object):
   @staticmethod
   def fact(n):
   if n < 2:
   return 1
   else:
   return n * Demo.fact(n - 1)


print Demo.fact(6)

On the other hand, if I assume you're just giving a simple example of 
what's really intended to be a normal method (called with an instance, 
that it uses), then you'd change it this way.


class Demo2(object):
   def fact(self, n):
   if n<2:
   return 1
   else:
   return n * self.fact(n-1)

obj = Demo2()
print obj.fact(5)

Now the only real restriction, as opposed to all these red-herrings, is 
that the class may not be used before it's complete.  That only comes to 
play when class attributes (non-instance "variables") are defined in 
terms of class methods.  So if you have such attributes to define, move 
them outside of the class, perhaps immediately after it.



class Demo(object):
   @staticmethod
   def fact(n):
   if n < 2:
   return 1
   else:
   return n * Demo.fact(n - 1)
Demo._classvar = Demo.fact(5)


def fact_iter(n):
ret = 1
for i in range(1, n + 1):
ret *= i
return ret

classvar1 = fact_iter(5)
classvar2 = fact_rec(5)

This code won't compile as shown, 
Sure it will compile.  It just won't run.  You get the error after 
compiling the function when *calling* it from the classvar* line.  But 
at that time the class is not defined, and not everything is ready for use.


You can probably work around this by replacing the staticmethod 
decorator with an equivalent function call:.


class Demo9(object):
   def fact(n):
   if n < 2:
   return 1
   else:
   return n * Demo.fact(n - 1)

   _classvar = fact(5)
   fact = staticmethod(fact)

print Demo9._classvar
xx = Demo9()
print xx.fact(6)
print Demo9.fact(8)

but it does compile if the last
line (the call to the recursive fact_rec) is commented out.  There
is no justification for discriminating against recursive functions
in this context.  Recursive functions should be OK wherever functions
are OK.  I can't think of any other language that allows recursion
but not anywhere.

Is there any good reason (from the point of view of Python's overall
design) for not fixing this?

kynn


  

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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In  Dave Angel 
 writes:

>Thanks for diluting my point.  The OP is chasing the wrong problem.  Who 
>cares whether a class initializer can call a method, if the method 
>doesn't meet its original requirements, to be callable outside the class?

>And the arguments about how recursion is restricted are ridiculous.  
>Nothing wrong with a method calling itself, once it's got a proper 
>signature.  You just have to make the call agree with the signature.  
>The problem is only that the method may not be actually called until the 
>class definition is complete.

As I described at length in another reply, the function in question
is not intended to be "callable outside the class".  And yes,
recursive functions in Python *are* restricted in ways that
non-recursive functions aren't.  The examples I've posted prove
this point unambiguously.

At this point the only defense for this restriction is to claim
that it is somehow negligible.  But I disagree.  It's easy to come
up with equally negligible, and equally indefensible, restrictions
to the language would be found quite unacceptable by most users.
E.g. suppose that Python's specification prohibited the use of
upper case X in an identifier.  That's certainly a negligible
restriction: it is not harder at all to write great software without
the services of the letter X than with them.  Still, I think most
users would find this restriction infuriatingly idiotic.  Which
pretty much captures what I feel about Python's prohibition of
recursive functions within class statements.

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


Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]

2009-08-26 Thread Carl Banks
On Aug 25, 1:07 pm, Evan Driscoll  wrote:
> On Aug 25, 2:33 pm, Evan Driscoll  wrote:
>
> > I want to make a context manager that will temporarily change the
> > value of a variable within the scope of a 'with' that uses it. This is
> > inspired by a C++ RAII object I've used in a few projects. Ideally,
> > what I want is something like the following:
>
> Okay, so I think I actually got this with some consultation with a
> friend. Critiques?
>
>     from contextlib import contextmanager
>     import inspect
>
>     def get_parents_var(offset, var):
>         f = inspect.stack()[offset][0]
>         if var in f.f_locals:
>                 return f.f_locals[var]
>         else:
>                 return f.f_globals[var]
>
>     def set_parents_var(offset, var, val):
>         f = inspect.stack()[offset][0]
>         if var in f.f_locals:
>             f.f_locals[var] = val
>         elif var in f_globals:
>             f.f_globals[var] = val
>         else:
>             assert False
>
>     @contextmanager
>     def changed_value_tb(var_name, temp_value):
>         # 1 is here, 2 will be the implicit next() function, 3 is the
> real caller
>         offset = 3
>         old_value = get_parents_var(offset, var_name)
>         set_parents_var(offset, var_name, temp_value)
>         try:
>             yield None
>         finally:
>             set_parents_var(offset, var_name, old_value)
>
>     x = 5
>     print x   # prints 5
>     with changed_value_tb("x", 10):
>         print x  # prints 10
>     print x  # prints 5

Well, it wouldn't be a "can I rebind a variable using a with-
statement" thread if someone didn't post a solution that they thought
worked, but didn't test it on local variables.


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


Raw data extraction question

2009-08-26 Thread Maggie
i have event timing stretch of code i need to alter. here is code
below:
--
# we start each run with one full silent trial
# creating a "stub" with the duration of a full block
# less the discarded acquisitions
stub = block_dur - (distax * tr)

feed = sys.stdin.readlines()
sess = -1
for line in feed:
if re.search(line != rest):
   time = (line + line (-1)) + (distax * tr)
print time

 elif (line(-1) = rest):
# block onsets are determined by
# block number, block duration,
# and the stub; 3dDeconvolve
# takes care of making these
# "global"
time = (line) + (distax * tr)
print time
-
my concern is that it is extracting line number and not data contained
on a given line. I need it to extract data from each line (excluding
lines with spaces and/or lines that contain the word "pause" or
"silence"). Basically i need ONLY raw data extracted from line 1 -
onward.

Please let me know if you have any suggestions.

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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In <1bf83a7e-f9eb-46ff-84fe-cf42d9608...@j21g2000yqe.googlegroups.com> Carl 
Banks  writes:

>On Aug 26, 7:09=A0am, kj  wrote:
>> In <16b72319-8023-471c-ba40-8025aa6d4...@a26g2000yqn.googlegroups.com> Ca=
>rl Banks  writes:
>>
>> >> First, one of the goals of OO is encapsulation, not only at the
>> >> level of instances, but also at the level of classes. =3DA0Your commen=
>t
>> >> suggests that Python does not fully support class-level encapsulation.
>> >I can't answer this, I don't even know what you are talking about.
>>
>> Yes, you do. =A0As I said in another post, Python offers some degree
>> of class-level encapsulation (e.g. class variables). =A0But it is
>> limited by the fact that these class-encapsulated elements can't
>> always be accessed from within the class itself, which is kind of
>> silly.

>Nope, you're wrong.  Class variables are accessible wherever a class
>exists.  The apparent silliness of this is because you are confusing
>classes with class statements.

Repeating an earlier example (though I've switched the order of
the two internal functions):

class Demo(object):
def fact_iter(n):
ret = 1
for i in range(1, n + 1):
ret *= i
return ret

def fact_rec(n):
if n < 2:
return 1
else:
return n * fact_rec(n - 1)

classvar1 = fact_iter(5)
classvar2 = fact_rec(5)


In the initialization of classvar1, fact_iter is invoked without
any problem even though the class is not yet created: no need to
qualify it with the name of the class.  This is completely inconsistent
with the requirement that fact_rec be so qualified when invoked
within fact_rec.

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


Re: Numeric literals in other than base 10 - was Annoying octal notation

2009-08-26 Thread Steven D'Aprano
On Tue, 25 Aug 2009 11:45:28 -0700, Mensanator wrote:

> On Aug 25, 9:14 am, Steven D'Aprano  cybersource.com.au> wrote:
>> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote:
>> >> If you want your data file to have values entered in hex, or oct, or
>> >> even unary (1=one, 11=two, 111=three, =four...) you can.
>>
>> > Unary? I think you'll find that Standard Positional Number Systems
>> > are not defined for radix 1.
>>
>> Of course not. But unary isn't a positional number system. It's a tally
>> system, like my example above shows. Roman numerals are another tally
>> system. Like Roman numerals, the disadvantages of unary are that you
>> can't represent negative numbers, zero, or fractions, and anything but
>> addition and subtraction is difficult. But if you want to use it,
>> perhaps out of a sense of sadism towards your users, it's easy:
[...]
> But without insignificant leading 0's, I fail to see the relevance of
> unary to this discussion.

It was just an example of how you can use numeric data in any format, no 
matter how obscure, weird or difficult, you can use it by passing it 
through an appropriate converter. You don't need compiler support for 
user-supplied data, you just write your own function.

As for insignificant leading zeroes, such a thing is meaningless in a 
base-1 tally system. Zero is the absence of a tally mark.


> And what would you call a tally system of
> radix 2? Certainly not binary.

"Radix" isn't the correct term, because radix doesn't apply to tally 
counting systems. I'd accept "base 2", in the sense that the tally is 
based on two different marks. We do something similar when we mark four 
tally lines, then for five we mark a diagonal line through the previous 
four. So by analogy a base-2 tally could go:

/ one
X two
X/three
XXfour
XX/   five
XXX   six
XXX/  seven


But I certainly wouldn't call it "binary", for fear of confusion with 
radix-2 binary. Possibly binary-tally, for lack of a better term.



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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In  Dave Angel 
 writes:

>Stephen Fairchild wrote:
>> You are trying to run code in a class that does not exist yet. 
>>
>> def Demo():
>> def fact(n):
>> if n < 2:
>> return 1
>> else:
>> return n * fact(n - 1)
>> return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar":
>> fact(5)})
>> Demo = Demo()
>>
>> d = Demo()
>> print d._classvar# prints 120
>> print d.fact(7)  # prints 5040
>> print Demo   # prints 
>>
>>   
>In all these messages, something I haven't seen pointed out is that 
>fact() has no self argument.  Seems to me that makes it a staticmethod, 
>so it should be declared that way.

No, the fact() function here represents an internal "helper"
function.  It is meant to be called only once to help initialize
a class variable that would be inconvenient to initialize otherwise;
this helper function is not meant to be called from outside the
class statement.  Granted, in the example I gave, the "helper"
function (factorial) is a bit silly, but that was just intended as
a simple and familiar example of a recursive function.  The actual
function that motivated this post would be considerably more
difficult to explain and would have obscured the point of the post.

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


Re: Need help with Python scoping rules

2009-08-26 Thread Carl Banks
On Aug 26, 8:13 am, Dave Angel  wrote:
> You can probably work around this by replacing the staticmethod
> decorator with an equivalent function call:.
>
> class Demo9(object):
>     def fact(n):
>         if n < 2:
>             return 1
>         else:
>             return n * Demo.fact(n - 1)
>
>     _classvar = fact(5)
>     fact = staticmethod(fact)
>
> print Demo9._classvar
> xx = Demo9()
> print xx.fact(6)
> print Demo9.fact(8)

This won't work normally.  It only worked for you because you made a
typo.


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


Re: Zlib: correct checksum but error decompressing

2009-08-26 Thread InvisibleRoads Patrol
On Wed, 26 Aug 2009 07:19:42 -0700 (PDT), Andre 
wrote:
> I have been trying to solve this issue for a while now. I receive data
> from a TCP connection which is compressed. I know the correct checksum
> for the data and both the client and server generate the same
> checksum. However, in Python when it comes to decompressing the data I
> get the exception: "Error -5 while decompressing data"! I would assume
> that if the string in python is equivalent to the correct checksum
> than the decompress function should also work on the same string, but
> that's clearly not the case.
> 
> # convert data to a byte array
> data = array('b', raw_data)
> # print checksum for visual inspection
> print zlib.crc32(data.tostring())
> # try to decompress, but fails!
> str = zlib.decompress(data.tostring())
> 
> Does anyone know what's going on?

Hi Andre,

Hmm.  Can you decompress the string on the server before it was sent? 
Maybe the zipfile or gzip module will work.
Reference:
http://bytes.com/topic/python/answers/42131-zlib-decompress-cannot-gunzip-can
from cStringIO import StringIO
from gzip import GzipFile
body = GzipFile('', 'r', 0, StringIO(raw_data)).read()

You might want to try experimenting with the wbits parameter of
zlib.decompress()
Reference:
http://mail.python.org/pipermail/python-list/2008-December/691694.html
zlib.decompress(data, -15)

The zlib module seems to work fine with both strings and byte arrays.
import array, zlib
dataAsString = zlib.compress('example string')
dataAsArray = array.array('b', dataAsString)
zlib.decompress(dataAsString) == zlib.decompress(dataAsArray)
zlib.decompress(dataAsString) == zlib.decompress(dataAsArray.tostring())

-- 
http://invisibleroads.com

We train ordinary people into Python software developers and connect them
with jobs and projects for local businesses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with Python scoping rules

2009-08-26 Thread Steven D'Aprano
On Wed, 26 Aug 2009 10:57:32 +, kj wrote:

> In <[email protected]> "Diez B. Roggisch"
>  writes:
> 
>>Classes are not scopes.
> 
> This looks to me like a major wart, on two counts.
> 
> First, one of the goals of OO is encapsulation, not only at the level of
> instances, but also at the level of classes.  Your comment suggests that
> Python does not fully support class-level encapsulation.

I don't even know what that is supposed to mean. If anything, your 
problem could be because Python has TOO MUCH "class-level encapsulation" 
compared to what you are expecting: functions inside a class don't see 
the class attributes you expect them too.

Actually, I think your problem is that you are interpreting what you're 
seeing in terms of C++ or Java, and assuming that whatever they do is the 
One True Definition of OO. That's hardly valid -- if any language 
deserves the label of the One True OO Design, it might be Smalltalk, on 
the basis that it was the first OO language. But even that is silly -- 
just because something was the first, that doesn't make it the best 
example of something.


> Second, my example shows that Python puts some peculiar restrictions on
> recursion.  

Incorrect. Recursive calls are just like any other function call in 
Python: when you call *any* function from the body of a function, it must 
be in scope at runtime.

def fact(n):
print g()  # g must be in scope when fact is called
if n < 2: return 1
return n*fact(n-1)  # fact must be in scope when fact is called


Python doesn't treat recursive functions specially in any way. It is 
*classes*, not functions, that are special. This is explained in the docs:

http://docs.python.org/reference/executionmodel.html

It is also discussed in the PEP introducing nested scopes to Python:

http://www.python.org/dev/peps/pep-0227/

It's even eluded to in the tutorial:

http://docs.python.org/tutorial/classes.html




> Recursion!  One of the central concepts in the theory of
> functions!  This is shown most clearly by the following elaboration of
> my original example:
> 
> class Demo(object):
> def fact_rec(n):
> if n < 2:
> return 1
> else:
> return n * fact_rec(n - 1)

Why are you defining a method without a self parameter?

In any case, the problem has nothing to do with recursion:


>>> class Broken:
... def f():
... return g()
... def g():
... return "gee"
... x = f()
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 6, in Broken
  File "", line 3, in f
NameError: global name 'g' is not defined




> def fact_iter(n):
> ret = 1
> for i in range(1, n + 1):
> ret *= i
> return ret
> 
> classvar1 = fact_iter(5)
> classvar2 = fact_rec(5)
> 
> This code won't compile as shown, 

That's nonsense. It compiles, and then it suffers a runtime error when 
you *execute* it.  (NameError occurs at runtime, not at compile time.) 
You can prove this for yourself by putting that above class definition 
inside a string, s:

>>> x = compile(s, '', 'exec')
>>> exec(x)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
  File "", line 15, in Demo
  File "", line 6, in fact_rec
NameError: global name 'fact_rec' is not defined


If you expect us to take your criticisms seriously, at least get your 
basic facts right.


[...]
> Is there any good reason (from the point of view of Python's overall
> design) for not fixing this?

It doesn't need to be "fixed" because it's not broken. The question is, 
should it be *changed* to match C++ programmers' expectations?



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


Re: Help with arrays

2009-08-26 Thread Dave Angel

Mart. wrote:

On Aug 26, 3:02 am, Dave Angel  wrote:
  

Stephen Fairchild wrote:


Philip Semanchuk wrote:
  

On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote:


Hello! I'm working on an exercise wherein I have to write a Guess The
Number game, but it's the computer who's guessing MY number. I can get
it to work, but there's one obvious problem: the computer generates
random numbers until one of them corresponds to my number, but it will
often generate one number (eg. 4) numerous times, meaning it doesn't
know that this number is invalid. What I mean is, it will sometimes
use 37 tries to guess a number out of 1 - 9, which makes no sense,
since it should only take 9 tries, at most. I was trying to find a way
to make a dynamic list of all the numbers the computer generates in
the loop and then make it re-generate the number if the previous
number is present in the list, so it doesn't keep on generating 4 (as
an example). I don't know if that makes sense... Basically, we humans
know that once something is incorrect, there's no point in trying to
use it as the answer next time, because we already know it's
incorrect. How do I go about coding this in Python? I'm still quite
new to the language so any help will be appreciated...
  

One cheap way to do it (not necessarily efficient) is to make a list
of your possible guesses (e.g. range(1,10)), use random.shuffle() to
put them in random order and then run through the guesses one at a time.


import random
import time
  
l = range(1, 10)
  
while l:

print l.pop(random.randint(0, len(l) - 1))
time.sleep(2)
  

While both of these will work well, I'd point out that a direct
translation of your question is to use a set.  Define an empty set, and
each time you try a number unsuccessfully, add it to the set.  Then just use
   while x in myset:
   x = newguess()

to find the next guess.  This approach isn't as efficient, but it's a
useful paradigm to understand.

A separate question is whether the human is supposed to tell the
computer whether the guess is high or low.  If so, you can eliminate
many numbers on each guess.   For example, suppose the solution is 8.  A
guess of 5 would say "too low."  Then you'd cross off now only 5 but 1-4
as well.

With this change the best solution changes from a random shuffle to a
binary search.

DaveA



That's a good point if you can define whether the computer has guessed
too low/high, then you could use the previous guess to set a bounds
and rescale the next random guess.

min + (random_number * max)

although I think random.randomint does this for you!

  
Actually, if you change the specs this way, you don't need random at 
all.  Just guess halfway through the remaining range.  To guess a number 
between 1 and 100 this way takes 7 guesses, worst case.  (plus/minus 1, 
I haven't checked)   Same problem as searching a sorted list.


This code (from:  
http://stackoverflow.com/questions/212358/binary-search-in-python)  
appears to search a sorted list


|def binary_search(a, x, lo=0, hi=None):
   if hi is None:
   hi = len(a)
   while lo < hi:
   mid = (lo+hi)//2
   midval = a[mid]
   if midval < x:
   lo = mid+1
   elif midval > x: 
   hi = mid

   else:
   return mid
   return -1

|


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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In <1bf83a7e-f9eb-46ff-84fe-cf42d9608...@j21g2000yqe.googlegroups.com> Carl 
Banks  writes:

>Yeah, it's a little surprising that you can't access class scope from
>a function, but that has nothing to do with encapsulation.

It does: it thwarts encapsulation.  The helper function in my
example is one that clearly rightfully belongs nowhere else than
the class itself, i.e. encapsulated within the class.  It is only
this silly prohibition against recursive functions in a class
statement that forces one to put it outside the class statement.

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


Re: Need help with Python scoping rules

2009-08-26 Thread Steven D'Aprano
On Wed, 26 Aug 2009 13:57:23 +, kj wrote:

> In  "Martin P. Hellwig"
>  writes:
> 
>>kj wrote:
>>
>>> First, one of the goals of OO is encapsulation, not only at the level
>>> of instances, but also at the level of classes.
>>Who says?
> 
> Python itself: it already offers a limited form of class encapsulation
> (e.g. class variables).

An int variable is an int. A string variable is a string. A bool variable 
is a bool. A class variable is a class.

Perhaps you mean a class attribute?


> It would be nice if it went all the way and
> gave classes their own bona fide scope.

Classes have their own bona fide scope. It just doesn't work the way you 
expect it to.


> (But I hasten to add: I *still*
> don't understand the Python scope model, and not for lack of trying. 
> I've only succeeded in finding fragments of this model explained here
> and there, like pottery shards: a bit lost in a tutorial, or some
> comment in a newsgroup thread, etc.  Maybe the full, authoritative
> documentation of Python's scope model got lost somewhere, and will be
> found by archaeologists in the 25th century...)

It's all in the Fine Manual:

http://docs.python.org/reference/executionmodel.html


 
>>Anyway, you could be right (I am not capable to judge it) and Python
>>should change on this issue but from what I gathered, Pythons OO is
>>inspired by the following:
>>- Don't repeat yourself
>>- Containing code into logical units makes it easier to understand and
>>maintain.
> 
> ...except, apparently, when that code is a recursive function, in which
> case one's out of luck.

Incorrect. As I showed in my previous post, your problem has nothing to 
do with recursion.


>>> Second, my example shows that Python puts some peculiar restrictions
>>> on recursion.  Recursion!  One of the central concepts in the theory
>>> of functions!
>>
>>It is also one of the best ways to shoot yourself in the foot...
> 
> If recursion is so evil, and Python so intent in saving us from shooting
> ourselves in the foot, why does it allow recursion at all?

Recursion isn't evil, and Python isn't intent on preventing foot-shooting.



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


Re: Need help with Python scoping rules

2009-08-26 Thread Nigel Rantor
kj wrote:
>
> Needless to say, I'm pretty beat by this point.  Any help would be
> appreciated.
> 
> Thanks,

Based on your statement above, and the fact that multiple people have
now explained *exactly* why your attempt at recursion hasn't worked, it
might be a good idea to step back, accept the advice and walk away
instead of trying to convince people that the language forbids recursion
and doesn't provide decent OO ecapsulation.

Otherwise I'd wager you'll soon be appearing in multiple kill-files.

  n

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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In <[email protected]> Steven D'Aprano 
 writes:

>On Wed, 26 Aug 2009 10:57:32 +, kj wrote:

>> Recursion!  One of the central concepts in the theory of
>> functions!  This is shown most clearly by the following elaboration of
>> my original example:
>> 
>> class Demo(object):
>> def fact_rec(n):
>> if n < 2:
>> return 1
>> else:
>> return n * fact_rec(n - 1)

>Why are you defining a method without a self parameter?

Because, as I've explained elsewhere, it is not a method: it's a
"helper" function, meant to be called only once, within the class
statement itself.

Well, this is not strictly true, because the function is recursive,
so it will also call itself a few times.  But still, all these
calls happen (loosely speaking) "within the class statement".

In fact the only reason to use a function for such initialization
work is when one needs recursion; otherwise there's no point in
defining a function that will only be invoked exactly once.

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


Re: ubuntu dist-packages

2009-08-26 Thread Jorgen Grahn
On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch
 wrote:
> Robin Becker wrote:
>
>> I was surprised a couple of days ago when trying to assist a colleage with
>> his python setup on a ubuntu 9.04 system.
>> 
>> We built our c-extensions and manually copied them into place, but
>> site-packages wasn't there. It seems that ubuntu now wants stuff to go
>> into lib/python2.6/dist-packages.
...

> I don't know much about the atrocities distributions commit to
> python-installations (ripping out distutils "because it's a developer-only
> thing",

Well, if you are thinking about Debian Linux, it's not as much
"ripping out" as "splitting into a separate package with a non-obvious
name". Annoying at times, but hardly an atrocity.

/Jorgen

-- 
  // Jorgen GrahnO  o   .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Move dictionary from instance to class level

2009-08-26 Thread Dave Angel

Frank Millman wrote:
"MRAB"  wrote in message 
news:[email protected]...
  

An alternative is:



class MyClass(object):
  

... def on_message_received(self, msg):
... try:
... getattr(self, "method_%d" % msg)()
... except AttributeError:
... raise Exception("Unknown message")
... def method_0(self):
... print 'in method_0'
... def method_1(self):
... print 'in method_1'
...


my_obj = MyClass()
my_obj.on_message_received(0)
  

in method_0


my_obj.on_message_received(1)
  

in method_1


my_obj.on_message_received(2)
  

Traceback (most recent call last):
  File "", line 1, in 
  File "", line 6, in on_message_received
Exception: Unknown message



I like the idea. Unfortunately my real-world situation is a little more 
complex than my simple example implied.


This is a more typical example -

(EVT_GETLOGIN
,EVT_LOGOUT
,EVT_GETMENUOPT
,EVT_GOTFOCUS
,EVT_LOSTFOCUS
,EVT_BUTTONCLICKED
,EVT_CHECKBOX
...
) = xrange(28)

method_dict = {}
method_dict[EVT_GETLOGIN] = onGetLogin
method_dict[EVT_LOGOUT] = onLogout
method_dict[EVT_GETMENUOPT] = onGetMenuOpt
method_dict[EVT_GOTFOCUS] = onGotFocus
method_dict[EVT_LOSTFOCUS] = onLostFocus
method_dict[EVT_BUTTONCLICKED] = onButtonClicked
method_dict[EVT_CHECKBOX] = onCheckBox

You can probably figure out from my method names what I am doing here - the 
messages are sent by a thin client (wxPython), and processed by a server.I 
am anticipating some "don't do that" responses, but I like the concept, and 
so far it is very fast and responsive, so I will pursue it for now.


Thanks for the input.

Frank


  
Any time I see multiple lists like that which have to stay in synch, I 
think code-smell.


Why not let the EVT's be passed as strings, and avoid the whole mapping 
to integers and mapping back detail?  And name the methods involved in a 
way that you can directly translate the string to the method name?


Barring that, make a single "structure" which lists the event names and 
method names in matched pairs, and derive whatever lists and 
dictionaries you actually need from that one structure.  And that 
structure should be shared between client and server code, perhaps as a 
text file that they both parse.  Or as a stream that's passed from one 
to the other during startup.  That way, consistency between them can be 
regulated (with version string in the file, for example)


DaveA

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


Re: Need help with Python scoping rules

2009-08-26 Thread Steven D'Aprano
On Wed, 26 Aug 2009 14:09:57 +, kj wrote:

>>1. One of the key aspects of Python's design is that attributes must be
>>accessed explicitly with dot notation.  Accessing class scopes from
>>nested functions would (seemingly) allow access to class attributes
>>without the dotted notation.  Therefore it is not allowed.
> 
> It would be trivial to define a keyword (e.g. this, or if you prefer,
> __this__), valid only within a class statement, and that the interpreter
> would recognize as "the current class", even before this class is full
> defined.

Python doesn't treat the addition of new keywords, and the corresponding 
breakage of code which used that word as a normal name, as "trivial" -- 
the Python dev team takes their responsibilities to not casually break 
people's code seriously. That pretty much rules out "this", although it 
would allow "__this__".

However, what's your use-case?

class Demo(object):
def f(n):
return n+1
x = f(10)


is a poorly written class, because the user will expect to do this:

instance = Demo()
assert instance.c == 11  # suceeds
instance.f(10) == 11  # fails


Since the function f doesn't refer to a Demo instance, or the Demo class, 
why do you put it inside the Demo class? It doesn't belong there, it 
belongs in the global (module) scope. Move it out, and your problem goes 
away.

The only use-case I can think of for __this__ is the following:

class Example(object):
@staticmethod
def rec(n):
if n < 2: return "x"
return "x" + __this__.rec(n/2)

Example.rec(15)


but again, why include rec() in the class if it doesn't actually have 
anything to do with the class or the instance? Or why make it a 
staticmethod? Just make it a class method:

class Example(object):
@classmethod
def rec(cls, n):
if n < 2: return "x"
return "x" + cls.rec(n/2)



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


Re: Need help with Python scoping rules

2009-08-26 Thread Carl Banks
On Aug 26, 8:36 am, kj  wrote:
> In <1bf83a7e-f9eb-46ff-84fe-cf42d9608...@j21g2000yqe.googlegroups.com> Carl 
> Banks  writes:
>
> >Yeah, it's a little surprising that you can't access class scope from
> >a function, but that has nothing to do with encapsulation.
>
> It does: it thwarts encapsulation.  The helper function in my
> example is one that clearly rightfully belongs nowhere else than
> the class itself, i.e. encapsulated within the class. It is only
> this silly prohibition against recursive functions in a class
> statement that forces one to put it outside the class statement.

Oh well, I guess that sucks for you.


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


Re: ubuntu dist-packages

2009-08-26 Thread Robin Becker

Jorgen Grahn wrote:

On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch



Well, if you are thinking about Debian Linux, it's not as much
"ripping out" as "splitting into a separate package with a non-obvious
name". Annoying at times, but hardly an atrocity.
so where is the official place for user installed stuff on ubuntu/debian ie will 
there be dist-packages and site-packages.

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


Re: Python Processor

2009-08-26 Thread Terry Reedy

manish wrote:

Hi,

I am also wondering about how to implement a soft core reconfigurable 
processor in a FPGA

which would directly execute the compiled python bytecode.

I am trying to understand the bytecode format but apart from 
http://docs.python.org/library/dis.html

there is hardly any documentation on the python bytecodes.


Contrary to the ancient and, I believe, obsolete text in the 
documentation, there is no 'python bytecode'. Dis is based on CPython 
bytecode. Jython uses Java bytecode. IronPython uses, I believe, 
Microsoft clr bytecode. Object code compilers do not use bytecode.


Before going through the one of the existing VM implementations, i want 
to know if there is there any informaition
available which elaborates on the structure of the bytecodes. Like 
details regarding co_names, co_cellvars,
co_freevars, the concept of frames, global, local, objects, functions 
etc with respect to the bytecode.


These are mostly version-specific Cpython implementation details.

tjr

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


Re: Need help with Python scoping rules

2009-08-26 Thread Steven D'Aprano
On Wed, 26 Aug 2009 15:36:35 +, kj wrote:

> In <1bf83a7e-f9eb-46ff-84fe-cf42d9608...@j21g2000yqe.googlegroups.com>
> Carl Banks  writes:
> 
>>Yeah, it's a little surprising that you can't access class scope from a
>>function, but that has nothing to do with encapsulation.
> 
> It does: it thwarts encapsulation.  The helper function in my example is
> one that clearly rightfully belongs nowhere else than the class itself,
> i.e. encapsulated within the class.

There's nothing "clearly" about it. 

This helper function doesn't reference the class, or any instance of the 
class. Why should it be encapsulated in the class? It's not *part* of the 
class, it shouldn't be *inside* the class.

Look at it this way: classes are made from building blocks. Just because 
a building block ends up in a class, doesn't mean the function that makes 
the building block has to be inside the class too.

It's an accident of Python's execution model that a single function call 
*sometimes* works as you expect inside the class statement:

class Demo:
def f():
return 2
def g():
return f()+1
x = f()  # works
y = g()  # fails


As you can see, the problem is not because of recursion, but because the 
class scope is not inserted into the function scope. As I said earlier, 
your problem isn't too little class encapsulation, but too much: the 
class scope doesn't leak into the function scope.

Python could, of course, behave the way you want, but it would lead to 
some odd interactions:

class Weird(object):
x = 1
def __init__(self):
self.y = 2
def test(self):
print self.x  # refers to attribute x with value 1
print x   # refers to attribute x with value 1
print self.y  # refers to attribute y with value 2
print y   # refers to global y

In existing Python, both x and y will refer to globals, because it's 
considered more important for all attribute access to be consistently 
explicit than to insert the class scope into the function scope. This 
isn't a design flaw, or a bug, it's a feature. Yes, it makes it hard for 
you to solve your problem the way you want to solve it, but it doesn't 
stop you from solving your problem. The module is encapsulation enough.



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


Re: quantiles of a student distribution

2009-08-26 Thread Colin J. Williams

Pierre wrote:

Hello...

Do you know how I can calculate the quantiles of a student
distribution in pyhton ?

Thanks
You might look at: 
http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/special.html


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


Re: Object's nesting scope

2009-08-26 Thread zaur
On 26 авг, 17:13, "Diez B. Roggisch"  wrote:
> Whom am we to judge? Sure if you propose this, you have some usecases in
> mind - how about you present these

Ok. Here is a use case: object initialization.

For example,

person = Person():
  name = "john"
  age = 30
  address = Address():
 street = "Green Street"
 no = 12

vs.

person = Person()
person.name = "john"
person.age = 30
address = person.address = Address()
address.street = "Green Street"
address.no = 12

In this example any assignment is an equivalence of setting
attribute's address of the parent object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on the Web

2009-08-26 Thread Phil
Thanks to everybody. I believe I am understanding things better.

I have looked at the links that have been provided, although I have
seen most of them in the past month or so that I've been looking into
this stuff. I do agree with most of the things Armin stated in that
NIH post. I agree with everybody in this thread so far. If I wanted to
write an application, I would use an existing framework and wait for
it to be ported to 3.x. However, I do not have the need to write a web
application at this time, and creating blogs or other applications I
do not need for fun is getting old.

My reasoning for working on my own instead of following the 'NIH'
concept or contributing to an existing framework is because I have
experimented with many existing frameworks and I have figured out what
I like/dislike, and have envisioned my own design that I feel would
work potentially better for others, or at least newcomers. Things like
this are fun for me, and I do not mind the challenge. I don't want to
pollute the web with (sigh) 'another framework', but it would be fun
for me to write it and get some feedback. I would love for people like
you, Armin, and others who take a look at the various frameworks that
pop up seemingly every day, to look at my (hypothetical) framework and
just rip it apart with (constructive) criticism. That is just the way
I do things, whether the community agrees with it or not. The reason I
was asking about Python 3 on the web was just because I like some of
the changes that have been made, and would like to use it for my
framework. That is when I realized that I was absolutely clueless
about the details of how Python, or any language, works on the web.

Graham, regarding number 3 in your list of ways to host WSGI: I
haven't really looked into mod_wsgi at all, but basically it sounds
like the web server would be running this embedded module. That module
would then serve the function of both FCGI and the 'WSGI Server' in my
diagram? That actually sounds really neat. Unfortunately I missed this
because I've been hooked on lighttpd, as the minimalist I am.

Here are the things I am still confused with:

1) Why do I not want to consider running Python on the web with FCGI,
without WSGI? You said 'no' straight up, no questions asked. I would
imagine that there is a good reason of course, as you've been in this
field for a long time. I just feel more comfortable understanding why.
>From my understanding, the only real purpose of WSGI is to remain
independent of FCGI/SCGI/CGI/AJP (whatever that is) and the web server
it is run on. However, 99.9% of the discussion I see with Python on
the web is around FCGI. So for example, lets say everybody used FCGI.
All that would be left to deal with is web server independence. Now
this is what I don't get, I thought that FCGI itself was supposed to
be the protocol that deals with web server independence. Maybe I just
need to re-read entire WSGI specification to understand, along with
all the details of FCGI. There are just so many details regarding web
servers, FCGI, and WSGI that it is hard to absorb it all and see how
it works together. That is why I tried to create the diagram, but it
doesn't provide enough details. And those are the details I am
missing. I've been trying to find a simple diagram or explaination of
the process a request takes to make a response, from HTTP all the way
up to the application, to the the user.

2) In the development stack, the 'WSGI Server' seems to take on the
role of the web server (dealing with HTTP specification), skips FCGI,
and deals with the WSGI specification. Then, the 'WSGI Server' in the
production stack (eg. Flup, CherryPy, etc) only deals with FCGI and
WSGI specification, because the HTTP is already taken care of by the
web server?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object's nesting scope

2009-08-26 Thread Rami Chowdhury

person = Person():
  name = "john"
  age = 30
  address = Address():
 street = "Green Street"
 no = 12



Can you clarify what you mean? Would that define a Person class, and an  
Address class?


If you are expecting those classes to be already defined, please bear in  
mind that if you want, you can do this:



> > class Person(object):

def __init__(self, name='Nemo', age=0, address=None):
self.name = name
self.age = age
self.address = address


> > class Address(object):

def __init__(self, street=None, no=None):
self.street = street
self.no = no


> > otherperson = Person(

 name = 'Bob',
 age = 26,
 address = Address(
 street = 'Blue Street',
 no = 1
 )
 )







On Wed, 26 Aug 2009 09:49:48 -0700, zaur  wrote:


On 26 авг, 17:13, "Diez B. Roggisch"  wrote:

Whom am we to judge? Sure if you propose this, you have some usecases in
mind - how about you present these


Ok. Here is a use case: object initialization.

For example,

person = Person():
  name = "john"
  age = 30
  address = Address():
 street = "Green Street"
 no = 12

vs.

person = Person()
person.name = "john"
person.age = 30
address = person.address = Address()
address.street = "Green Street"
address.no = 12

In this example any assignment is an equivalence of setting
attribute's address of the parent object.




--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with Python scoping rules

2009-08-26 Thread Ulrich Eckhardt
kj wrote:
> class Demo(object):
> def fact_iter(n):
> ret = 1
> for i in range(1, n + 1):
> ret *= i
> return ret
> 
> def fact_rec(n):
> if n < 2:
> return 1
> else:
> return n * fact_rec(n - 1)
> 
> classvar1 = fact_iter(5)
> classvar2 = fact_rec(5)
> 
> 
> In the initialization of classvar1, fact_iter is invoked without
> any problem even though the class is not yet created: no need to
> qualify it with the name of the class.  This is completely inconsistent
> with the requirement that fact_rec be so qualified when invoked
> within fact_rec.

Let me take a shot at explaining this, maybe it helps that I'm mostly a C++
guy


Firstly, if Python sees a name, it looks up that name first in the local
scope and then in the global scope. This is very simple (especially
compared to C++ when adding ADL there...), but it is something most people
can live with. So, even inside a class function (static or member), you
have to qualify a function call like 'ClassName.function_name', because
neither is 'function_name' a local nor is it a global.

Secondly, and that is due to the very dynamic nature of Python's types, the
class doesn't exist until its definition is finished. Therefore, any
attempt (directly or indirectly) to access a class member will usually fail
before that time. The exception is that inside the class definition you can
access the members directly, because they are in the same scope (access to
locals). Note that the scope already seems to exist but that it is not yet
available under any name! Looking at your example, you can not
write 'classvar1 = Demo.fact_iter(42)', because the lookup of 'Demo' will
fail.

Now, what actually causes problems is that 'fact_rec' is not universally
accessible until class 'Demo' is fully defined, but you need this in order
to fully define it. Here comes a drawback of the dynamic nature of Python,
that the declaration phase (compiling) is not separate from the execution.

I fully agree that this case is rather vexing to my (and obviously your)
biased brain. I wouldn't call this a bug before fully understanding why
e.g. you can not access a class before its definition is finished. I think
someone mentioned one or two PEPs, which are the design documents that
explain Python including the rationale, I'd use that as a starting point.


Suggestion: someone mentioned that you should make the function a normal
function. You can mark it as private using an underscore as prefix. If you
want to make it foolproof, you could even delete ("del fact_rec") the
function after use. Other alternatives would be to put it into a separate
baseclass, use a local function as implementation or to add the class
attributes after defining the class. Neither of these provide the 'perfect'
encapsulation of things in a class that you might be used to from e.g.
Java, but they have proven to be very useful nonetheless.


Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: How does the file.seek() work ?

2009-08-26 Thread gert
On Aug 26, 12:46 am, Graham Dumpleton 
wrote:
> On Aug 25, 5:37 am, Tim Chase  wrote:
>
> > > I want the file pointer set to 100 and overwrite everything from there
> > [snip]
> > > def application(environ, response):
> > >     query=os.path.join(os.path.dirname(__file__),'teemp')
> > >     range=environ.get('HTTP_RANGE','bytes=0-').replace
> > > ('bytes=','').split(',')
> > >     offset=[]
> > >     for r in range: offset.append(r.split('-'))
> > >     with open(query,'w+') as f:
> > >          f.seek(int(offset[0][0]))
> > >          while True:
> > >              chunk=environ['wsgi.input'].read(8192).decode('latin1')
> > >              if not chunk: break
> > >              f.write(chunk)
> > >     f=open(query)
> > >     l=str(os.fstat(f.fileno()).st_size)
> > >     response('200 OK', [('Content-Type', 'text/plain'), ('Content-
> > > Length', str(len(l)))])
> > >     return [l]
>
> > A couple items of note:
>
> > - you don't open the file in binary mode -- seek is more reliable
> > in binary mode :)
>
> If my memory is right, if file is opened in binary mode, also wouldn't
> need to be decoding the WSGI input stream as latin-1 to get a string.
> Instead can just deal with bytes and write bytes to file.
>
> Graham
>
> > - if you want to lop off the rest of the file, use f.truncate()
>
> > An example:
>
> > # create the initial file
> >  >>> f = file('zzz.zzz', 'wb+')
> >  >>> f.write('abcdefghijklmnop')
> >  >>> f.close()
>
> >  >>> f = file('zzz.zzz', 'ab+')
> >  >>> f.read() # show the existing content
> > 'abcdefghijklmnop'
> >  >>> f.seek(5) # seek to the desired offset
> >  >>> f.truncate() # throw away everything after here
> >  >>> f.write('zyx') # write the new data at pos=5
> >  >>> f.close()
>
> > # demonstrate that it worked
> >  >>> f = file('zzz.zzz', 'rb')
> >  >>> f.read()
> > 'abcdezyx'
> >  >>> f.close()
>
> > > also why must I open the file a second time to know how big it is ?
>
> > Likely the output has been buffered.  You can try using
>
> >    f.flush() # write all the data to the disk first
> >    size = os.fstat(f.fileno()).st_size
>
> > which seems to do the trick for me.
> > -tkc
>

Works thanks

curl -C 10 -T upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi
--header "Transfer-Encoding: chunked" -v

import os

def application(environ, response):
#query=environ.get['QUERY_STRING']
#print (query, file=environ['wsgi.errors'])
query=os.path.join(os.path.dirname(__file__),'teemp')
range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes
','').split('/')[0].split(',')
offset=[]
for r in range: offset.append(r.split('-'))
with open(query,'rb+') as f:
 f.seek(int(offset[0][0]))
 if environ['REQUEST_METHOD']=='PUT':
 f.truncate()
 while True:
 chunk=environ['wsgi.input'].read(8192)
 if not chunk: break
 f.write(chunk)
 f.flush()
 l=str(os.fstat(f.fileno()).st_size)
response('200 OK', [('Content-Type', 'text/plain'), ('Content-
Length', str(len(l)))])
return [l]



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


Re: Need help with Python scoping rules

2009-08-26 Thread Terry Reedy

kj wrote:

In <[email protected]> "Diez B. Roggisch"  
writes:


Classes are not scopes.


Classes are objects.  In particular, they are (by default) instances of 
class 'type'. Unless 'scopes' were instances of some other metaclass, 
the statement has to be true. I understand 'scope' as referring to a 
section of code, as opposed to a runtime object.


Class statements introduce a new local namespace used to define the 
class.  Whether one considers that as introducing a new 'scope' depends, 
I suppose, on one's exact definition of scope.



This looks to me like a major wart, on two counts.


It is a 'wart' that a Python object is not a 'scope', whatever that is 
to you? I have trouble comprehending that claim.



First, one of the goals of OO is encapsulation, not only at the
level of instances, but also at the level of classes.  Your comment
suggests that Python does not fully support class-level encapsulation.


I really do not see how your claim follows from the comment. The irony 
of your 'two counts' is that the example of 'count 2' fails precisely 
because of the encapsulation that you claim does not exist as 'count 1'.



Second, my example shows that Python puts some peculiar restrictions
on recursion.


I claim it does not. Name-based recursion inherently requires that a 
function be able to access itself by name at the time it is called. This 
can be a bit tricky, especially in a language with dynamic rather than 
static name binding and resolution, as it requires that code within the 
function be able to access a scope outside itself in which the function 
name is defined. In other words, it requires that function code *not* be 
completely encapsulated. It also require that the appropriate name be 
used when there is one. Neither of these is a 'peculiar restriction' 
imposed by Python.



class Demo(object):
def fact_rec(n):
if n < 2:
return 1
else:
return n * fact_rec(n - 1)


This function is just a function. It is not an instance method. It is 
not even a class method. It does not belong here and should not be here.


If you insist on putting it where it does not belong, then you have to 
call it by a name that works.  If you only call it after the class 
statement has finished, then 'Demo.fact_rec' works, as I believe someone 
else pointed out.


If you want to call the function during class creation, before (in this 
case) Demo exists, then binding it to a local name works. With 3.1


class Demo:
   def f1(n):
  if n < 2: return 1
  else: return n * Demo.f1(n - 1)

   def f2(n,f):
  if n < 2: return 1
  else: return n * f(n - 1, f)

   cvar = f2(5, f2)

print(Demo.f1(5), Demo.cvar, Demo.f2(5,Demo.f2))

# prints
>>>
120 120 120


Recursive functions should be OK wherever functions are OK.


Iteration can and has been viewed as within-frame recursion. When 
iterative rather than recursive syntax is used, the naming issue is

avoided.


Is there any good reason (from the point of view of Python's overall
design) for not fixing this?


After reading the above, what, if anything, do you think still needs to 
be fixed?


Before 2.2, Python functions were more encapsulated than they are today 
in that they could only access local and global namespaces but not outer 
function namespaces.  It would be possible to further de-encapsulate 
them by giving them direct access to lexically surrounding class 
namespaces, but this would increase the problem of name clashes without 
solving any real problems in proper Python code. It could also break the 
intentional design principle that function code should mean the same 
thing whether placed within or without a class statement. This principle 
allows functions to be added to existing classes as attributes and work 
as methods that same as if they had been defined with the class.


Terry Jan Reedy

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


Re: Numeric literals in other than base 10 - was Annoying octal notation

2009-08-26 Thread Mensanator
On Aug 26, 9:58 am, Steven D'Aprano  wrote:
> On Tue, 25 Aug 2009 11:45:28 -0700, Mensanator wrote:
> > On Aug 25, 9:14 am, Steven D'Aprano  > cybersource.com.au> wrote:
> >> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote:
> >> >> If you want your data file to have values entered in hex, or oct, or
> >> >> even unary (1=one, 11=two, 111=three, =four...) you can.
>
> >> > Unary? I think you'll find that Standard Positional Number Systems
> >> > are not defined for radix 1.
>
> >> Of course not. But unary isn't a positional number system. It's a tally
> >> system, like my example above shows. Roman numerals are another tally
> >> system. Like Roman numerals, the disadvantages of unary are that you
> >> can't represent negative numbers, zero, or fractions, and anything but
> >> addition and subtraction is difficult. But if you want to use it,
> >> perhaps out of a sense of sadism towards your users, it's easy:
> [...]
> > But without insignificant leading 0's, I fail to see the relevance of
> > unary to this discussion.
>
> It was just an example of how you can use numeric data in any format, no
> matter how obscure, weird or difficult, you can use it by passing it
> through an appropriate converter. You don't need compiler support for
> user-supplied data, you just write your own function.

Ok, no problem with that.

>
> As for insignificant leading zeroes, such a thing is meaningless in a
> base-1 tally system. Zero is the absence of a tally mark.
>
> > And what would you call a tally system of
> > radix 2? Certainly not binary.
>
> "Radix" isn't the correct term, because radix doesn't apply to tally
> counting systems. I'd accept "base 2", in the sense that the tally is
> based on two different marks.

I thought the two were equivalent, but maybe I'm wrong. Anyway, that's
a minor quibble.

> We do something similar when we mark four
> tally lines, then for five we mark a diagonal line through the previous
> four. So by analogy a base-2 tally could go:
>
> /     one
> X     two
> X/    three
> XX    four
> XX/   five
> XXX   six
> XXX/  seven

Sure, as long as you're consistent, there's no problem.

>
> But I certainly wouldn't call it "binary", for fear of confusion with
> radix-2 binary.

That's my point. Since the common usage of "binary" is for
Standard Positional Number System of Radix 2, it follows
that "unary" is the common usage for Standard Positional
Number System of Radix 1. That's VERY confusing since such
a system is undefined. Remember, common usage does not
necessarily properly define things. Saying simply "unary"
sounds like you're extending common usage beyond its proper
boundaries.

> Possibly binary-tally, for lack of a better term.

Then possibly unary-tally would be better than unary.
Tally systems being much less common require a less
common terminology to avoid confusion.

>
> --
> Steven

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


SimpleXMLRPCServer timeout issue

2009-08-26 Thread Mahi Haile
Hi all,
I have an XML-RPC server running that is using SimpleXMLRPCServer, and I am
trying to send a relatively large file on a poor connection [simulated low
bandwidth, high latency]. The file is simply the return value of a function
call available on the server.
However, sometime in to the transfer, I get a timeout, seemingly regardless
of what I do. The server is initiated as follows:

s = SimpleXMLRPCServer((HOST, PORT), requestHandler = RequestHandler)
s.timeout = 10  #I tried setting this to None, and also a higher number

And the exception I get is:

Traceback (most recent call last):
  File "/python2.5/SocketServer.py", line 464, in process_request_thread
self.finish_request(request, client_address)
  File "/python2.5/SocketServer.py", line 254, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "/python2.5/SocketServer.py", line 522, in __init__
self.handle()
  File "/python2.5/BaseHTTPServer.py", line 316, in handle
self.handle_one_request()
  File "python2.5/BaseHTTPServer.py", line 310, in handle_one_request
method()
  File "/python2.5/SimpleXMLRPCServer.py", line 481, in do_POST
self.wfile.write(response)
  File "/python2.5/socket.py", line 262, in write
self.flush()
  File "/python2.5/socket.py", line 249, in flush
self._sock.sendall(buffer)
timeout: timed out

Googling resulted in similar questions asked in the CherryPy forums, and the
general suggestions seem to be to use a streaming transfer, using yield
rather than return.
Do you know how I go about solving when using the SimpleXMLRPCServer? For
what it is worth, I am running the server on Mac OS X.

Thank you,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with Python scoping rules

2009-08-26 Thread Ethan Furman

kj wrote:



I have many years of programming experience, and a few languages,
under my belt, but still Python scoping rules remain mysterious to
me.  (In fact, Python's scoping behavior is the main reason I gave
up several earlier attempts to learn Python.)

Here's a toy example illustrating what I mean.  It's a simplification
of a real-life coding situation, in which I need to initialize a
"private" class variable by using a recursive helper function.

class Demo(object):
def fact(n):
if n < 2:
return 1
else:
return n * fact(n - 1)

_classvar = fact(5)


As has been pretty thoroughly discussed, the issue here is not 
recursion, but name lookup.


Going back through the archives I found Arnaud's post with this decorator:

def bindfunc(f):
def boundf(*args, **kwargs):
return f(boundf, *args, **kwargs)
return boundf

If you use it on your fact function like so...

class Demo(object):
@bindfunc
def fact(recurse, n)# recurse can be any name you like
if n < 2:
return 1
else:
return n * recurse(n-1)
_classvar = fact(5)
del fact# no longer needed, and won't work
# once class is created

This should do as you want.

As a side note, if you're going to bother asking questions on this list, 
you really should try to understand the answers.  I won't gripe at you 
too much, though, 'cause I learned a lot from the many responses given 
due to your refusal to do so.  ;-)


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


Re: Object's nesting scope

2009-08-26 Thread zaur
On 26 авг, 21:11, "Rami Chowdhury"  wrote:
> > person = Person():
> >   name = "john"
> >   age = 30
> >   address = Address():
> >      street = "Green Street"
> >      no = 12
>
> Can you clarify what you mean? Would that define a Person class, and an  
> Address class?
I suppose that someone already define classes Person ans Address.
For example, in this stupid way in a foreign module:

class Person(object):
   pass

class Address(object):
   pass

and the following statements

person = Person():
   name = "john"
   age = 30
   address = Address():
  street = "Green Street"
  no = 12

are constructing an instance as follows:

person = Person()
person.name = "john"
person.age = 30
address = person.address = Address()
address.street = "Green Street"
address.no = 12

> If you are expecting those classes to be already defined, please bear in  
> mind that if you want, you can do this:
>
> > > > class Person(object):
>
>         def __init__(self, name='Nemo', age=0, address=None):
>                 self.name = name
>                 self.age = age
>                 self.address = address
>
> > > > class Address(object):
>
>         def __init__(self, street=None, no=None):
>                 self.street = street
>                 self.no = no
>
> > > > otherperson = Person(
>
>                      name = 'Bob',
>                      age = 26,
>                      address = Address(
>                              street = 'Blue Street',
>                              no = 1
>                              )
>                      )
>
Yes, that's right. I aware about this way of instance initialization.

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


Re: ubuntu dist-packages

2009-08-26 Thread Florian Diesch
Robin Becker  writes:

> I was surprised a couple of days ago when trying to assist a colleage
> with his python setup on a ubuntu 9.04 system.
>
> We built our c-extensions and manually copied them into place, but
> site-packages wasn't there. It seems that ubuntu now wants stuff to go
> into lib/python2.6/dist-packages.
>
> What is the relation between dist-packages/site-packages if any? Is
> this just a name change or is there some other problem being
> addressed?
>
> For developers is it best just to create one's own private
> installations from the original tarballs?

>From /usr/lib/python2.6/site.py:

,
| For Debian and derivatives, this sys.path is augmented with directories
| for packages distributed within the distribution. Local addons go
| into /usr/local/lib/python/dist-packages, Debian addons
| install into /usr/{lib,share}/python/dist-packages.
| /usr/lib/python/site-packages is not used.
`




   Florian
-- 

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


Re: Need help with Python scoping rules

2009-08-26 Thread kj
In <[email protected]> Steven D'Aprano 
 writes:

>http://docs.python.org/reference/executionmodel.html

>It is also discussed in the PEP introducing nested scopes to Python:

>http://www.python.org/dev/peps/pep-0227/

>It's even eluded to in the tutorial:

>http://docs.python.org/tutorial/classes.html

Thanks!

kynn

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


Re: Python Processor

2009-08-26 Thread John Nagle

Terry Reedy wrote:

manish wrote:

Hi,

I am also wondering about how to implement a soft core reconfigurable 
processor in a FPGA

which would directly execute the compiled python bytecode.


  It probably wouldn't help much.  CPython's performance problems
come from excessive dictionary lookups, not from instruction decode.

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


Re: quantiles of a student distribution

2009-08-26 Thread Robert Kern

On 2009-08-26 11:49 AM, Colin J. Williams wrote:

Pierre wrote:

Hello...

Do you know how I can calculate the quantiles of a student
distribution in pyhton ?

Thanks

You might look at:
http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/special.html


[Please pardon the piggybacking. I have not gotten the original, yet.]

Using scipy:

In [1]: from scipy import stats

In [2]: import numpy as np

In [3]: x = np.linspace(-1.0, 1.0, 21)

In [4]: x
Out[4]:
array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1,  0. ,
0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])

In [5]: ndof = 10

In [6]: stats.t.cdf(x, ndof)
Out[6]:
array([ 0.17044657,  0.19463963,  0.22115021,  0.24994379,  0.28092759,
0.3139468 ,  0.3487837 ,  0.3851603 ,  0.4227446 ,  0.46116036,
0.5   ,  0.53883964,  0.5772554 ,  0.6148397 ,  0.6512163 ,
0.6860532 ,  0.71907241,  0.75005621,  0.77884979,  0.80536037,
0.82955343])


--
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


ANN: ActivePython 3.1.1.2 is now available

2009-08-26 Thread Sridhar Ratnakumar

I'm happy to announce that ActivePython 3.1.1.2 is now available for
download from:

  http://www.activestate.com/activepython/python3/

This is a patch release that updates ActivePython to core Python 3.1.1
We recommend that you try 2.6 version first. See the release notes for
full details:

  http://docs.activestate.com/activepython/3.1/relnotes.html


What is ActivePython?
-

ActivePython is ActiveState's binary distribution of Python. Builds
for Windows, Mac OS X, Linux, HP-UX and AIX are made freely available.

ActivePython includes the Python core and the many core extensions:
zlib and bzip2 for data compression, the Berkeley DB (bsddb) and
SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS
support, the Tix GUI widgets for Tkinter, ElementTree for XML
processing, ctypes (on supported platforms) for low-level library
access, and others. The Windows distribution ships with PyWin32 -- a
suite of Windows tools developed by Mark Hammond, including bindings
to the Win32 API and Windows COM. See this page for full details:

  http://docs.activestate.com/activepython/3.1/whatsincluded.html

As well, ActivePython ships with a wealth of documentation for both
new and experienced Python programmers. In addition to the core Python
docs, ActivePython includes the "What's New in Python" series, "Dive
into Python", the Python FAQs & HOWTOs, and the Python Enhancement
Proposals (PEPs).

An online version of the docs can be found here:

  http://docs.activestate.com/activepython/

We would welcome any and all feedback to:

  [email protected]

Please file bugs against ActivePython at:

  http://bugs.activestate.com/query.cgi?set_product=ActivePython


On what platforms does ActivePython run?


ActivePython includes installers for the following platforms:

- Windows/x86
- Windows/x64 (aka "AMD64")
- Mac OS X
- Linux/x86
- Linux/x86_64 (aka "AMD64")
- Solaris/SPARC
- Solaris/x86
- HP-UX/PA-RISC
- AIX/PowerPC
- AIX/PowerPC64


Extra Bits
--

ActivePython releases also include the following:

- ActivePythonXY.chm: An MS compiled help collection of the full
ActivePython documentation set. Linux users of applications such as
xCHM might find this useful. This package is installed by default on
Windows.

Extra bits are available from:

  http://downloads.activestate.com/ActivePython/etc/


Thanks, and enjoy!

The Python Team

--
Sridhar Ratnakumar
sridharr at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]

2009-08-26 Thread Evan Driscoll
On Aug 26, 10:15 am, Carl Banks  wrote:
> Well, it wouldn't be a "can I rebind a variable using a with-
> statement" thread if someone didn't post a solution that they thought
> worked, but didn't test it on local variables.

I'm not going to deny it was pretty stupid... though in my defense,
I'm new at more that trivial Python coding and don't have the Python
scoping rules and such ingrained in my mind yet. :-)

Evan

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


Re: Object's nesting scope

2009-08-26 Thread MRAB

zaur wrote:

On 26 авг, 21:11, "Rami Chowdhury"  wrote:

person = Person():
  name = "john"
  age = 30
  address = Address():
 street = "Green Street"
 no = 12
Can you clarify what you mean? Would that define a Person class, and an  
Address class?

I suppose that someone already define classes Person ans Address.
For example, in this stupid way in a foreign module:

class Person(object):
   pass

class Address(object):
   pass

and the following statements

person = Person():
   name = "john"
   age = 30
   address = Address():
  street = "Green Street"
  no = 12

are constructing an instance as follows:

person = Person()
person.name = "john"
person.age = 30
address = person.address = Address()
address.street = "Green Street"
address.no = 12


[snip]

Create factory functions:

def new_address(**kwargs):
address = Address()
address.__dict__.update(kwargs)
return address

def new_person(**kwargs):
person = Person()
person.__dict__.update(kwargs)
return person

person = new_person(name="john", age=30, 
address=new_address(street="Green Street", no=12))


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


Re: pygtk - What is the best way to change the mouse pointer

2009-08-26 Thread MRAB

Ido Levy wrote:

Hello All,

I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( 
let's assume widget in the example below is its instance )
When the user select one of the values from the gtk.ComboBoxEntry I need 
to run some calculations that takes a few seconds.
In order to reflect calculation time to the user I want to switch the 
mouse pointer to an hour glass and back to arrow what it finish the 
calculation.


I use the following code but it doesn't seems to work in a deterministic 
way. From time to time it skips the last line and keep the mouse pointer 
as an hour glass.


watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
widget.window.set_cursor(watch)

calculation code

widget.window.set_cursor(None)

I would appreciate your advice on the right way to implement this.


Could the calculation code be raising an exception? Try adding some
logging to see whether the last lien is actually being called. You could
also use a try...finally... block to ensure that the last line is
called:

watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
widget.window.set_cursor(watch)
try:
calculation code
finally:
widget.window.set_cursor(None)

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


Re: Need help with Python scoping rules

2009-08-26 Thread Dave Angel

Carl Banks wrote:

On Aug 26, 8:13 am, Dave Angel  wrote:
  

You can probably work around this by replacing the staticmethod
decorator with an equivalent function call:.

class Demo9(object):
def fact(n):
if n < 2:
return 1
else:
return n * Demo.fact(n - 1)

_classvar =act(5)
fact =taticmethod(fact)

print Demo9._classvar
xx =emo9()
print xx.fact(6)
print Demo9.fact(8)



This won't work normally.  It only worked for you because you made a
typo.


Carl Banks

  
Sorry about the typo.  I was trying out several different versions of 
the class in the same module, and forgot to include to change Demo to 
Demo9 in the recursive call.


I didn't like that approach anyway, as it smacked of taking advantage of 
some implementation accident.  The other approaches are more 
straightforward.



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


  1   2   >