Re: Write bits in file

2008-05-23 Thread Andrew Lee

Tim Roberts wrote:

Monica Leko <[EMAIL PROTECTED]> wrote:

I have a specific format and I need binary representation.  Does
Python have some built-in function which will, for instance, represent
number 15 in exactly 10 bits?


For the record, I'd like to point out that even C cannot do this.  You need
to use shifting and masking to produce a stream of 8-bit bytes, or to
extract your values from a stream of 8-bit bytes.



H, bitfields are exactly non-aligned bits in a structure and are 
part of ANSI C.  Although C gives no guarantee of the ordering of fields 
within machine words ... so bitfieds are of limited use in portable 
programs unless they are 0-initialized.


IIRC, Huffman code uses arbitrary length bit strings and is the basis of 
many compression algorithms.





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


Re: Producing multiple items in a list comprehension

2008-05-23 Thread Peter Otten
Yves Dorfsman wrote:

> Peter Otten <[EMAIL PROTECTED]> wrote:
> 
>> > A slightly similar problem: If I want to "merge," say, list1=[1,2,3]
>> > with list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way
>> > with "zip" to do so?
> 
>> >>> items = [None] * 6
>> >>> items[::2] = 1,2,3
>> >>> items[1::2] = 4,5,6
>> >>> items
>> [1, 4, 2, 5, 3, 6]
> 
> My problem with this solution is that you depend on knowing how many
> elements you have in each list ahead of time. 

$ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100; from operator import
add" "list(reduce(add, zip(a, b)))"
1000 loops, best of 3: 637 usec per loop

$ python -m timeit -s"a = [1,2,3]*100; b =
[4,5,6]*100" "items=[None]*(2*len(a)); items[::2] = a; items[1::2] = b"
1 loops, best of 3: 23.4 usec per loop

The speed gain is significant. Why should I throw away useful information if
I have it? I'd even be willing to convert one arbitrary iterable to a list
to get the length information.

$ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100" "aa = list(a);
items=[None]*(2*len(aa)); items[::2] = aa; items[1::2] = b"
1 loops, best of 3: 29.5 usec per loop

> Assuming that both list 
> are of the same length, then, I find the following more elegant:
> 
> list1=[1,2,3]
> list2=[4,5,6]
> 
> reduce(lambda x, y: x+y, zip(list1, list2))
> 
> of course, zip creates tuples, so you end up with a tuple, therefore if
> you need for your solution to be a list:
> list(reduce(lambda x, y: x+y, zip(list1, list2)))

I'd rather use a plain old for-loop:

>>> from itertools import izip
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> items = []
>>> for chunk in izip(a, b):
... items.extend(chunk)
...
>>> items
[1, 4, 2, 5, 3, 6]

$ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100; from itertools
import izip" "items = []
> for chunk in izip(a, b): items.extend(chunk)"
1000 loops, best of 3: 242 usec per loop

$ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100; from itertools
import izip" "items = []; extend = items.extend
for chunk in izip(a, b): extend(chunk)"
1 loops, best of 3: 70.9 usec per loop

> reduce(lambda x, y: x+y, list(zip(list1, list2)) )

list(zip(...)) has no effect here. Possible fixes

>>> reduce(lambda x, y: x + list(y), zip(list1, list2), [])
[1, 4, 2, 5, 3, 6]

>>> reduce(lambda x, y: x.extend(y) or x, zip(list1, list2), [])
[1, 4, 2, 5, 3, 6]

$ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100" "reduce(lambda x, y:
x.extend(y) or x, zip(a, b), [])"
1000 loops, best of 3: 368 usec per loop

are more complicated than elegant. Not recommended.

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


Re: can python do some kernel stuff?

2008-05-23 Thread Andrew Lee

Jimmy wrote:

Hi to all

python now has grown to a versatile language that can
accomplish tasks for many different purposes. However,
AFAIK, little is known about its ability of kernel coding.

So I am wondering if python can do some kernel coding that
used to be the private garden of C/C++. For example, can python
intercept the input of keyboard on a system level? someone told me
it's a kernel thing, isn't it?



http://wiki.python.org/moin/elmer

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


error using all()/numpy [TypeError: cannot perform reduce with flexible type]

2008-05-23 Thread Marc Oldenhof
Hello all,

I'm pretty new to Python, but use it a lot lately. I'm getting a crazy
error trying to do operations on a string list after importing numpy.
Minimal example:

[start Python]

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> a=['1','2','3']
>>> all(a)
True
>>> from numpy import *
>>> all(a)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
982, in all
return _wrapit(a, 'all', axis, out)
  File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
37, in _wrapit
result = getattr(asarray(obj),method)(*args, **kwds)
TypeError: cannot perform reduce with flexible type

[end of example]

It seems that Python calls numpy's "all" instead of the standard one,
is that right? If so, how can I call the standard "all" after the
numpy import? ["import numpy" is not a desirable option, I use a lot
of math in my progs]

Is there another way around this error?

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


Re: Python(2.5) reads an input file FASTER than pure C(Mingw)

2008-05-23 Thread Lie
On Apr 30, 8:57 pm, n00m <[EMAIL PROTECTED]> wrote:
> >>> a = ['zzz', 'aaa']
> >>> id(a[0]), id(a[1])
>
> (12258848, 12259296)>>> a.sort()
> >>> id(a[0]), id(a[1])
>
> (12259296, 12258848)
>
>

That proves you know nothing, that is a list operation, not a string
operation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling class method by name passed in variable

2008-05-23 Thread Bruno Desthuilliers

Sagari a écrit :

Greetings,

Can someone suggest an efficient way of calling method whose name is
passed in a variable?



method = getattr(obj, 'method_name', None)
if callable(method):
method(args)
--
http://mail.python.org/mailman/listinfo/python-list


Re: error using all()/numpy [TypeError: cannot perform reduce with flexible type]

2008-05-23 Thread Marc Oldenhof
On 23 mei, 09:12, Marc Oldenhof <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I'm pretty new to Python, but use it a lot lately. I'm getting a crazy
> error trying to do operations on a string list after importing numpy.
> Minimal example:
>
> [start Python]
>
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> >>> a=['1','2','3']
> >>> all(a)
> True
> >>> from numpy import *
> >>> all(a)
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
> 982, in all
>     return _wrapit(a, 'all', axis, out)
>   File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
> 37, in _wrapit
>     result = getattr(asarray(obj),method)(*args, **kwds)
> TypeError: cannot perform reduce with flexible type
>
> [end of example]
>
> It seems that Python calls numpy's "all" instead of the standard one,
> is that right? If so, how can I call the standard "all" after the
> numpy import? ["import numpy" is not a desirable option, I use a lot
> of math in my progs]
>
> Is there another way around this error?
>
> Marc

Never mind, I found a way. For reference:

>>> import __builtin__
>>> __builtin__.all(a)
True

Works!

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


Re: [Regexes] Stripping puctuation from a text

2008-05-23 Thread Andrew Lee

shabda raaj wrote:

I want to strip punctuation from text.

So I am trying,


p = re.compile('[a-zA-Z0-9]+')
p.sub('', 'I love tomatoes!! hell yeah! ... Why?')

'  !!  ! ... ?'

Which gave me all the chars which I want to replace.

So Next I tried by negating the regex,


p = re.compile('^[a-zA-Z0-9]+')
p.sub('', 'I love tomatoes!! hell yeah! ... Why?')

' love tomatoes!! hell yeah! ... Why?'

But this removed the first char instead of the puctuation. So I guess
^ is matching start of line, instead of negation. How can I take
negation of the regex here?



p = re.compile('[^a-zA-Z0-9]+')
--
http://mail.python.org/mailman/listinfo/python-list


Re: where is the Write method of ElementTree??

2008-05-23 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
> I'm messing around with trying to write an xml file using
> xml.etree.ElementTree.  All the examples on the internet show the use
> of ElementTree.write(), although when I try to use it it's not
> available, gives me ...
> 
>ElementTree(sectionElement).write("section.xml")
> TypeError: 'module' object is not callable

I guess you did

from xml.etree import ElementTree

Then you should do this:

ElementTree.ElementTree(sectionElement).write("section.xml")

sadly, the module names in ET are upper case and look like classes...

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


Python treeview and recursion: help needed

2008-05-23 Thread Mailing List SVR
Hi, 

I have a database with the following structure:

idname  sublevel

for example

1 Node1 None
2 Node2 1
3 Node3 2
4 Node4 None
5 Node5 1
6 Node6 5




where Node1 and Node4 are treeview's master nodes, Node2 is a subnode of
Node1, Node3 is a subnode of Node2, Node5 is a subnode of Node1 and
Node6 a subnode of Node5 and so on

I need a recursive function to populate treeview and I'm stuck on this
function :confused:

I need a list where I have the master node with child node inside and if
a child node as others child nodes, I need thess nodes inside the child
nodes.

Something like this:

[
{"id":1,"name":"Node1","Childs":[{"id:2","name":"Node2","Childs":[{"id":3,"name":"Node3","Childs":[]}]},
{"id":5,
"name":"Node5","Childs":[{"id":6,"name":"Node6","Childs":[]}]}]},{"id":4,"name":"Node4","Childs":[]}
  
]

I'm using django so I access the data as 

all=Data.objects.all()

and I can do something like

for a in all:
  print a.id
  print a.name
  
to get database value.

Any help is appreciated,

thanks,
Nicola

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

Re: php vs python

2008-05-23 Thread Michael Fesser
.oO(Nick Craig-Wood)

>Damon Getsman <[EMAIL PROTECTED]> wrote:
>> PHP has great support for accessing a MySQL database,
>
>Actually I'd say PHP's mysql support is lacking a very important
>feature.  mysql_query() doesn't support parameters (or placeholders,
>usually '?')

Where were you the last couple of years? It's lacking a lot more
features, but that's not the fault of the MySQL extension, which is
quite old. Meanwhile we have the improved MySQL extension and PDO.

>It is not a big deal, but I've had it drummed into me to always use
>parameters for user input and I was really suprised PHP didn't have
>them.

PHP supports them since _years_, you just have to choose the right
database interface.

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


Re: error using all()/numpy [TypeError: cannot perform reduce with flexible type]

2008-05-23 Thread Gary Herron

Marc Oldenhof wrote:

Hello all,

I'm pretty new to Python, but use it a lot lately. I'm getting a crazy
error trying to do operations on a string list after importing numpy.
Minimal example:

[start Python]

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

  

a=['1','2','3']
all(a)


True
  

from numpy import *
all(a)


Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
982, in all
return _wrapit(a, 'all', axis, out)
  File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
37, in _wrapit
result = getattr(asarray(obj),method)(*args, **kwds)
TypeError: cannot perform reduce with flexible type

[end of example]

It seems that Python calls numpy's "all" instead of the standard one,
is that right? If so, how can I call the standard "all" after the
numpy import? ["import numpy" is not a desirable option, I use a lot
of math in my progs]

Is there another way around this error?
  


Yes, there are several solutions, but before that I'll say that "from 
... import *" is frowned upon for just this reason.   You have no 
control (and often no idea) what * ends up importing, and if any of 
those names overwrite an existing name (as you've found here), you may 
not notice.(It's not quite fair to say "Python calls numpy's "all".  
*You* call it after you chose to replace Python's "all" with numpy's "all".)


Solutions:



Save Python's "all" first under another name:
   original_all = all
   from numpy import all
Now you can call all(...) or original_all(...).



The built-in (as they are called) are always available through __builtins__:
   from numpy import *
   all(...)  # is numpy's all
   __builtins__.all(...)  # Is the original all




Don't import *, but rather import only those things you need.
   from numpy import array, dot, float32, int32, ...
and if you need numpy's all
   from numpy import all as numpy_all


Gary Herron





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


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


Re: Relationship between GUI and logic?

2008-05-23 Thread Bruno Desthuilliers

John Salerno a écrit :
I know that it is good programming practice to keep GUI and logic code 
physically separate, by using XRC for example, but I'm wondering if it's 
also good practice (and even possible) to keep them separate from an 
implementation standpoint as well. Basically what I mean is, should it 
be possible to write, for example, the logic for a strategy game without 
even knowing what the graphics will look like or how they will work?


Depends on your definition of "logic". The point is not "keep GUI and 
logic code" separate, but to keep "domain" logic (as) separated (as 
possible) from user-interface stuff.


To be more specific, let's say I want to create a simple, 2D strategy 
game. It will have a board layout like chess or checkers and the player 
will move around the board. Let's say this is all I know, and perhaps I 
don't even know *this* for sure either. Is it possible to write the 
logic for such a game at this point?


Yes : build a model of the board and pieces and functions/methods to 
allow (code-level) interaction with it. Then your user interface will 
just have to create a visual representation of this model (let's call it 
a view) and present the user with ways (connected to things we'll call 
'controllers') to call the interaction functions/methods.


Then : the view registers itself with the model, display itself, and 
wait for user interactions. These user interactions are sent to the 
appropriate controller, which will call on the model's interaction 
functions/methods. Then the model updates itself and notify the view 
that it's state has changed, so the view can refresh itself.


Ever heard of the "Model/View/Controller" pattern ?

Let's say I want to write a "move" function (or perhaps it would be a 
method of a "Character" class) for moving the player around. Could you 
really write this function without 1) knowing what the interface will 
look like, and 2) integrating GUI code with the logic?


Yes. The move function will modify the state of the board/pieces 
("character", whatever) model, which will then notify whoever is 
interested that it's state has changed.


Another example could be printing messages to the player. If I need to 
say "You killed the monster!", is there a general way to write this, or 
do I need to specifically refer to GUI widgets and methods, etc. in 
order for it to be displayed properly?


Idem. State change, notification.

Basically, the question is this: can you write the logic behind a 
program (whether it be a game, an email client, a text editor, etc.) 
without having any idea of how you will implement the GUI?


s/GUI/ui/g

The user interface doesn't need to be graphical. There were games and 
emails clients and text editors before GUIs existed, you know ?


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


Re: Python is slow

2008-05-23 Thread Bruno Desthuilliers

Brad a écrit :

cm_gui wrote:

Python is slow.


It ain't C++, but it ain't a punch card either... somewhere in between. 
I find it suitable for lots of stuff. I use C++ when performance really 
matters tho... right tool for the job. Learn a good interpreted language 
(Pyhton) and a good compiled language (C or C++) 


LordHaveMercy(tm). Could you guys please learn what you're talking about?

1/ being interpreted or compiled (for whatever definition of these
terms) is not a property of a language, but a property of an
implementation of a language.

2/ actually, all known Python implementations compile to byte-code.


and you'll be just 
fine. Until then, quit bitching.

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


pickle error: can't pickle instancemethod objects

2008-05-23 Thread Michele Simionato
Can somebody explain what's happening with the following script?

$ echo example.py
import pickle

class Example(object):

def __init__(self, obj, registry):
self._obj = obj
self._registry = registry
for name, func in self._registry.iteritems():
setattr(self, name, func.__get__(obj, obj.__class__))

def __gestate__(self): # should skip the bound methods attributes
return dict(_registry=self._registry, _obj=self._obj)

class C(object):
pass

def foo(self):
pass

if __name__ == '__main__':
ex = Example(C(), dict(foo=foo))
pickle.dumps(ex)

I get the following traceback:

Traceback (most recent call last):
  File "pickle_error.py", line 22, in 
pickle.dumps(ex)
  File "/usr/lib/python2.5/pickle.py", line 1366, in dumps
Pickler(file, protocol).dump(obj)
  File "/usr/lib/python2.5/pickle.py", line 224, in dump
self.save(obj)
  File "/usr/lib/python2.5/pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
  File "/usr/lib/python2.5/pickle.py", line 419, in save_reduce
save(state)
  File "/usr/lib/python2.5/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.5/pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.5/pickle.py", line 663, in _batch_setitems
save(v)
  File "/usr/lib/python2.5/pickle.py", line 306, in save
rv = reduce(self.proto)
  File "/usr/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects

I know that instancemethods cannot be pickled, this is why I
used a __getstate__ method, but apparently it does not work.
Any hint?

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


Re: MVC

2008-05-23 Thread Bruno Desthuilliers

George Maggessy a écrit :

Hi Gurus,

I'm a Java developer and I'm trying to shift my mindset to start
programming python.


Welcome onboard then.


So, my first exercise is to build a website.
However I'm always falling back into MVC pattern.


And ? Is there anything wrong with web-style MVC ?


I know it's a
standard, but the implementation language affects the use of design
patter. So, here goes my question. Is that OK if I follow this? Should
I create DAOs, View Objects, Controllers and etc? Is there any sort of
best practice / standard to Python?


http://pylonshq.com/
http://www.djangoproject.com/
http://webpy.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2 different versions of python compiling files.

2008-05-23 Thread Ivan Illarionov
> The original .py will always be there but you know what, multiple python
> versions from different computers do access that one library at the same
> time.
> 
> Anyone know a possible solution ?

What about subversion or mercurial and separate copies of your library 
for each Python version?

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


Re: webcam (usb) access under Ubuntu

2008-05-23 Thread ticapix
On 16 avr, 09:41, Berco Beute <[EMAIL PROTECTED]> wrote:
> On Apr 15, 11:45 pm, Berco Beute <[EMAIL PROTECTED]> wrote:
>
> > I've tried reinstalling gstreamer (for windows):
>
> >http://gstreamer.freedesktop.org/pkg/windows/releases/gstreamer/gstre..
>
> > but that didn't help. I get some complaints about 'libgstinterfaces'
> > as well...
>
> To be more precise, when doing an 'import gst' Python shell pops up an
> error dialog saying:
>
> "This application has failed to start because
> libgstinterfaces-0.10.dll was not found."
>
> 2B

You need to install gst-plugins-good too

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


Re: error using all()/numpy [TypeError: cannot perform reduce with flexible type]

2008-05-23 Thread Peter Otten
Marc Oldenhof wrote:

> I'm pretty new to Python, but use it a lot lately. I'm getting a crazy
> error trying to do operations on a string list after importing numpy.
> Minimal example:
> 
> [start Python]
> 
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> 
 a=['1','2','3']
 all(a)
> True
 from numpy import *
 all(a)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
> 982, in all
> return _wrapit(a, 'all', axis, out)
>   File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line
> 37, in _wrapit
> result = getattr(asarray(obj),method)(*args, **kwds)
> TypeError: cannot perform reduce with flexible type
> 
> [end of example]
> 
> It seems that Python calls numpy's "all" instead of the standard one,
> is that right? If so, how can I call the standard "all" after the
> numpy import? ["import numpy" is not a desirable option, I use a lot
> of math in my progs]
> 
> Is there another way around this error?

That's not an error; star-import is a rebinding operation, just like
assignments and the def statement. 

>>> from numpy import *
>>> del all, sum, any
>>> all("123")
True

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


Re: Decorator metaclass

2008-05-23 Thread Carl Banks
On May 22, 10:28 pm, [EMAIL PROTECTED] wrote:
> Hi,
> I would like to create a Decorator metaclass, which automatically
> turns a class which inherits from the "Decorator" type into a
> decorator.
> A decorator in this case, is simply a class which has all of its
> decorator implementation inside a decorator() method. Every other
> attribute access is being proxied to decorator().getParent().
>
> Here's my attempt:

You got deep stuff going on there, chief, and some of it's wrong.
I'll try to point it out.

> ---
> from new import classobj
>
> class DecoratorType(type):
> def __new__(cls, name, bases, dct):
> dct2 = {}
> for key, val in dct.iteritems():
> dct2[key] = val

First of all, you can just do dct2 = dct.copy().
Second, since you never use dct again, even copying it is unnecessary.


> # create a new class which will store all of the 
> implementation
> impl = classobj('%sImpl'%name,(),dct2)

classobj creates an old-style class, and I'm pretty sure you don't
want to do that.  To create a new-style class, use type:

impl = type('%sImpl'%name,(),dct)


> # update the old class to implement this implementation
> def __init__(self, *args, **dargs):
> object.__setattr__(self, '__impl', impl(*args, 
> **dargs))

As your code stands now, object.__setattr__ isn't necessary here; just
using

self.__impl = impl(*args,**dargs)

should work fine.  I'm guessing you intend to override __setattr__
later?

If you do use object.__setattr__, I suggest that you might want to
call the superclass's __setattr__ instead of object's.  I imagine in
this case the superclass will rarely want to override __setattr__
itself, but in general it's a good idea.  In this particular
circumstance, we don't yet have the class object (it doesn't come till
after calling type.__new__) but we do have the parent class.  So you
might consider changing the definition of __init__ to this:

basecls = bases[0] if bases else object
def __init__(self, *args, **dargs):
basecls.__setattr__(self, '__impl', impl(*args, **dargs))

> def decorator(self):
> return object.__getattribute__(self,'__impl')

Again, consider changing it to

def decorator(self):
return basecls.__getattribute(self,'__impl')

> def __getattribute__(self, attr):
> if attr=="decorator":
> return 
> object.__getattribute__(self,'decorator')
> return getattr(object.__getattribute__(self, 
> 'decorator')
> ().getParent(), attr)
> dct = {}
> dct['__init__'] = __init__
> dct['decorator'] = decorator
> dct['__getattribute__'] = __getattribute__
>
> return type.__new__(cls, name, bases, dct)
>
> class Decorator(object):
> __metaclass__ = DecoratorType

Parenthetical: I don't normally recommend this style, since it
obscures the fact that you're using a custom metaclass to the user.
That is something the user probably would benefit from knowing, if for
no other reason than so they can make a mental note about where to
look first if something goes wrong.  I prefer to make the user use the
__metaclass__ attribute.

However, I could see it being desirable for some cases where you're
trying to be as transparent as possible, and indeed it looks as if
that's your goal here.


> class HBar(Decorator):
> def __init__(self, number):
> Decorator.__init__(self)

Ok, at this point you have to ask yourself what you want to do,
because the solution you choose will involve trade-offs.

You will note that Decorator does not define __init__.  In fact,
object.__init__ will be called, which does nothing.  If you think that
all classes with DecoratorType as their metaclass will be a direct
subclass of Decorator, you can get away with not calling
Decorator.__init__ at all.

However, this can cause problems if a user wants to define their own
base class with an __init__ that does something (either by using the
__metaclass__ attribute, or by subclassing a Decorator subclass).  In
that case, you will have to make arrangements to pass the decorator
object to the superclass instead of the decorated.  This can be pretty
hairy, and it beyond the scope of this reply.

To do it completely transparently, your decorated class will probably
have to maintain a reference to its decorator, and will also have to
derive from a base class that delegates any method calls to the
superclass of the decorator.  (Phew.)

That won't be as easy as it sounds.


> self._number = number
> def inc(self):
> self._number += 1
> def p(self):
> print self._number
>
> hbar = HBar(10)
> for each in dir(h

Re: pickle error: can't pickle instancemethod objects

2008-05-23 Thread Peter Otten
Michele Simionato wrote:

> Can somebody explain what's happening with the following script?

> def __gestate__(self): # should skip the bound methods attributes

Must be __getstate__ ;)

Peter

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


Re: Python and Flaming Thunder

2008-05-23 Thread Iain King
On May 23, 3:35 am, Charles Hixson <[EMAIL PROTECTED]> wrote:
> On Thursday 22 May 2008 13:30:07 Nick Craig-Wood wrote:
>
> > ...
> > >From Armstrong's book: The expression Pattern = Expression causes
>
> > Expression to be evaluated and the result matched against Pattern. The
> > match either succeeds or fails. If the match succeeds any variables
> > occurring in Pattern become bound.
>
> > It is a very powerful idea and one which (along with the concurrency
> > and message passing from Erlang) has been implemented for python :-
>
> >  http://candygram.sourceforge.net/
>
> > I've been reading the Erlang book and I have to say it has given me a
> > lot of insight into python...
>
> Although when comparing Candygram with Erlang it's worth noting that Candygram
> is bound to one processor, where Erlang can operate on multiple processors.
> (I'd been planning on using Candygram for a project at one point, but this
> made it unusable.)

lol, nice name.  Also surprisingly relevant to the thread:

candygrammar: n.

A programming-language grammar that is mostly syntactic sugar; the
term is also a play on ‘candygram’. COBOL, Apple's Hypertalk language,
and a lot of the so-called ‘4GL’ database languages share this
property. The usual intent of such designs is that they be as English-
like as possible, on the theory that they will then be easier for
unskilled people to program. This intention comes to grief on the
reality that syntax isn't what makes programming hard; it's the mental
effort and organization required to specify an algorithm precisely
that costs. Thus the invariable result is that ‘candygrammar’
languages are just as difficult to program in as terser ones, and far
more painful for the experienced hacker.
--
http://mail.python.org/mailman/listinfo/python-list


Re: error using all()/numpy [TypeError: cannot perform reduce with flexible type]

2008-05-23 Thread I V
On Fri, 23 May 2008 00:12:35 -0700, Marc Oldenhof wrote:
> It seems that Python calls numpy's "all" instead of the standard one, is
> that right? If so, how can I call the standard "all" after the numpy
> import? ["import numpy" is not a desirable option, I use a lot of math
> in my progs]

I think the ideal solution is to try and persuade yourself that typing 
"numpy." in front of some functions now and then is not that big a price 
to pay to avoid name collisions; using an editor with code completion 
would probably help in that task.

You could also try:

import numpy as n

which reduces the typing a bit and limits you to one possible name 
collision, or

from numpy import array, gradient #and whatever else you need

or 

import numpy

array = numpy.array
gradient = numpy.gradient # Then you can access the names you use a lot 
  # directly, while accessing stuff you use less
  # frequently via numpy.whatever

in which case you'll know exactly which names you're overwriting. Peter's 
solution, of explicitly deleting some names that you've imported, strikes 
me as less good, because you might find the same problem recurs later, if 
the numpy developers add new names to the module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pickle error: can't pickle instancemethod objects

2008-05-23 Thread Michele Simionato
On May 23, 10:12 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> Michele Simionato wrote:
> > Can somebody explain what's happening with the following script?
> >     def __gestate__(self): # should skip the bound methods attributes
>
> Must be __getstate__ ;)
>
> Peter

Aaargh!!! I spent a couple of hours on a typo!
Thanks anyway, now everything makes sense again ;)
--
http://mail.python.org/mailman/listinfo/python-list


Ploneboard - grouping forums and setting up on disk

2008-05-23 Thread Paul Rudin

I'm investigating using ploneboard and have a couple of questions.

First of all I don't quite get what the global view/local view
distinction is - perhaps someone could be good enough to explain what
it's for.

If it possible to group forums so that permissions can be applied to
each set so - for example - we have a set of public forums viewable by
everyone and a set of member's forums viewable only by logged in
members. I understand that permission can be set for each forum
individially, but it would be nice to have a grouping so that a new
forum can be added to a group and it automatically gets the appropriate
permissions for that group.

Finally - is it possible to configure the available forums and
permission on disk, so that a given forum structure can easily be setup
in a new plone instance without having to redo it through the web each
time?

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


Re: Python is slow

2008-05-23 Thread Carl Banks
On May 23, 3:50 am, Bruno Desthuilliers  wrote:
> Brad a écrit :
>
> > cm_gui wrote:
> >> Python is slow.
>
> > It ain't C++, but it ain't a punch card either... somewhere in between.
> > I find it suitable for lots of stuff. I use C++ when performance really
> > matters tho... right tool for the job. Learn a good interpreted language
> > (Pyhton) and a good compiled language (C or C++)
>
> LordHaveMercy(tm). Could you guys please learn what you're talking about?
>
> 1/ being interpreted or compiled (for whatever definition of these
> terms) is not a property of a language, but a property of an
> implementation of a language.
>
> 2/ actually, all known Python implementations compile to byte-code.
>
> > and you'll be just
> > fine. Until then, quit bitching.

You know, even though you're technically correct, I'd like to see you
abandon this little crusade.  At this point it's more noisy than
helpful.

Like it or not, to most of the world, "interpreted" vs. "compiled" is
a vague pragmatic distinction between fast machine-coded languages and
not-so-fast non-machine-coded languages.  And like it or not, the
world rarely cares to make the distinction between language and
implementation, and frankly, it's usually not necessary to.

What Brad said is perfectly acceptable, and good advice IMHO, under
the common usage of the terms.  I really don't see much reason to call
someone out on it unless they're being deliberately misleading.


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


KeyError in pickle

2008-05-23 Thread christof
Hi,

I am using pickle/unpickle to let my program save its documents to
disk. While this it worked stable for a long time, one of my users now
complained, that he had a file which can't be loaded.

The traceback is:

File "pickle.pyo", line 1374, in loads
File "pickle.pyo", line 858, in load
KeyError: 'A'


Does anybody know this problem. How this can happen and how can I
avoid it?

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


Google Treasure solution in python - first time python user, help whats wrong

2008-05-23 Thread x40
I try to learn python thru solving some interisting problem, found
google trasure hunt,
write first program ( but cant find whats wrong).

# Unzip the archive, then process the resulting files to obtain a
numeric result. You'll be taking the sum of lines from files matching
a certain description, and multiplying those sums together to obtain a
final result. Note that files have many different extensions, like
'.pdf' and '.js', but all are plain text files containing a small
number of lines of text.
#
#Sum of line 5 for all files with path or name containing abc and
ending in .js
#Sum of line 5 for all files with path or name containing HIJ and
ending in .js
#Hint: If the requested line does not exist, do not increment the sum.
#
#Multiply all the above sums together and enter the product below.
#(Note: Answer must be an exact, decimal representation of the
number.)

import fnmatch
import os

def zbrojipl(pattern):
rootPath = ''
sum1=0
for root, dirs, files in os.walk(rootPath):
 for filename in files:
  path=os.path.join(root, filename)
  if fnmatch.fnmatch(path, pattern):
#print path
f=open(path)
redovi=f.readlines()
#print len(redovi),redovi
if len(redovi)>=5:
#print redovi[4] # index od 0 kao C
sum1=sum1+int(redovi[4])
return sum1

print zbrojipl('*[abc]*.js')*zbrojipl('*[HIJ]*.js')
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyserial and file open conflict?

2008-05-23 Thread Peter
On 15 Maj, 19:37, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-05-15, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > I have a small but rather annoying problem withpyserial. I want to
> > open a file on disk for reading and then open a com-port, write lines
> > from the file to the port and then read something back and compare it
> > to the next line in the file. Should be simple. And it is, apart from
> > the fact that the file seems to be doubled ...? Or it loops through
> > the file twice.
>
> > If I exclude the "import serial" it works.
>
> > Any ideas?
>
> Your problem is in line 117 of your program.
>
> --
> Grant Edwards                   grante             Yow! Hmmm ... an arrogant
>                                   at               bouquet with a subtle
>                                visi.com            suggestion of POLYVINYL
>                                                    CHLORIDE ...

Do you have to much time?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-23 Thread Duncan Booth
Brian Quinlan <[EMAIL PROTECTED]> wrote:

> Dave Parker wrote:
>>> Or just:
>>>
>>> If command is "quit" ...
>> 
>> Hmmm.  In Flaming Thunder, I'm using "is" (and "is an", "is a", etc)
>> for assigning and checking types.  For example, to read data from a
>> file and check for errors:
>> 
>>  Read data from "input.txt".
>>  If data is an error then go to ...
> 
> Hey Dave,
> 
> Does this mean that Flaming Thunder requires explicit checking rather 
> than offering exceptions?

It looks that way but he doesn't seem to have got as far as documenting 
errors: the documentation gives several examples of that form and says that 
'error' is a reserved word but says nothing about how you create an error 
of if you can distinguish one error from another:

I'm guessing you can't as FT doesn't appear to have any concept of 
attributes on objects (or even any concept of objects): so far as I can see 
the only types are integers, rationals, intervals and strings (and real 
numbers if you pay real money for them).

Maybe I'm missing something though, because I don't see how you can do 
anything useful with out at least some sort of arrays (unless you are 
supposed to store numbers in long strings).

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-05-23 Thread inhahe

"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in 
message news:[EMAIL PROTECTED]
> Brad a écrit :
>> cm_gui wrote:
>>> Python is slow.
>>
>> It ain't C++, but it ain't a punch card either... somewhere in between. I 
>> find it suitable for lots of stuff. I use C++ when performance really 
>> matters tho... right tool for the job. Learn a good interpreted language 
>> (Pyhton) and a good compiled language (C or C++)
>
> LordHaveMercy(tm). Could you guys please learn what you're talking about?
>
> 1/ being interpreted or compiled (for whatever definition of these
> terms) is not a property of a language, but a property of an
> implementation of a language.

That's like saying being spherical is not a property of planets, it's a 
property of an instanciation of a planet.  Let alone that a) all known 
planets are spherical (all implementations of Python are not natively 
compiled (and you said for whatever definition)), and b) It's a far cry to 
imagine a planet coming into being that's not spherical (a language as 
dynamic as Python, or most other scripting languages, would be either 
extremely difficult or impossible to make a native compiler for).  I guess I 
should also mention that Python isn't very practical (as in "suitable", 
"right tool for the job", and "perfomance", as mentioned in the above post) 
without an implementation.  So I don't think this distinction has any use 
other than to beat other people over the head with a bat.

>
> 2/ actually, all known Python implementations compile to byte-code.
>

Which is then interpreted, but you're still technically right, because 
"compiled" can mean either compiled to bytecode or compiled to native code, 
despite what it actually did mean.  Semantics FTW!!






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

Re: error using all()/numpy [TypeError: cannot perform reduce with flexible type]

2008-05-23 Thread Marc Oldenhof
On 23 mei, 09:12, Marc Oldenhof <[EMAIL PROTECTED]> wrote:


Thanks for the reactions, I'll use the "from numpy import " from now on :)

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


Re: KeyError in pickle

2008-05-23 Thread Peter Otten
christof wrote:

> I am using pickle/unpickle to let my program save its documents to
> disk. While this it worked stable for a long time, one of my users now
> complained, that he had a file which can't be loaded.
> 
> The traceback is:
> 
> File "pickle.pyo", line 1374, in loads
> File "pickle.pyo", line 858, in load
> KeyError: 'A'
> 
> 
> Does anybody know this problem. How this can happen and how can I
> avoid it?

Is this reproducible? How? If not I would guess that the file is corrupted.

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


Re: can python do some kernel stuff?

2008-05-23 Thread Jimmy
On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:
> Jimmy wrote:
> > Hi to all
>
> > python now has grown to a versatile language that can
> > accomplish tasks for many different purposes. However,
> > AFAIK, little is known about its ability of kernel coding.
>
> > So I am wondering if python can do some kernel coding that
> > used to be the private garden of C/C++. For example, can python
> > intercept the input of keyboard on a system level? someone told me
> > it's a kernel thing, isn't it?
>
> http://wiki.python.org/moin/elmer

well, straightly speaking, how can I know a key is pressed on a system-
level if
using python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-23 Thread Nick Craig-Wood
I V <[EMAIL PROTECTED]> wrote:
>  On Thu, 22 May 2008 19:35:50 -0700, Charles Hixson wrote:
> > Although when comparing Candygram with Erlang it's worth noting that
> > Candygram is bound to one processor, where Erlang can operate on
> > multiple processors. (I'd been planning on using Candygram for a project
> > at one point, but this made it unusable.)
> 
>  Really? The FAQ says it uses operating system threads, which I would have 
>  thought would mean it runs on multiple processors (modulo, I suppose, the 
>  issues with the GIL).

I think candygram is crying out to be married with stackless &or PyPy.
It also needs an IPC channel to compete with Erlang directly.

If you are interested in stackless python vs Erlang then take a look
at this...

  
http://muharem.wordpress.com/2007/07/31/erlang-vs-stackless-python-a-first-benchmark/

...and read the discussion too!

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


Re: Calling class method by name passed in variable

2008-05-23 Thread Nick Craig-Wood
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> > Can someone suggest an efficient way of calling method whose name is
> > passed in a variable?
> > 
> 
>  method = getattr(obj, 'method_name', None)
>  if callable(method):
>   method(args)

I think that that is needless LBYL...

   getattr(obj, 'method_name')(args)

Will produce some perfectly good exceptions

>>> class A(object):
... def __init__(self):
... self.x = 2
... def f(self, x):
... print x == self.x
...
>>> obj = A()
>>> getattr(obj, 'floop')(1)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'A' object has no attribute 'floop'
>>> getattr(obj, 'x')(1)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'int' object is not callable
>>> getattr(obj, 'f')(1)
False
>>>

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


online money earnings

2008-05-23 Thread dasasdfd
online money earnings
value of money
money is the life
http://moneylife0123.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: php vs python

2008-05-23 Thread Andrew Lee

notbob wrote:

I'm not posting this just to initiate some religious flame war, though it's
the perfect subject to do so.  No, I actaully want some serious advice about
these two languages and since I think usenet is the best arena to find it,
here ya' go.

So, here's my delimna: I want to start a blog.  Yeah, who doesn't.  Yet, I
want learn the guts of it instead of just booting up some wordwank or
whatever.  I started to learn python, but heard php was easier or faster or
more like shell scripting or... fill in the blank.  Anyway, so I change over
to learning php.  Then I run across that blog, Coding Horror, and start
reading articles like this:

http://www.codinghorror.com/blog/archives/001119.html

Now what?  Go back to python.  Soldier on with php?  What do I know?  Not
much.  I can setup mysql and apache,, but don't know how to use 'em, really.
I use emacs and run slackware and can fumble my way through bash scripts,
but I can't really write them or do lisp.  I've taken basic basic and basic
C, but am barely literate in html.  Sometimes it seems overwhelming, but I
persevere because it's more fun/challenging than video games, which bore me
to tears.  


Well, that's my actual question, then.  Is php really so bad I'm just
wasting my time?  Or is it really the quickest way to blog functionality?
Would I be better served in the long run learning python, which claims to be
easy as pie to learn/program (still looks hard to me).  I admit I'm no code
geek.  But, I'm not completely brain dead, either, and I need something to
keep my geezer brain sparking.  What say ye?

nb


Personally, I believe PHP would get you more productive more quickly for 
a blog, but it is a potentially brain damaging language in terms of 
really getting your juices flowing with programming.  It is not a 
general purpose language and suffers from all the limitations of of a 
tool designed for one job.  If you are interested in programming and the 
blog is your path to that, stick with Python!  In particular, immerse 
yourself in mod_python or look at a framework like Django or Pylons -- 
the learning curve is steep for any of these technologies but they are a 
full meal compared to saltine cracker and water of PHP.

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


unittest: Calling tests in liner number order

2008-05-23 Thread Antoon Pardon
Some time ago I asked whether is would be possible that unittest would
perform the test in order of appearence in the file.

The answers seemed to be negative. Since I really would like this
behaviour I took the trouble of looking throught the source and
I think I found a minor way to get this behaviour.

Now my questions are:

Are other people interrested in this behaviour?
Does the following patch has a chance of being introduced in the
standard python distribution?

*** /usr/lib/python2.5/unittest.py  2008-04-17 16:26:37.0 +0200
--- unittest.py 2008-05-23 11:19:57.0 +0200
***
*** 570,575 
--- 570,577 
  """
  def isTestMethod(attrname, testCaseClass=testCaseClass, 
prefix=self.testMethodPrefix):
  return attrname.startswith(prefix) and 
callable(getattr(testCaseClass, attrname))
+ def getlinenr(name):
+ return getattr(testCaseClass, 
name).im_func.func_code.co_firstlineno
  testFnNames = filter(isTestMethod, dir(testCaseClass))
  for baseclass in testCaseClass.__bases__:
  for testFnName in self.getTestCaseNames(baseclass):
***
*** 577,582 
--- 579,586 
  testFnNames.append(testFnName)
  if self.sortTestMethodsUsing:
  testFnNames.sort(self.sortTestMethodsUsing)
+ else:
+ testFnNames.sort(key=getlinenr)
  return testFnNames
  

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


Re: pyserial and file open conflict?

2008-05-23 Thread Diez B. Roggisch


Do you have to much time?


Maybe you have enough time to read this:

http://www.catb.org/~esr/faqs/smart-questions.html

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


Re: call f(a, *b) with f(*a, **b) ?

2008-05-23 Thread Nick Craig-Wood
bukzor <[EMAIL PROTECTED]> wrote:
>  That does, in fact work. Thanks! I'm a little sad that there's no
>  builtin way to do it, owell.
> 
> >>> def f(a, *args):
>  ... print a
>  ... for b in args: print b
>  ...
> >>> import inspect
> >>> a = [2,3]
> >>> b = {'a':1}
> >>> inspect.getargspec(f)
>  (['a'], 'args', None, None)
> >>> map(b.get, inspect.getargspec(f)[0])
>  [1]
> >>> map(b.get, inspect.getargspec(f)[0]) + a
>  [1, 2, 3]
> >>> f(*map(b.get, inspect.getargspec(f)[0]) + a)
>  1
>  2
>  3

If I saw that in my code I'd be wanting to get rid of it as soon as
possible!

I'd re-write f() to have all named arguments then the problem becomes
easy and the answer pythonic (simple dictionary manipulation)...

So instead of f(a, *args) have f(a, list_of_args).

The f(*args) syntax is tempting to use for a function which takes a
variable number of arguments, but I usually find myself re-writing it
to take a list because of exactly these sort of problems.  In fact I'd
be as bold to say that f(*args) is slightly un-pythonic and you should
avoid as a user interface.  It does have its uses when writing
polymorphic code though.

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


Re: can python do some kernel stuff?

2008-05-23 Thread Andrew Lee

Jimmy wrote:

On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:

Jimmy wrote:

Hi to all
python now has grown to a versatile language that can
accomplish tasks for many different purposes. However,
AFAIK, little is known about its ability of kernel coding.
So I am wondering if python can do some kernel coding that
used to be the private garden of C/C++. For example, can python
intercept the input of keyboard on a system level? someone told me
it's a kernel thing, isn't it?

http://wiki.python.org/moin/elmer


well, straightly speaking, how can I know a key is pressed on a system-
level if
using python?


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

Unless you are using an ancient piece of hardware -- a terminal is a 
pseudo terminal and a key stroke isn't a kernel event at all.


If you were looking for examples of kernel level functions you might 
want to consider driver interfaces -- how to program device interfaces 
-- that, too, can be done in Python -- but, again, you are always 
calling some underlying C function exposed via SWIG or another cross 
compilation tool.  Python doesn't reinvent system calls!  :-)

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


Re: can python do some kernel stuff?

2008-05-23 Thread Andrew Lee

Diez B. Roggisch wrote:

Jimmy schrieb:

On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:

Jimmy wrote:

Hi to all
python now has grown to a versatile language that can
accomplish tasks for many different purposes. However,
AFAIK, little is known about its ability of kernel coding.
So I am wondering if python can do some kernel coding that
used to be the private garden of C/C++. For example, can python
intercept the input of keyboard on a system level? someone told me
it's a kernel thing, isn't it?

http://wiki.python.org/moin/elmer


well, straightly speaking, how can I know a key is pressed on a system-
level if
using python?


What has that todo with kernel programming? You can use e.g. pygame to 
get keystrokes. Or under linux, read (if you are root) the keyboard 
input file - I've done that to support several keyboards attached to a 
machine.


And the original question: no, python can't be used as kernel 
programming language. Amongst other reasons, performance & the GIL 
prevent that.


Diez


http://www.kernel-panic.it/programming/py-pf/

Of course you can code kernel routines in Python -- you are just calling 
the underlying C interface.  The GIL means you have to manage 
threadsafety on your own -- it doesn't imply kernel programming can not 
be done.


I'm not talking about writing an OS in Python (though a simple DOS-like 
OS is very possible).  Nor would I suggest writing device drivers in 
Python -- but of course you can call kernel routines and manage some 
kernel resources effectively.  Python's IPC libraries expose kernel 
functionality.

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


Re: Python is slow

2008-05-23 Thread Ivan Illarionov
On 23 май, 02:20, Brad <[EMAIL PROTECTED]> wrote:
> cm_gui wrote:
> > Python is slow.
>
> It ain't C++, but it ain't a punch card either... somewhere in between.
> I find it suitable for lots of stuff. I use C++ when performance really
> matters tho... right tool for the job. Learn a good interpreted language
> (Pyhton) and a good compiled language (C or C++) and you'll be just
> fine. Until then, quit bitching.

  It's wrong. Here's why.

  Compare your statement to:
   "OP:  Humans are weak.
   "Brad:  They ain't gorillas, but they ain't insects either...
somewhere in between."

  Python is *not* in between C++ and something else.  It's far ahead
of them all.  Raw speed is not the most important thing in programming
languages like raw physical strength is not the most important thing
in life.
  Pure Python has less raw speed than most compiled-to-machine-code
languages, but it doesn't matter.  Python can be extended easily and,
most important, Python is smart.

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

Re: call f(a, *b) with f(*a, **b) ?

2008-05-23 Thread inhahe

"Nick Craig-Wood" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> bukzor <[EMAIL PROTECTED]> wrote:
>>  That does, in fact work. Thanks! I'm a little sad that there's no
>>  builtin way to do it, owell.
>>
>> >>> def f(a, *args):
>>  ... print a
>>  ... for b in args: print b
>>  ...
>> >>> import inspect
>> >>> a = [2,3]
>> >>> b = {'a':1}
>> >>> inspect.getargspec(f)
>>  (['a'], 'args', None, None)
>> >>> map(b.get, inspect.getargspec(f)[0])
>>  [1]
>> >>> map(b.get, inspect.getargspec(f)[0]) + a
>>  [1, 2, 3]
>> >>> f(*map(b.get, inspect.getargspec(f)[0]) + a)
>>  1
>>  2
>>  3
>
> If I saw that in my code I'd be wanting to get rid of it as soon as
> possible!
>
> I'd re-write f() to have all named arguments then the problem becomes
> easy and the answer pythonic (simple dictionary manipulation)...
>
> So instead of f(a, *args) have f(a, list_of_args).
>
> The f(*args) syntax is tempting to use for a function which takes a
> variable number of arguments, but I usually find myself re-writing it
> to take a list because of exactly these sort of problems.  In fact I'd
> be as bold to say that f(*args) is slightly un-pythonic and you should
> avoid as a user interface.  It does have its uses when writing
> polymorphic code though.
>


(I second that) the function should definitely be changed if possible.  it's 
hard to say what the real constraints of the problem are, so I just answered 
his question as if that's what he actually needed (assuming the length of 
the list and number of named arguments would be variable).

if we assume the constraints are that:
1.he has list, l
2.he has a dictionary, d
3.he wants the function to print the values in the dictionary according to a 
specific order of their keys as defined by the function, followed by the 
values of the list
then:

def f(d, l):
  order_of_keys = ['a']
  for key in order_of_keys:
print d[key]
  for element in l:
print element

#not tested



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


Re: can python do some kernel stuff?

2008-05-23 Thread Diez B. Roggisch

Jimmy schrieb:

On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:

Jimmy wrote:

Hi to all
python now has grown to a versatile language that can
accomplish tasks for many different purposes. However,
AFAIK, little is known about its ability of kernel coding.
So I am wondering if python can do some kernel coding that
used to be the private garden of C/C++. For example, can python
intercept the input of keyboard on a system level? someone told me
it's a kernel thing, isn't it?

http://wiki.python.org/moin/elmer


well, straightly speaking, how can I know a key is pressed on a system-
level if
using python?


What has that todo with kernel programming? You can use e.g. pygame to 
get keystrokes. Or under linux, read (if you are root) the keyboard 
input file - I've done that to support several keyboards attached to a 
machine.


And the original question: no, python can't be used as kernel 
programming language. Amongst other reasons, performance & the GIL 
prevent that.


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


Re: call f(a, *b) with f(*a, **b) ?

2008-05-23 Thread inhahe

"inhahe" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> if we assume the constraints are that:
> 1.he has list, l
> 2.he has a dictionary, d
> 3.he wants the function to print the values in the dictionary according to 
> a specific order of their keys as defined by the function, followed by the 
> values of the list

It's also possible (even likely) that he knows outside of the function what 
order he wants the values in, and only used an (incidentally) unordered dict 
called kwargs because he thought that's the only way to pass to those 
parameters.  in which case the function could be left untouched and the he 
would call it like this:

args = [1,2,3]
f(*args)
or
f(*[1,2,3])


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


Re: ctypes help

2008-05-23 Thread Nick Craig-Wood
gianluca <[EMAIL PROTECTED]> wrote:
>  On 23 Mag, 07:48, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> > On Thu, 22 May 2008 21:55:41 -0700, gianluca wrote:
> > > Yes, I know it but when I load a function (a=myDLL.myFUNCT()) I've an
> > > exception like this:
> >
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > > myDLL.myFUNCT()
> > >   File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__
> > > func = self.__getitem__(name)
> > >   File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__
> > > func = self._FuncPtr((name_or_ordinal, self))
> > > AttributeError: function 'myFUNCT' not found
> >
> > Then maybe the DLL doesn't contain a function called `myFUNCT`.  Any
> > chance you compiled your C as C++ and name mangling kicked in?
> >
> > Can you show a minimal C source for a DLL, how you compiled it, what you
> > did on the Python side to call it, and how it fails?
> >
> > Ciao,
> > Marc 'BlackJack' Rintsch
> 
>  I've located my dll in c:\windows\system32 (in linux I aven't any
>  problem) and I compiled it with dev-c++. The source code is C standard
>  ANSII and is quite havy. If you like I can send it via mail (you can
>  realy at [EMAIL PROTECTED]) . I've tryed to build a wrape with swig
>  olso with same code and I can access at all the function.

You can use objdump from mingw or cygwin to look inside the dll and
see exactly what it is exporting, eg

objdump -x OurSharedCodeLibrary.dll

This prints a great deal of stuff!  In the middle you'll see

[snip]
The Export Tables (interpreted .rdata section contents)
[snip]
Ordinal/Name Pointer] Table
[   0] OSCL_DEBUG_fakeInitComplete
[   1] OSCL_close
[   2] OSCL_displayIdent
[   3] OSCL_getCurrentDynamicParams
[   4] OSCL_getCurrentStaticParams
[   5] OSCL_getErrorString
[   6] OSCL_getIdent
[snip]

This is a dll we used in a project, and those names exactly worked
with ctypes, eg some snips from the ctypes code

self.dll = cdll.LoadLibrary("OurSharedCodeLibrary")
self.dll.OSCL_getErrorString.restype = c_char_p

def getErrorString(self, status):
return self.dll.OSCL_getErrorString(c_int(status))

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


Re: Python is slow

2008-05-23 Thread Paul Rubin
"inhahe" <[EMAIL PROTECTED]> writes:
> planets are spherical (all implementations of Python are not natively 
> compiled (and you said for whatever definition)), and b) It's a far cry to 
> imagine a planet coming into being that's not spherical (a language as 
> dynamic as Python, or most other scripting languages, would be either 
> extremely difficult or impossible to make a native compiler for).

There are native Python compilers, see psyco and pypy.
--
http://mail.python.org/mailman/listinfo/python-list


Re: can python do some kernel stuff?

2008-05-23 Thread Diez B. Roggisch

Andrew Lee schrieb:

Diez B. Roggisch wrote:

Jimmy schrieb:

On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:

Jimmy wrote:

Hi to all
python now has grown to a versatile language that can
accomplish tasks for many different purposes. However,
AFAIK, little is known about its ability of kernel coding.
So I am wondering if python can do some kernel coding that
used to be the private garden of C/C++. For example, can python
intercept the input of keyboard on a system level? someone told me
it's a kernel thing, isn't it?

http://wiki.python.org/moin/elmer


well, straightly speaking, how can I know a key is pressed on a system-
level if
using python?


What has that todo with kernel programming? You can use e.g. pygame to 
get keystrokes. Or under linux, read (if you are root) the keyboard 
input file - I've done that to support several keyboards attached to a 
machine.


And the original question: no, python can't be used as kernel 
programming language. Amongst other reasons, performance & the GIL 
prevent that.


Diez


http://www.kernel-panic.it/programming/py-pf/

Of course you can code kernel routines in Python -- you are just calling 
the underlying C interface.  The GIL means you have to manage 
threadsafety on your own -- it doesn't imply kernel programming can not 
be done.


I understood the OP's question as "can one program kernelspace routines 
in python". Which I don't think is possible. And I don't see how py-pf 
does that either.


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


Re: Why is math.pi slightly wrong?

2008-05-23 Thread Nick Craig-Wood
Jerry Hill <[EMAIL PROTECTED]> wrote:
>  On Thu, May 22, 2008 at 12:32 PM, Dutton, Sam <[EMAIL PROTECTED]> wrote:
> > I've noticed that the value of math.pi -- just entering it at the 
> > interactive prompt -- is returned as 3.1415926535897931, whereas (as every 
> > pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the 
> > end.)
> >
> > Is this a precision issue, or from the underlying C, or something else? How 
> > is math.pi calculated?
> 
>  I believe this is an issue with the precision of IEEE floating point
>  numbers[1].  Those are the types of numbers used by the hardware
>  floating point processor on your CPU.  I'm not an expert, by any
>  stretch of the imagination, but I believe you have two choices to
>  represent pi as an IEEE double precision float:
> 
>  3.1415926535897931 (stored as 0x400921FB54442D18) or
>  3.1415926535897936 (stored as 0x400921FB54442D19)

Just in case you were wondering how you get those hex numbers (like I
was!)

  >>> import math
  >>> import struct
  >>> struct.pack(">d", math.pi).encode("hex")
  '400921fb54442d18'
  >>> struct.unpack(">d", "400921FB54442D18".decode("hex"))
  (3.1415926535897931,)
  >>> struct.unpack(">d", "400921FB54442D19".decode("hex"))
  (3.1415926535897936,)
  >>> 

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


Re: Relationship between GUI and logic?

2008-05-23 Thread inhahe
>
>> To be more specific, let's say I want to create a simple, 2D strategy
>> game. It will have a board layout like chess or checkers and the player
>> will move around the board. Let's say this is all I know, and perhaps I
>> don't even know *this* for sure either. Is it possible to write the
>> logic for such a game at this point?
>
> Maybe even this is possible.  But here you are not only drawing the line
> between GUI and logic but also within the logic part itself because the
> board layout isn't (just) a GUI issue.  If you have checkers, hexagons, or
> other shapes also has influence on the logic part, because you need
> slightly different algorithms for finding ways from tile `A` to tile `B`,
> or to decide when a piece is blocked by others, and how the rules to move
> pieces around look like.  Just imagine how to modify chess rules to a
> board with hexagonal patterns.  It would severely change the logic part.

If the GUI defines that it's a board layout like chess or 
checkers and the player will move around the board, it's hard to say what's 
left for the "logic" part to do.  I can't think of any generalization for 
the fact that it's a 2D strategy game.  You could have a 2-dimensional 
array, the size of which is determined by the GUI, but even motion on it 
would have to be defined by the GUI, in which case the GUI would simply be 
using the "logic" part for storing the array and accessing it via index 
values.  And then there's no reason not to put the array inside the GUI. 
Although it would help if only your "logic" part could provide persistence. 
Also, the "logic" part could provide many useful functions that games are 
likely to use, but then it's more like a library than anything else. 
Secondly, it's unclear whether the fact that it's a 2D strategy game was 
included in what he might not know, and in that possible case, strictly 
speaking, he didn't define anything that the logic part *does* know, and it 
being an example, one could theorize that that logically implies the "logic" 
part of the program is null.

>
>> Another example could be printing messages to the player. If I need to
>> say "You killed the monster!", is there a general way to write this, or
>> do I need to specifically refer to GUI widgets and methods, etc. in
>> order for it to be displayed properly?
>
> The observer pattern can be used here.  The GUI has to register a callback
> function with your logic engine and every time you want to inform the
> player about something, your game logic calls that function with the
> message.  It doesn't have to know if it will be rendered as graphic on
> screen, displayed as text in a terminal, or synthesized as sexy female
> computer voice.

If the function name to register the callback function is hard-coded into 
the logic part and into the GUI, then so can the name of the callback 
function itself be, so that it doesn't need to be a callback, barring only 
the possibility of the callback function being changed from one instance to 
the next by the particular GUI, and even that can be done without a callback 
simply by reassigning the name, or in C++ you could cast a pointer to 
function within the hard-coded function and call it and and change that 
pointer when desired.

Not that I know anything about MVC.





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


Re: can python do some kernel stuff?

2008-05-23 Thread Andrew Lee

Diez B. Roggisch wrote:

Andrew Lee schrieb:

Diez B. Roggisch wrote:

Jimmy schrieb:

On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:

Jimmy wrote:

Hi to all
python now has grown to a versatile language that can
accomplish tasks for many different purposes. However,
AFAIK, little is known about its ability of kernel coding.
So I am wondering if python can do some kernel coding that
used to be the private garden of C/C++. For example, can python
intercept the input of keyboard on a system level? someone told me
it's a kernel thing, isn't it?

http://wiki.python.org/moin/elmer


well, straightly speaking, how can I know a key is pressed on a system-
level if
using python?


What has that todo with kernel programming? You can use e.g. pygame 
to get keystrokes. Or under linux, read (if you are root) the 
keyboard input file - I've done that to support several keyboards 
attached to a machine.


And the original question: no, python can't be used as kernel 
programming language. Amongst other reasons, performance & the GIL 
prevent that.


Diez


http://www.kernel-panic.it/programming/py-pf/

Of course you can code kernel routines in Python -- you are just 
calling the underlying C interface.  The GIL means you have to manage 
threadsafety on your own -- it doesn't imply kernel programming can 
not be done.


I understood the OP's question as "can one program kernelspace routines 
in python". Which I don't think is possible. And I don't see how py-pf 
does that either.


Diez



OP: "I am wondering if python can do some kernel coding that
used to be the private garden of C/C++."

The answer is yes.  IPC and py-pf are examples.  If you don't think of 
packet filtering as kernel coding, I can understand.  But clearly the 
Python interfaces to fork(), waitpid(), signal(), alarm() and so forth 
are forays into the once private garden of C.

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


Re: php vs python

2008-05-23 Thread Erwin Moller

Andrew Lee schreef:

notbob wrote:
I'm not posting this just to initiate some religious flame war, though 
it's
the perfect subject to do so.  No, I actaully want some serious advice 
about
these two languages and since I think usenet is the best arena to find 
it,

here ya' go.

So, here's my delimna: I want to start a blog.  Yeah, who doesn't.  
Yet, I

want learn the guts of it instead of just booting up some wordwank or
whatever.  I started to learn python, but heard php was easier or 
faster or
more like shell scripting or... fill in the blank.  Anyway, so I 
change over

to learning php.  Then I run across that blog, Coding Horror, and start
reading articles like this:

http://www.codinghorror.com/blog/archives/001119.html

Now what?  Go back to python.  Soldier on with php?  What do I know?  Not
much.  I can setup mysql and apache,, but don't know how to use 'em, 
really.

I use emacs and run slackware and can fumble my way through bash scripts,
but I can't really write them or do lisp.  I've taken basic basic and 
basic
C, but am barely literate in html.  Sometimes it seems overwhelming, 
but I
persevere because it's more fun/challenging than video games, which 
bore me
to tears. 
Well, that's my actual question, then.  Is php really so bad I'm just

wasting my time?  Or is it really the quickest way to blog functionality?
Would I be better served in the long run learning python, which claims 
to be
easy as pie to learn/program (still looks hard to me).  I admit I'm no 
code
geek.  But, I'm not completely brain dead, either, and I need 
something to

keep my geezer brain sparking.  What say ye?

nb


Personally, I believe PHP would get you more productive more quickly for 
a blog, but it is a potentially brain damaging language in terms of 
really getting your juices flowing with programming.  It is not a 
general purpose language and suffers from all the limitations of of a 
tool designed for one job.  If you are interested in programming and the 
blog is your path to that, stick with Python!  In particular, immerse 
yourself in mod_python or look at a framework like Django or Pylons -- 
the learning curve is steep for any of these technologies but they are a 
full meal compared to saltine cracker and water of PHP.


Some statement Andrew.
Care to clarify that a little?
I don't know much Python (aside from a little in ZOPE), but I did a lot 
of Java, Perl, VB/ASP (juck), and a little C before I learned PHP.

I stopped using all in favor of PHP.

If your statement says PHP is abused a lot, yes. Because it is 
relatively easy to learn for new programmers, a lot of bad PHP coders 
exist.

But I saw them too in Java/Perl/etc.
And I am sure you can find them too coding Python.

It is perfectly possible to write clean good code in PHP.

Why do you say it 'tastes less' then Python?
I don't want to start a religious war, but am curious.
Who knows, maybe  I'll dump PHP and start using Python after your 
answer. ;-)


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


Re: php vs python

2008-05-23 Thread Jerry Stuckle

inhahe wrote:

PHP can do that.  There are also a number of templating engines
available.  The nice thing about PHP is you have a choice.


i just meant that php is sort of invented to combine html and code, so if 
you use python instead you should use a templating engine.  but i suppose 
it's useful for php too.





Not at all.  With PHP, it's possible to do so, but not required.  With 
Python, OTOH, you pretty much have to use a templating engine.


--
==
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
[EMAIL PROTECTED]
==
--
http://mail.python.org/mailman/listinfo/python-list


Re: php vs python

2008-05-23 Thread Jerry Stuckle

Andrew Lee wrote:

notbob wrote:
I'm not posting this just to initiate some religious flame war, though 
it's
the perfect subject to do so.  No, I actaully want some serious advice 
about
these two languages and since I think usenet is the best arena to find 
it,

here ya' go.

So, here's my delimna: I want to start a blog.  Yeah, who doesn't.  
Yet, I

want learn the guts of it instead of just booting up some wordwank or
whatever.  I started to learn python, but heard php was easier or 
faster or
more like shell scripting or... fill in the blank.  Anyway, so I 
change over

to learning php.  Then I run across that blog, Coding Horror, and start
reading articles like this:

http://www.codinghorror.com/blog/archives/001119.html

Now what?  Go back to python.  Soldier on with php?  What do I know?  Not
much.  I can setup mysql and apache,, but don't know how to use 'em, 
really.

I use emacs and run slackware and can fumble my way through bash scripts,
but I can't really write them or do lisp.  I've taken basic basic and 
basic
C, but am barely literate in html.  Sometimes it seems overwhelming, 
but I
persevere because it's more fun/challenging than video games, which 
bore me
to tears. 
Well, that's my actual question, then.  Is php really so bad I'm just

wasting my time?  Or is it really the quickest way to blog functionality?
Would I be better served in the long run learning python, which claims 
to be
easy as pie to learn/program (still looks hard to me).  I admit I'm no 
code
geek.  But, I'm not completely brain dead, either, and I need 
something to

keep my geezer brain sparking.  What say ye?

nb


Personally, I believe PHP would get you more productive more quickly for 
a blog, but it is a potentially brain damaging language in terms of 
really getting your juices flowing with programming.  It is not a 
general purpose language and suffers from all the limitations of of a 
tool designed for one job.  If you are interested in programming and the 
blog is your path to that, stick with Python!  In particular, immerse 
yourself in mod_python or look at a framework like Django or Pylons -- 
the learning curve is steep for any of these technologies but they are a 
full meal compared to saltine cracker and water of PHP.


And what job is that?  I have a lot of batch scripts written in PHP, for 
instance.


--
==
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
[EMAIL PROTECTED]
==
--
http://mail.python.org/mailman/listinfo/python-list


RE: Why is math.pi slightly wrong?

2008-05-23 Thread Dutton, Sam
Thanks for all the answers and comments.

>math.pi is exactly equal to 884279719003555/281474976710656, which is the 
>closest C double to the actual value of pi

So much for poor old 22/7...

Sam
 





SAM DUTTON
SENIOR SITE DEVELOPER

200 GRAY'S INN ROAD
LONDON
WC1X 8XZ
UNITED KINGDOM
T +44 (0)20 7430 4496
F 
E [EMAIL PROTECTED]
WWW.ITN.CO.UK

P  Please consider the environment. Do you really need to print this email?
Please Note:

 

Any views or opinions are solely those of the author and do not necessarily 
represent 
those of Independent Television News Limited unless specifically stated. 
This email and any files attached are confidential and intended solely for the 
use of the individual
or entity to which they are addressed. 
If you have received this email in error, please notify [EMAIL PROTECTED] 

Please note that to ensure regulatory compliance and for the protection of our 
clients and business,
we may monitor and read messages sent to and from our systems.

Thank You.


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


Re: can python do some kernel stuff?

2008-05-23 Thread Diez B. Roggisch


OP: "I am wondering if python can do some kernel coding that
used to be the private garden of C/C++."


"kernel coding" is pretty clear I'd say - coding a or in the kernel. Not 
coding that runs on an OS that happens to have a kernel.


The answer is yes.  IPC and py-pf are examples.  If you don't think of 
packet filtering as kernel coding, I can understand.  But clearly the 
Python interfaces to fork(), waitpid(), signal(), alarm() and so forth 
are forays into the once private garden of C.


Also not "kernel coding" in my book. system-near coding - yes. But not 
coding a kernel...


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


Re: php vs python

2008-05-23 Thread Michael Fesser
.oO(Andrew Lee)

>Personally, I believe PHP would get you more productive more quickly for 
>a blog, but it is a potentially brain damaging language in terms of 
>really getting your juices flowing with programming.  It is not a 
>general purpose language

Please elaborate.

>and suffers from all the limitations of of a 
>tool designed for one job.

Please elaborate.

And what "one" job are you talking about? There are many things possible
with PHP: web apps, shell scripts, daemons, GUI apps ...

>If you are interested in programming and the 
>blog is your path to that, stick with Python!

Where whitespace is more important than the code.

Seriously, it's just a question of personal taste and preferences. In
terms of capabilities there's absolutely no difference between PHP and
Python. You need a good understanding of programming in general for
both, the rest is just syntax and the available standard libraries.

>In particular, immerse 
>yourself in mod_python or look at a framework like Django or Pylons -- 
>the learning curve is steep for any of these technologies but they are a 
>full meal compared to saltine cracker and water of PHP.

If you don't like PHP, that's perfectly OK. But you should accept that
it's only a tool and just as good as the one who uses it. For me and
many others it's a quite good language, we're able to write clean and
efficient code with it in a rather short time.

PHP is much more than just crackers and water. Of course you should know
how to cook.

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


Re: where is the Write method of ElementTree??

2008-05-23 Thread gray . bowman
On May 23, 3:22 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I'm messing around with trying to write an xml file using
> > xml.etree.ElementTree.  All the examples on the internet show the use
> > of ElementTree.write(), although when I try to use it it's not
> > available, gives me ...
>
> >ElementTree(sectionElement).write("section.xml")
> > TypeError: 'module' object is not callable
>
> I guess you did
>
> from xml.etree import ElementTree
>
> Then you should do this:
>
> ElementTree.ElementTree(sectionElement).write("section.xml")
>
> sadly, the module names in ET are upper case and look like classes...
>
> Stefan

That was it!  Thanks to both of you for helping.

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


Re: php vs python

2008-05-23 Thread Duncan Booth
Erwin Moller 
<[EMAIL PROTECTED]> wrote:

> Why do you say it 'tastes less' then Python?
> I don't want to start a religious war, but am curious.
> Who knows, maybe  I'll dump PHP and start using Python after your 
> answer. ;-)

I may not be a good person to answer this since I don't know PHP: I don't 
have any religious objection to it, but I just never found it intuitive in 
the way I found Python fits my mindset.

On those rare occasions when I've helped someone who wanted advice I've 
found that my Python oriented viewpoint can be quite hard to translate to 
PHP. For example I'd suggest 'oh you just encode that as utf8' only to be 
told that there's no easy way to do that (have just Google'd it looks like 
there is now a way to do that but with a big red warning about it being 
EXPERIMENTAL and only use at your own risk).

(Looking at the example given for unicode_encode it appears to depend for 
its working on a global setting which isn't included in the example. I may 
have misunderstood the example but if I read that correctly its a good 
example of why PHP doesn't fit my brain.)

Anyway Google should find you plenty of articles comparing the languages. 
I'd say you use whichever feels right to you. I would also suggest you 
should try Python at least a bit (but since I don't intend to do the same 
for PHP you may not count my advice for much).

I found these pretty quickly:

http://python.about.com/od/gettingstarted/ss/whatispython_4.htm
http://wiki.w4py.org/python-vs-php.html


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling class method by name passed in variable

2008-05-23 Thread Bruno Desthuilliers

Nick Craig-Wood a écrit :

Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:

Can someone suggest an efficient way of calling method whose name is
passed in a variable?


 method = getattr(obj, 'method_name', None)
 if callable(method):
  method(args)


I think that that is needless LBYL...


From experience, it isn't.



   getattr(obj, 'method_name')(args)

Will produce some perfectly good exceptions


The problem is that you can't tell (without reading the exception's 
message and traceback etc) if the exception happened in you code or 
within the called method.


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


Re: Books for learning how to write "big" programs

2008-05-23 Thread Simon Brunning
On Thu, May 22, 2008 at 4:55 PM, duli <[EMAIL PROTECTED]> wrote:
> Hi:
> I would like recommendations for books (in any language, not
> necessarily C++, C, python) which have walkthroughs for developing
> a big software project ? So starting from inception, problem
> definition, design, coding and final delivery on a single theme
> or application.

With regard to the arcitecture of systems rather than process, there
are some good boos liked to from here:
. Patterns
of Enterprise Application Architecture in particular is a bit of a
classic.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-05-23 Thread Bruno Desthuilliers

Carl Banks a écrit :
(snip technically pedantic correction)

You know, even though you're technically correct, I'd like to see you
abandon this little crusade.  At this point it's more noisy than
helpful.

(snip)

Mmm... You're probably right. I tend to be way too pedantic sometimes. 
OTHO, there are people not even having the slightest clue here - I once 
was - and being corrected on similar things usually helped me. But yes, 
I'll try to refrain myself...

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


Re: php vs python

2008-05-23 Thread Michael Fesser
.oO(Duncan Booth)

>On those rare occasions when I've helped someone who wanted advice I've 
>found that my Python oriented viewpoint can be quite hard to translate to 
>PHP. For example I'd suggest 'oh you just encode that as utf8' only to be 
>told that there's no easy way to do that (have just Google'd it looks like 
>there is now a way to do that but with a big red warning about it being 
>EXPERIMENTAL and only use at your own risk).
>
>(Looking at the example given for unicode_encode it appears to depend for 
>its working on a global setting which isn't included in the example. I may 
>have misunderstood the example but if I read that correctly its a good 
>example of why PHP doesn't fit my brain.)

The only little problem is that PHP doesn't have native Unicode support
yet, which will change with PHP 6. But of course you can still use UTF-8
without any trouble, I do it all the time. You just have to keep in mind
that many string functions still work on bytes, not on characters, but
this can almost always be solved with the Multibyte extension. Apart
from that there's no problem with PHP and UTF-8. It's also easily
possible to convert between various encodings using the iconv extension.

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


Advice from senior Members

2008-05-23 Thread flit
Hello All,

I am looking for some experience from the senior members.
Now I am doing a simple desktop application, this application will
have 3 main functions:

1- Read information about the desktop system;
2- Interact with the user;
3- Send information to a server.

The first part, reading information about the desktop system, is
already done.
And now I am starting to make the gui for the user, that is when the
question appear:
"What is the best way to make it? divide in files? by classes or
functions?"
I have now one big file with all functions to get the desktop
information.
Should I make one file for the visual functions (wxpython)? another
for the server?
Is productive to divide in files? what is the best way?

It seems like a naive question, maybe easy one, but I am willing to
enjoy the experience from the most senior programmers here.

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


Re: Relationship between GUI and logic?

2008-05-23 Thread Marc 'BlackJack' Rintsch
On Fri, 23 May 2008 07:14:08 -0400, inhahe wrote:

> If the GUI defines that it's a board layout like chess or 
> checkers and the player will move around the board, it's hard to say what's 
> left for the "logic" part to do.

The logic part has the rules how you may move the pieces.  The GUI
shouldn't have to know how a knight, bishop, or queen can move or
what castling is.

> I can't think of any generalization for the fact that it's a 2D strategy
> game.  You could have a 2-dimensional array, the size of which is
> determined by the GUI,

No it isn't!  The size is independent from the GUI.  Most 2D strategy
games have maps that are way large than the GUI displays at once.  You
almost always see just a portion of the model of the game world in the GUI.

> but even motion on it would have to be defined by the GUI, in which case
> the GUI would simply be using the "logic" part for storing the array and
> accessing it via index values.  And then there's no reason not to put
> the array inside the GUI.

There are plenty of reasons.  You tie the game to one GUI this way.  No
way to change the GUI toolkit or to split the game into server (game
logic) and client (different GUIs, web application).

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


Re: Relationship between GUI and logic?

2008-05-23 Thread John Salerno
"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in 
message news:[EMAIL PROTECTED]
> Ever heard of the "Model/View/Controller" pattern ?

Yes, I have, but I probably don't understand it well enough yet. For 
example, I don't  really know what is meant by phrases like "build a model", 
"the view registers itself with the model", "interations are sent to the 
appropriate controller" -- I may understand them literally, but I get the 
feeling that the implementation of these ideas are beyond me. I think it's 
mainly an issue of terminology, so probably I should just read up on MVC.

> The user interface doesn't need to be graphical. There were games and 
> emails clients and text editors before GUIs existed, you know ?

Of course, but I'm specifically asking about creating a program that has a 
GUI, and even more specifically it would be wxPython. 


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


WXpython Question

2008-05-23 Thread Gandalf
I try to reach a specific wx StaticText element's text and to change
it by clicking on a button


now let's say the this is my element:

wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE)


And this is my EVT_BUTTON bind function :

def OnClick(event):

which code shude i enter to change "hello" to "goodbay"?

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


Re: Advice from senior Members

2008-05-23 Thread Mike Driscoll
On May 23, 8:02 am, flit <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> I am looking for some experience from the senior members.
> Now I am doing a simple desktop application, this application will
> have 3 main functions:
>
> 1- Read information about the desktop system;
> 2- Interact with the user;
> 3- Send information to a server.
>
> The first part, reading information about the desktop system, is
> already done.
> And now I am starting to make the gui for the user, that is when the
> question appear:
> "What is the best way to make it? divide in files? by classes or
> functions?"
> I have now one big file with all functions to get the desktop
> information.
> Should I make one file for the visual functions (wxpython)? another
> for the server?
> Is productive to divide in files? what is the best way?
>
> It seems like a naive question, maybe easy one, but I am willing to
> enjoy the experience from the most senior programmers here.
>
> Thanks

I would investigate the MVC (model-view-controller) architecture. That
is what wxPython advocates as does TurboGears and Django. The idea is
to keep your view (the GUI) separate from the logic (the controller)
and (I think) the model controls the data access.

Anyway, it's explained much better at these sites:

http://wiki.wxpython.org/ModelViewController
http://wiki.wxpython.org/wxPython%20Patterns
http://en.wikipedia.org/wiki/Model-view-controller

I try to keep my GUI code as decoupled from my logic code as possible.

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


Re: WXpython Question

2008-05-23 Thread Mike Driscoll
On May 23, 8:24 am, Gandalf <[EMAIL PROTECTED]> wrote:
> I try to reach a specific wx StaticText element's text and to change
> it by clicking on a button
>
> now let's say the this is my element:
>
> wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE)
>
> And this is my EVT_BUTTON bind function :
>
> def OnClick(event):
>
> which code shude i enter to change "hello" to "goodbay"?
>
> thanks


You're probably looking for SetLabel(). So if you do something like
this to instantiate the StaticText:

self.myText = wx.StaticText(panel, 15, "Hello" ,(30, 70) ,
style=wx.ALIGN_CENTRE)

Then you can change your text by adding this to your OnClick event
handler:

self.myText.SetLabel("goodbye")

Have fun! And remember, there's a great wxPython mailing list too:

http://www.wxpython.org/maillist.php

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


Re: Calling class method by name passed in variable

2008-05-23 Thread Nick Craig-Wood
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood a ?crit :
> > Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> >>> Can someone suggest an efficient way of calling method whose name is
> >>> passed in a variable?
> >>>
> >>  method = getattr(obj, 'method_name', None)
> >>  if callable(method):
> >>   method(args)
> > 
> > I think that that is needless LBYL...
> 
>   From experience, it isn't.

> >getattr(obj, 'method_name')(args)
> > 
> > Will produce some perfectly good exceptions
> 
>  The problem is that you can't tell (without reading the exception's 
>  message and traceback etc) if the exception happened in you code or 
>  within the called method.

I guess it depends on whether you are expecting it to ever fail or
not.  If a user types in method_name then yes you are right checking
stuff and producing a nice error is good.  However if it is part of
your internal program flow and you never expect it to go wrong in
normal operation then I'd be quite happy with the exception and
backtrace to debug the problem.

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


Re: WXpython Question

2008-05-23 Thread Gandalf
On May 23, 3:29 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On May 23, 8:24 am, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > I try to reach a specific wx StaticText element's text and to change
> > it by clicking on a button
>
> > now let's say the this is my element:
>
> > wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE)
>
> > And this is my EVT_BUTTON bind function :
>
> > def OnClick(event):
>
> > which code shude i enter to change "hello" to "goodbay"?
>
> > thanks
>
> You're probably looking for SetLabel(). So if you do something like
> this to instantiate the StaticText:
>
> self.myText = wx.StaticText(panel, 15, "Hello" ,(30, 70) ,
> style=wx.ALIGN_CENTRE)
>
> Then you can change your text by adding this to your OnClick event
> handler:
>
> self.myText.SetLabel("goodbye")
>
> Have fun! And remember, there's a great wxPython mailing list too:
>
> http://www.wxpython.org/maillist.php
>
> Mike

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


Re: KeyError in pickle

2008-05-23 Thread christof
On 23 Mai, 10:48, Peter Otten <[EMAIL PROTECTED]> wrote:
> christof wrote:
> > I am using pickle/unpickle to let my program save its documents to
> > disk. While this it worked stable for a long time, one of my users now
> > complained, that he had a file which can't be loaded.
>
> > The traceback is:
>
> > File "pickle.pyo", line 1374, in loads
> > File "pickle.pyo", line 858, in load
> > KeyError: 'A'
>
> > Does anybody know this problem. How this can happen and how can I
> > avoid it?
>
> Is this reproducible? How? If not I would guess that the file is corrupted.
>
> Peter

I found the problem: the user did a text export and gave the exported
file the wrong extension. So: the file was not valid python pickle. I
should add a type signature to fhe file format to avoid this.

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


Re: Why is math.pi slightly wrong?

2008-05-23 Thread J. Cliff Dyer
On Thu, 2008-05-22 at 15:06 -0400, Dan Upton wrote:
> Who wants to verify that that's correct to that many digits? ;)

Verified.

I checked it against the million digits on piday.org, by putting each
into a string, stripping out spaces and newlines, and doing:

>>> piday[:len(clpy)] == clpy
False
>>> piday[:len(clpy)-1] == clpy[:-1]
True
>>> print piday[len(clpy)-10:len(clpy)+1]
44893330963
>>> print clpy[-10:]
4489333097
>>> 

So the last digit doesn't match, even accounting for rounding, but
that's probably because it was calculated to the bit, not to the digit.


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


Re: Python treeview and recursion: help needed

2008-05-23 Thread Mailing List SVR
Il giorno ven, 23/05/2008 alle 09.20 +0200, Mailing List SVR ha scritto:
> Hi, 
> 
> I have a database with the following structure:
> 
> idname  sublevel
> 
> for example
> 
> 1 Node1 None
> 2 Node2 1
> 3 Node3 2
> 4 Node4 None
> 5 Node5 1
> 6 Node6 5
> 
> 
> 
> 
> where Node1 and Node4 are treeview's master nodes, Node2 is a subnode of
> Node1, Node3 is a subnode of Node2, Node5 is a subnode of Node1 and
> Node6 a subnode of Node5 and so on
> 
> I need a recursive function to populate treeview and I'm stuck on this
> function :confused:
> 
> I need a list where I have the master node with child node inside and if
> a child node as others child nodes, I need thess nodes inside the child
> nodes.
> 
> Something like this:
> 
> [
> {"id":1,"name":"Node1","Childs":[{"id:2","name":"Node2","Childs":[{"id":3,"name":"Node3","Childs":[]}]},
> {"id":5,
> "name":"Node5","Childs":[{"id":6,"name":"Node6","Childs":[]}]}]},{"id":4,"name":"Node4","Childs":[]}
>   
> ]
> 
> I'm using django so I access the data as 
> 
> all=Data.objects.all()
> 
> and I can do something like
> 
> for a in all:
>   print a.id
>   print a.name
>   
> to get database value.
> 
> Any help is appreciated,
> 
> thanks,
> Nicola
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

only for the records attacched is a working solution, maybe not the best
one but a working one,

regards
Nicol

#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
#sys.path.append('/var/www/videosorveglianza')
import sys
sys.path.append('/home/nicola/django/videosorveglianza')
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.conf import settings
from videosorveglianza.commands.Classi import *
from videosorveglianza.commands.models import *

zones=[]

def ottienifigli(zona):
	zone=Zone.objects.filter(sublivello_di=zona)
	figli=[]
	for z in zone:
		figli.append({
'Zona_id':z.id,
'Id_padre':z.sublivello_di.id,
		})
		ottienifigli(z)
	zones.append({
		'Zona_id':zona.id,
		'Figli':figli
	})

def rimuoviduplicati(lista):
	for s in lista:
		j=-1
		i=0
		for s1 in lista:
			j=j+1
			if s['Zona_id']==s1['Zona_id']:
i=i+1
if i >1:
	del lista[j]


listaid=[]
def generaid():
	zone=Zone.objects.all()
	# se il sublivello e' nullo allora e' una zona padre
	for zona in zone:
		#if zona.sublivello_di is None:
		listaid.append(zona.id)
	#print padri

padri=[]
def generapadri():
	zone=Zone.objects.all()
	# se il sublivello e' nullo allora e' una zona padre
	for zona in zone:
		if zona.sublivello_di is None:
			padri.append(zona.id)
	#print padri

def visitaalbero():
	zone=Zone.objects.all()
	for z in zone:
		ottienifigli(z)
	rimuoviduplicati(zones)
	print zones

visitaalbero()
generaid()
generapadri()

def accoppia(z):
	if z['Zona_id'] in listaid:
		i=-1
		for c in z['Figli']:
			i=i+1
			for z1 in zones:
if c['Zona_id'] ==z1['Zona_id']:
	z['Figli'][i]=z1
	accoppia(z['Figli'][i])
	#print "\n\n\n\n"
	#print zones

def accoppianodi():
	for z in zones:
		accoppia(z)

darimuovere=[]
def childdarimuovere():
	i=-1
	for z1 in zones:
		i=i+1
		if z1['Zona_id'] not in padri:
			darimuovere.append(i)

accoppianodi()
print "\n\n\n\n"
print zones
print "\n\n\n\n"
childdarimuovere()
print darimuovere
k=-1
for s in darimuovere:
	k=k+1
	del zones[s-k]
	print s
	#print type(s)

print "\n\n\n\n"

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

Re: Python is slow

2008-05-23 Thread Grant Edwards
On 2008-05-23, RPM1 <[EMAIL PROTECTED]> wrote:
> Larry Bates wrote:
>> If your Python program is slow, you have almost assuredly
>> approached it with a wrong method or algorithm.
>
> I agree for most applications.  There are however times where
> Python just isn't fast enough, and that's usually when people
> write extension modules.

Writing an extension modules is probably pretty far down the
list.  What usually happens is people

 a) Figure out they're using the wrong algorithm

 b) Find the library module that already does the "bottleneck"
operations. 

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


Re: Python is slow

2008-05-23 Thread Eric Brunel

On Fri, 23 May 2008 12:48:56 +0200, > wrote:


"inhahe" <[EMAIL PROTECTED]> writes:

planets are spherical (all implementations of Python are not natively
compiled (and you said for whatever definition)), and b) It's a far cry  
to

imagine a planet coming into being that's not spherical (a language as
dynamic as Python, or most other scripting languages, would be either
extremely difficult or impossible to make a native compiler for).


There are native Python compilers, see psyco and pypy.


... and C/C++ interpreters; see:
http://root.cern.ch/twiki/bin/view/ROOT/CINT
--
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

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


Genuine Lifetime Income!! Earn!! = 10,000 US Dollars per month without Investmen

2008-05-23 Thread cashm491
You Have Finally Found It Genuine Lifetime Income!!
Earn!! à 10,000 US Dollars per month without Investment
http://seniorfriendfinder.com/go/g970599-pmem
Earn!! à 10,000 US Dollars per month without Investment
By working only one hour per day from the cyber café or PC
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyserial and file open conflict?

2008-05-23 Thread Grant Edwards
On 2008-05-23, Peter <[EMAIL PROTECTED]> wrote:
> On 15 Maj, 19:37, Grant Edwards <[EMAIL PROTECTED]> wrote:
>> On 2008-05-15, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>
>> > I have a small but rather annoying problem withpyserial. I want to
>> > open a file on disk for reading and then open a com-port, write lines
>> > from the file to the port and then read something back and compare it
>> > to the next line in the file. Should be simple. And it is, apart from
>> > the fact that the file seems to be doubled ...? Or it loops through
>> > the file twice.
>>
>> > If I exclude the "import serial" it works.
>>
>> > Any ideas?
>>
>> Your problem is in line 117 of your program.
>
> Do you have to much time?

"Do you have a sense of irony?" he asked, already knowing the answer.

-- 
Grant

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


Re: php vs python

2008-05-23 Thread Duncan Booth
Michael Fesser <[EMAIL PROTECTED]> wrote:

> .oO(Duncan Booth)
> 
>>On those rare occasions when I've helped someone who wanted advice
>>I've found that my Python oriented viewpoint can be quite hard to
>>translate to PHP. For example I'd suggest 'oh you just encode that as
>>utf8' only to be told that there's no easy way to do that (have just
>>Google'd it looks like there is now a way to do that but with a big
>>red warning about it being EXPERIMENTAL and only use at your own
>>risk). 
>>
>>(Looking at the example given for unicode_encode it appears to depend
>>for its working on a global setting which isn't included in the
>>example. I may have misunderstood the example but if I read that
>>correctly its a good example of why PHP doesn't fit my brain.)
> 
> The only little problem is that PHP doesn't have native Unicode
> support yet, which will change with PHP 6. But of course you can still
> use UTF-8 without any trouble, I do it all the time. You just have to
> keep in mind that many string functions still work on bytes, not on
> characters, but this can almost always be solved with the Multibyte
> extension. Apart from that there's no problem with PHP and UTF-8. It's
> also easily possible to convert between various encodings using the
> iconv extension. 
> 
As I remember it the problem was that the data was stored in a database 
in latin-1 but the HTML page had to be in utf-8 (because the rest of the 
server and therefore all the page skins were already in utf-8). In 
python that would be a trivial conversion but I was told that in PHP it 
wasn't. 

Also it was PHP4 and as I understand it updating to a more recent 
version was non-trivial. Of course sometimes updating Python code to a 
newer version is also non-trivial: Zope in particular is very version 
specific but in most cases anything written in pure Python will be 
compatible with more recent versions.

But one small example isn't really the point. It's that the whole way 
Python works seems *to me* to make sense and (mostly) fits together 
cleanly and consistently. YMMV

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Producing multiple items in a list comprehension

2008-05-23 Thread Yves Dorfsman
Peter Otten <[EMAIL PROTECTED]> wrote:

> The speed gain is significant. Why should I throw away useful information if
> I have it? 

My thinking was that it wasn't generic enough, and I was looking for a
solution that would work for more generic problem. I agree, I shouldn't
have used the world "elegant" here, more generic would have been better.

> I'd even be willing to convert one arbitrary iterable to a list
> to get the length information.

> $ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100" "aa = list(a);
> items=[None]*(2*len(aa)); items[::2] = aa; items[1::2] = b"
> 1 loops, best of 3: 29.5 usec per loop

Yes, I like that, it is as generic as the reduce one.


> are more complicated than elegant. Not recommended.

You proved your point. Every book and webpage out there says that
functional solutions are faster than loops, that's why I tried hard not
to use a loop, and "reduce" is considered functional - I should have
timed it.


Yves.
http://www.SollerS.ca

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


Re: Code For Five Threads To Process Multiple Files?

2008-05-23 Thread tdahsu
On May 23, 12:20 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Thu, 22 May 2008 11:03:48 -0700 (PDT), [EMAIL PROTECTED] declaimed the
> following in comp.lang.python:
>
> > Ah, well, I didn't get any other responses, but here's what I've done:
>
>         Apparently the direct email from my work address did not get through
> (I don't have group posting ability from work).
>
> > loopCount = 0
> >                 for l in range(len(self.filesToProcess)):
> >                     threads = []
> >                     try:
>
> > threads.append(threading.Thread(target=self.processFiles(self.filesToProcess[loopCount
> > +l])))
>
>         Python lists index from 0... So this will be 0+0, first entry in the
> file list
>
>
>
> > threads.append(threading.Thread(target=self.processFiles(self.filesToProcess[loopCount
> > +2])))
>
>         This is 0+2, THIRD entry in the file list -- you've just skipped
> over the second entry...
>
> > threads.append(threading.Thread(target=self.processFiles(self.filesToProcess[loopCount
> > +3])))
>
> > threads.append(threading.Thread(target=self.processFiles(self.filesToProcess[loopCount
> > +4])))
>
> > threads.append(threading.Thread(target=self.processFiles(self.filesToProcess[loopCount
> > +5])))
>
>         Very ugly... Also going to fail for other reasons... Consider:
>
> filestoprocess = [ 'file1', 'file2', 'file3' ]
> for jnk in range(len(filestoprocess)):  #this will loop three times!
>                                                                               
>   #jnk = 0, 1, 2
>
>         You proceed to create FIVE threads (or try to) when there are only
> THREE files... It will fail as soon as it tries loopCount+3 (fourth
> entry in a three element list)
>
> >                         msg = "Processing file...\n"
> >                         for thread in threads:
> >                             wx.CallAfter(self.textctrl03.write(msg),
> > thread.start())
>
>         Is this running as the main controller of some GUI? if so...
>
> >                         for thread in threads:
> >                             thread.join()
>
>         Your GUI will essentially freeze since it can't process events
> (including screen updates) until the entire function you are in returns
> to the event handler... But .join() blocks until the specified thread
> really finishes...
>
> >                         loopCount += 5
> >                     except IndexError:
> >                         pass
>
>         BAD style -- if you are going to trap an exception, you should do
> something with it... But then, the only reason you would GET this
> exception is because the preceding code is looping too many times
> relative to the number of files...
>
>         As shown, with three files, you will create the first thread (0) for
> first file, skip the second file creating the second thread (1) for the
> third file, and raise an exception on trying to create the third thread
> (2) when you try to access a fourth file in the list.  The exception
> will be raised -- SKIPPING over the thread.start() calls, and skipping
> the thread.join() calls. You then ignore the error, and go back to the
> start of the loop where the index is now "1"... AND reset the thread
> list, so threads 0&1 are forgotten, never started, never joined, garbage
> collected...
>
>         Again, you now create a thread (0) giving it the second file (since
> loopCount was never incremented, and the first thread is using loopCount
> + ), create thread (1) giving it the third file, raise the
> exception... repeat
>
>
>
> > It works, and it works well.  It starts five threads, and processes
> > five files at a time.  (In the "self.processFiles" I read the whole
> > file into memory using readlines(), which works well.)
>
>         It only works as long as loopCount+5 is less than the number of
> files in the list... AND at that, it skips one file and double processes
> another...
>
> > Of course, now the wx.CallAfter function doesn't work... I get
> > "TypeError: 'NoneType' object is not callable" for every time it is
> > run...
>
>         Probably because it wants you to supply it with one or two
> /callable/ functions... but you are actually calling the functions and
> passing it the results of the called functions (and they aren't
> returning anything -- None).
>
>         Ignoring GUI stuff... here is a simple one-job threadpool algorithm
> -- you have to plug in the file list and the actual processing work. It
> creates n-threads; and those threads pull the work off of a common
> queue; the main program only has to fill the queue with the work to be
> done, and stuff a sentinal value onto the queue when it wants the
> threads to die -- which would be before shutdown of the program (create
> the pool at start-up, leave the threads blocked on the .get() until you
> need one to process...
>
> -=-=-=-=-=-=-=-
> #
> #       Example code for a pooled thread file processor
> #       NOT EXECUTABLE as is -- there is no cod

Re: Misuse of list comprehensions?

2008-05-23 Thread duncan smith

Simon Forman wrote:

On May 21, 4:36 am, Bruno Desthuilliers  wrote:

Simon Forman a écrit :




On May 20, 8:58 am, Paul McGuire <[EMAIL PROTECTED]> wrote:

On May 20, 10:50 am, [EMAIL PROTECTED] wrote:

You don't need all those conditionals. A set differs from a list
precisely in the fact that each element is unique. And since the
function is expecting "s" to be an iterable object, it can be
constructed even without a for loop:
def compress(s):
return list(set(s))
That does the trick.

Only if order does not need to be maintained.  list(set(s)) will not
necessarily keep the unique characters in the order they are seen.
We'll have to check with the OP to see if this is important (I just
assumed that it was because of the use of list comps).
-- Paul

If order is important, you can use sorted() instead of list() like so:
def compress(s):
new = sorted(set(s), key=s.index)
return return ''.join(new)

This won't still preserve the *original* order.



I don't understand.

new will contain each unique item in s, sorted in order of the items'
first occurance in s, right?
There are other ways to do it (other functions that could be passed to
sorted() as the key arg) of course, but this seems like a good value
of "original order", no? :)

Regards,
~S


But, I think, worst case quadratic performance through generating all 
the indices.


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


Re: Relationship between GUI and logic?

2008-05-23 Thread Bruno Desthuilliers

John Salerno a écrit :
"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in 
message news:[EMAIL PROTECTED]

Ever heard of the "Model/View/Controller" pattern ?


Yes, I have, but I probably don't understand it well enough yet. For 
example, I don't  really know what is meant by phrases like "build a model",


An abstract, logical representation of your board and players, which 
have a state (ie : board has X cells, player1 is on cell (x, y) and 
player2 on cell (x', y')) and behaviour (ie : player2.move_to(x, y)) 
that changes the state.



"the view registers itself with the model",


This is the Observer pattern. The view is passed the model when 
instanciated, and calls model.register(self). When the model changes 
it's state, it calls back the '.notify()' method of each of the 
registered views (a same model can have multiple views at the same time).


"interactions are sent to the 
appropriate controller"


In a typical GUI, the controllers are the event handlers (or are called 
from the event handlers - depending on how the GUI works). The system 
dispatch the events to the appropriate event handlers.


-- I may understand them literally, but I get the 
feeling that the implementation of these ideas are beyond me. I think it's 
mainly an issue of terminology, so probably I should just read up on MVC.


Probably, yes !-)

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


Re: php vs python

2008-05-23 Thread Michael Fesser
.oO(Duncan Booth)

>Michael Fesser <[EMAIL PROTECTED]> wrote:
>
>> The only little problem is that PHP doesn't have native Unicode
>> support yet, which will change with PHP 6. But of course you can still
>> use UTF-8 without any trouble, I do it all the time. You just have to
>> keep in mind that many string functions still work on bytes, not on
>> characters, but this can almost always be solved with the Multibyte
>> extension. Apart from that there's no problem with PHP and UTF-8. It's
>> also easily possible to convert between various encodings using the
>> iconv extension. 
>> 
>As I remember it the problem was that the data was stored in a database 
>in latin-1 but the HTML page had to be in utf-8 (because the rest of the 
>server and therefore all the page skins were already in utf-8). In 
>python that would be a trivial conversion but I was told that in PHP it 
>wasn't.

It would have been trivial in PHP as well, assuming the DB was MySQL,
which could have done this conversion automatically when sending the
data to the script.
 
>But one small example isn't really the point. It's that the whole way 
>Python works seems *to me* to make sense and (mostly) fits together 
>cleanly and consistently. YMMV

Fair enough. The nature of PHP as being a grown language has its
advantages, but also a lot of drawbacks, which are hard to solve.

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


Re: Relationship between GUI and logic?

2008-05-23 Thread David C. Ullrich
On Fri, 23 May 2008 09:13:50 -0400, "John Salerno"
<[EMAIL PROTECTED]> wrote:

>"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in 
>message news:[EMAIL PROTECTED]
>> Ever heard of the "Model/View/Controller" pattern ?
>
>Yes, I have, but I probably don't understand it well enough yet. For 
>example, I don't  really know what is meant by phrases like "build a model", 
>"the view registers itself with the model", "interations are sent to the 
>appropriate controller" -- I may understand them literally, but I get the 
>feeling that the implementation of these ideas are beyond me. 

I doubt that.

I've done things like this. I ended up with just a Model and a View,
no Controller. I assumed that meant I was being Bad - I read once
that that often happens, specifically with GUI programs.

An example, certainly not meant to be definitive, maybe not
even right, probably not "right", but illustrating explicitly
what those terms you claim not to understand might mean
in an implementation:

class Model:
  """Encapsulates an abstract version of the game:
Knows nothing about how the players make moves,
the moves are reported to the model via the 
ProcessMove method. Knows nothing about how the
state of the game is displayed to the players;
that's handled by the view or views. The model
might contain a matrix, where the entry in each
cell is None or a certain Piece object. The model
knows that if a certain Cell contains a King then
it's legal to move that King to this Cell but
not to that Cell - that's part of the rules of the
game, something the View knows nothing about"""

  def __init__(self):
#set up internal state, for example
#self.board = [[None]*8]*8
#and then self.board[0,4] = Queen[WhitePlayer],
#etc. Whatever...

self.views = []

#or just self.view = None if there's
#no reason for multiple views. When I did
#something like this once I decided at the
#end that I should have allowed multiple
#views even though there was only one to start,
#because functionality that got added to the view
#could have been done more cleanly by creating
#a second view (one view being the display and
#another being spoken messages)

  def RegisterView(self, view):
self.views.append(view)
#or just self.view = view

  def UpdateViews(self):
for view in self.views:
  view.UpdateDisplay(self)

  #or UpdateView(self): if self.view: self.view.UpdateDisplay(self)

  def ProcessMove(self, move):
"""Model recieves "messages" from View here."""
#modify internal state depending on the
#information passed in "move",
#for example move might say that the Piece in
#a certain Cell was dragged to another Cell.
#Here in ProcessMove you decide whether that's
#a legal move, and if so what effect it should
#have on the state of the game. Update state, then

self.UpdateViews()

  #or there could be more than one "Process" method
  #if there are various different sorts of things the
  #players might do

class Square:
  def __init__(self, row, col):
self.row = row
self.col = col

#say a move is a drag from one square to another:

class Move:
  def __init__(self, start, end)
self.start = start
self.end = end

#wrote that out explicitly just to emphasize that
#the Move object, which the View passes to the
#Model as a message, doesn't know anything
#about the details of the display and also doesn't
#know anything about the rules of the game...

class View:

  def __init__(self, game):
#set up the wxPython stuff
self.game = game
self.game.RegisterView(self)
Bind(self, VariousEvents, VariousHandlers)

  def VariousHandlers(self, evt)
#figure out what the players just did based
#on evt. Maybe a player has just dragged a piece
#from one square to another. figure out the row
#and col of the start and end squares from 
#information in evt.

#Now tell the Model what just happened:

self.game.ProcessMove(Move(Square(row1, col1),Square(row2, col2)))

  def UpdateDisplay(self):
#look at self.game to figure out what pieces
#go where, then draw them on the screen.
wx.This
wx.That

game = Model()
view = View(game)

>I think it's 
>mainly an issue of terminology, so probably I should just read up on MVC.
>
>> The user interface doesn't need to be graphical. There were games and 
>> emails clients and text editors before GUIs existed, you know ?
>
>Of course, but I'm specifically asking about creating a program that has a 
>GUI, and even more specifically it would be wxPython. 
>

David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest: Calling tests in liner number order

2008-05-23 Thread John Roth
On May 23, 3:36 am, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> Some time ago I asked whether is would be possible that unittest would
> perform the test in order of appearence in the file.
>
> The answers seemed to be negative. Since I really would like this
> behaviour I took the trouble of looking throught the source and
> I think I found a minor way to get this behaviour.
>
> Now my questions are:
>
> Are other people interested in this behavior?

I'm not. If there are any changes in the current behavior I'd much
prefer that unittest create a random permutation as a way of flushing
out intertest dependencies.

> Does the following patch has a chance of being introduced in the
> standard python distribution?

I certainly hope not!

John Roth
Python FIT

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


Re: Database Query Contains Old Data

2008-05-23 Thread John Nagle

Paul Boddie wrote:

On 21 Mai, 15:22, [EMAIL PROTECTED] wrote:

I did and I confirmed this by modifying the data, selecting it from
the mysql command line client to verify the changes, then running the
report again. If I exit the application and then start it again,
everything works as expected until the second instance of the report
is run.


Note that if you have a connection open in your program, especially if
that connection has already been used to select data, it may be the
case that you then have to perform a rollback or commit before
attempting to access newly added data. 


Exactly.  Although it seems counterintutive, it's not enough
to do a COMMIT after UPDATE and INSERT operations.  You also have to
do a COMMIT after a SELECT if you're going to reuse the database handle
and do another SELECT.  Otherwise, you reread the same data forever.

COMMIT, by the way, is per database handle, so if you have
multiple database handles, each needs to handle its own COMMIT needs.

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


Re: can python do some kernel stuff?

2008-05-23 Thread Jimmy
On May 23, 5:53 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Jimmy schrieb:
>
> > On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:
> >> Jimmy wrote:
> >>> Hi to all
> >>> python now has grown to a versatile language that can
> >>> accomplish tasks for many different purposes. However,
> >>> AFAIK, little is known about its ability of kernel coding.
> >>> So I am wondering if python can do some kernel coding that
> >>> used to be the private garden of C/C++. For example, can python
> >>> intercept the input of keyboard on a system level? someone told me
> >>> it's a kernel thing, isn't it?
> >>http://wiki.python.org/moin/elmer
>
> > well, straightly speaking, how can I know a key is pressed on a system-
> > level if
> > using python?
>
> What has that todo with kernel programming? You can use e.g. pygame to
> get keystrokes. Or under linux, read (if you are root) the keyboard
> input file - I've done that to support several keyboards attached to a
> machine.
>
> And the original question: no, python can't be used as kernel
> programming language. Amongst other reasons, performance & the GIL
> prevent that.
>
> Diez

sorry, my aim is not limited to one particular program. Yes, many
library can
permit you to respond to keyboard event, however, what I want is a
universal
function. as long as a key is pressed, no matter where, my program can
repond.

I am quite strange with this topic. But according to my understanding,
any event, keyboard event
for example, once triggered, will be dilivered by keyboard driver to X
system, and then
any running program can either choose to respond or ignore. So my
question can be translated to:
how to make my program respond ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest: Calling tests in liner number order

2008-05-23 Thread Quentin Gallet-Gilles
I personally don't see any benefit in this approach. By definition,
unittests should be independent, so the order argument suggests a deeper
issue.  What's your use case ?

Quentin

On Fri, May 23, 2008 at 11:36 AM, Antoon Pardon <[EMAIL PROTECTED]>
wrote:

> Some time ago I asked whether is would be possible that unittest would
> perform the test in order of appearence in the file.
>
> The answers seemed to be negative. Since I really would like this
> behaviour I took the trouble of looking throught the source and
> I think I found a minor way to get this behaviour.
>
> Now my questions are:
>
> Are other people interrested in this behaviour?
> Does the following patch has a chance of being introduced in the
> standard python distribution?
>
> *** /usr/lib/python2.5/unittest.py  2008-04-17 16:26:37.0 +0200
> --- unittest.py 2008-05-23 11:19:57.0 +0200
> ***
> *** 570,575 
> --- 570,577 
>  """
>  def isTestMethod(attrname, testCaseClass=testCaseClass,
> prefix=self.testMethodPrefix):
>  return attrname.startswith(prefix) and
> callable(getattr(testCaseClass, attrname))
> + def getlinenr(name):
> + return getattr(testCaseClass,
> name).im_func.func_code.co_firstlineno
>  testFnNames = filter(isTestMethod, dir(testCaseClass))
>  for baseclass in testCaseClass.__bases__:
>  for testFnName in self.getTestCaseNames(baseclass):
> ***
> *** 577,582 
> --- 579,586 
>  testFnNames.append(testFnName)
>  if self.sortTestMethodsUsing:
>  testFnNames.sort(self.sortTestMethodsUsing)
> + else:
> + testFnNames.sort(key=getlinenr)
>  return testFnNames
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: can python do some kernel stuff?

2008-05-23 Thread Jimmy
On May 23, 11:14 pm, Jimmy <[EMAIL PROTECTED]> wrote:
> On May 23, 5:53 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Jimmy schrieb:
>
> > > On May 23, 3:05 pm, Andrew Lee <[EMAIL PROTECTED]> wrote:
> > >> Jimmy wrote:
> > >>> Hi to all
> > >>> python now has grown to a versatile language that can
> > >>> accomplish tasks for many different purposes. However,
> > >>> AFAIK, little is known about its ability of kernel coding.
> > >>> So I am wondering if python can do some kernel coding that
> > >>> used to be the private garden of C/C++. For example, can python
> > >>> intercept the input of keyboard on a system level? someone told me
> > >>> it's a kernel thing, isn't it?
> > >>http://wiki.python.org/moin/elmer
>
> > > well, straightly speaking, how can I know a key is pressed on a system-
> > > level if
> > > using python?
>
> > What has that todo with kernel programming? You can use e.g. pygame to
> > get keystrokes. Or under linux, read (if you are root) the keyboard
> > input file - I've done that to support several keyboards attached to a
> > machine.
>
> > And the original question: no, python can't be used as kernel
> > programming language. Amongst other reasons, performance & the GIL
> > prevent that.
>
> > Diez
>
> sorry, my aim is not limited to one particular program. Yes, many
> library can
> permit you to respond to keyboard event, however, what I want is a
> universal
> function. as long as a key is pressed, no matter where, my program can
> repond.
>
> I am quite strange with this topic. But according to my understanding,
> any event, keyboard event
> for example, once triggered, will be dilivered by keyboard driver to X
> system, and then
> any running program can either choose to respond or ignore. So my
> question can be translated to:
> how to make my program respond ?

maybe I'd better elaborate on my question. Back to my original
question:
intercept keyboard event on a system level. If you are writing program
in
 emacs, of course, the keyboard inputs are meant for emacs only. What
I
want is no matter what program you're running, keyboard events can be
anyway caught by my program.

Am I clear with myself? :)
--
http://mail.python.org/mailman/listinfo/python-list


How to print a sorted list as a multi-column table

2008-05-23 Thread Sverker Nilsson
Hi all,

I would like to ask about opinions about the best way to format sorted
tables of items for interactive use. I have begun to add interactive
help to Guppy/Heapy (http://guppy-pe.sourceforge.net) because it lacks
the usual ways for introspection (see for example
http://www.pkgcore.org/trac/pkgcore/doc/dev-notes/heapy.rst) which is
due to Heapy's use of dynamic things like __getattr__ and to some
extent properties.

There seems to be no (good or otherwise) way to hook into the standard
help() (?) (At least not before 2.6 where I recall seeing a __dir__
magic method may be introduced, but I want it to be backwards
compatible to at least 2.4, preferably to 2.3.)

So I am about to roll my own help system. It will be based on having
the API objects supplying a standardized '.help' attribute which can
be used interactively, and will limit the output it prints to say 15
or 20 rows at a time.

That's for a background. Now what I was stumbling on which pumped up
enough adrenalin to make me begin to write this ---

Why are tables formatted like the following, when sorted? (Both in
linux eg ls, ftp help, and in Python help() when listing (eg)
modules))

(1)

a  g  m  s
b  h  n  t
c  i  o  u
d  j  p  v
e  k  q
f  l  r

Wouldn't it be more natural to just sort them like this:

(2)

a  b  c  d
e  f  g  h
i  j  k  l
m  n  o  p
q  r  s  t
u  v

What's the rationale for the choice of (1)?

In a pager, if you want to limit the number of lines output at a time,
then yo'd see with (1) (if artifically limiting output to 2 lines):

a  g  m  s
b  h  n  t

So to see the f item you would have to scroll down all the way.  The
number of times you would have to scroll down is in completely
unrelated to the item's position in sort order. That seems to defeat
the purpose of sorting in the first place. It feels strange, to me at
least. Anybody had the same feeling?

Well, what's the rationale (if any) for using the layout (1)?
Wouldn't layout (2) be better? And/or would it be confusing /
non-pythonic / non-unlixonic if a program used the (2) layout instead?

Have a (:nice:) weekend :-)

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


Re: Producing multiple items in a list comprehension

2008-05-23 Thread Paul Hankin
On May 22, 7:21 pm, "Joel Koltner" <[EMAIL PROTECTED]>
wrote:
> Is there an easy way to get a list comprehension to produce a flat list of,
> say, [x,2*x] for each input argument?
>
> E.g., I'd like to do something like:
>
> [ [x,2*x] for x in range(4) ]

[x * i for x in xrange(4) for i in xrange(1, 3)]

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


Re: Python is slow

2008-05-23 Thread Brian Blais

On May 23, 2008, at May 23:10:11 AM, Grant Edwards wrote:


On 2008-05-23, RPM1 <[EMAIL PROTECTED]> wrote:

Larry Bates wrote:

If your Python program is slow, you have almost assuredly
approached it with a wrong method or algorithm.


I agree for most applications.  There are however times where
Python just isn't fast enough, and that's usually when people
write extension modules.


Writing an extension modules is probably pretty far down the
list.  What usually happens is people


I think that really depends on what you are doing.  For me, it is  
exactly as Larry said.  I prototype in Python, then profile to figure  
out the slowest piece(s), and write an extension module.  Personally,  
I use Cython which makes the transition pretty trivial.  It is this  
solution (cython, that is) that convinced me to use Python over Ruby,  
or some other language, when I was moving code from Matlab.  I  
haven't regretted it since.



bb


--
Brian Blais
[EMAIL PROTECTED]
http://web.bryant.edu/~bblais



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

Another Question

2008-05-23 Thread Gandalf
How can i bind function that handle the mouse clicking  window X event
or clicking alt+F4


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


Re: Decorator metaclass

2008-05-23 Thread Thomas Karolski
Thanks for pointing out all those mistakes. I think I'm already starting 
to grasp all of the python magic going on in there.



Parenthetical: I don't normally recommend this style, since it
obscures the fact that you're using a custom metaclass to the user.
That is something the user probably would benefit from knowing, if for
no other reason than so they can make a mental note about where to
look first if something goes wrong.  I prefer to make the user use the
__metaclass__ attribute.


Really just personal preference I think. I'm not really a friend of 
declaring variables if there is a more "intuitive" way.



class HBar(Decorator):
def __init__(self, number):
Decorator.__init__(self)


Ok, at this point you have to ask yourself what you want to do,
because the solution you choose will involve trade-offs.


Yes, it was probably a bad example. I decided not to call the Decorator 
's __init__ method in my new version (which I have posted as a reply to 
the reply of Maric Michaud).



You will note that Decorator does not define __init__.  In fact,
object.__init__ will be called, which does nothing.  If you think that
all classes with DecoratorType as their metaclass will be a direct
subclass of Decorator, you can get away with not calling
Decorator.__init__ at all.


Now, inside my new version, I have a class which inherits from both 
Decorator and Window, out of which the __init__ for Decorator is not 
called. Does this prove to be a problem?



Probably the best piece of advice is "Don't try to use Decorator
pattern".  :)


Well, I decided on the decorator pattern, because I want to be able to 
change the behavior of classes during run-time. I did not really find 
any other pattern which would let me do that.


Regards,
Thomas K.

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


Re: Relationship between GUI and logic?

2008-05-23 Thread Bruno Desthuilliers

David C. Ullrich a écrit :

On Fri, 23 May 2008 09:13:50 -0400, "John Salerno"
<[EMAIL PROTECTED]> wrote:

"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in 
message news:[EMAIL PROTECTED]

Ever heard of the "Model/View/Controller" pattern ?
Yes, I have, but I probably don't understand it well enough yet. For 
example, I don't  really know what is meant by phrases like "build a model", 
"the view registers itself with the model", "interations are sent to the 
appropriate controller" -- I may understand them literally, but I get the 
feeling that the implementation of these ideas are beyond me. 


I doubt that.

I've done things like this. I ended up with just a Model and a View,
no Controller.


In the code snippet you gave, you do have the controller part - it's 
just merged with the view. Thruth is that the controller part does not 
map to a single, explicit, obvious *component*. It  in fact often 
happens that the controller bits are handled by various components of 
the system.


In the case of most modern GUI toolkits, the OS and GUI toolkit handles 
the first part of the controller stuff : mapping user actions to 
appropriate events, then mapping events to event handlers 
functions/methods - which, since views and controllers are usually 
tightky coupled, are most often than not methods of the view object 
itself - either because the GUI toolkit requires it or because the coder 
found it simpler and more obvious. Now even in the first case, you can 
still factor the controller part out of the view, and have the view's 
event handlers call on the controller. This may help unit-testing both 
the controller and the view and avoid having too much logic into the 
view itself.


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


Re: call f(a, *b) with f(*a, **b) ?

2008-05-23 Thread bukzor
On May 23, 3:29 am, "inhahe" <[EMAIL PROTECTED]> wrote:
> "inhahe" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > if we assume the constraints are that:
> > 1.he has list, l
> > 2.he has a dictionary, d
> > 3.he wants the function to print the values in the dictionary according to
> > a specific order of their keys as defined by the function, followed by the
> > values of the list
>
> It's also possible (even likely) that he knows outside of the function what
> order he wants the values in, and only used an (incidentally) unordered dict
> called kwargs because he thought that's the only way to pass to those
> parameters.  in which case the function could be left untouched and the he
> would call it like this:
>
> args = [1,2,3]
> f(*args)
> or
> f(*[1,2,3])

The actual application is an option-parser wrapper (it inherits from
optparse.OptionParser). I use the option setting to generate a dict of
the entry-point arguments versus the values specified by the
commandline. This works well. I can then do main(**options).

I was trying to add support for an entrypoint signature like
main(a,b,c,*argv) so that you can have a script with a variable number
of arguments. I can then make a script like: ./script.py a b c ...,
which requires quotes right now. (The actual application is a command
wrapper, where I would like to just add the script to the front of a
command without modification.)

It's easy to get the dictionary I had previously (of arguments versus
values) and a list of extraneous values to be passed to argv, but I
realized that main(*argv, **options) wasn't going to work.

I wish this worked:
>>> def main(a,b,*argv): pass
>>> options['argv'] = argv
>>> main(**options)
TypeError: main() got an unexpected keyword argument 'argv'


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


Re: Another Question

2008-05-23 Thread Mike Driscoll
On May 23, 10:45 am, Gandalf <[EMAIL PROTECTED]> wrote:
> How can i bind function that handle the mouse clicking  window X event
> or clicking alt+F4
>
> thanks

You really need to learn to ask good questions. Unless people dive
into your previous posts, they won't know what Python GUI toolkit you
are using, which version of said toolkit, which Python or which OS.

Here's a good place to read about events in general:

http://wiki.wxpython.org/EventPropagation

If you use Google, you can look for the close event, which gives you
this:

http://www.wxpython.org/docs/api/wx.CloseEvent-class.html

So you'll want to bind your frame to EVT_CLOSE. You can disable the
"X" in your frame's window by using non-standard style parameters.

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


  1   2   >