Re: How do I sort these?

2005-10-28 Thread Amaury
Sam Pointon a écrit :
>>unzip doesn't seem to work for me...
> 
> 
> It's not a part of the standard Python distribution, but this is a
> naive implementation (it doesn't react well to the list's contents
> having different lengths).
> 
> def unzip(seq):
> result = [[] for i in range(len(seq[0]))]
> for item in seq:
> for index in range(len(item)):
> result[index].append(item[index])
> return result
> 
> 
>>>>unzip(zip(range(5), 'abcde'))
> 
> [[0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e']]
> 

unzip() could be also be written like this:

def unzip(seq):
 return zip(*seq)

Faster and nicer, isn't it?

Except that it returns a list of tuples:
 >>>unzip(zip(range(5), 'abcde'))
[(0, 1, 2, 3, 4), ('a', 'b', 'c', 'd', 'e')]

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


Re: Is there a built-in method for transforming (1,None,"Hello!") to 1,None,"Hello!"?

2005-11-13 Thread Amaury
Hello,

Daniel Crespo wrote:
> Is there a built-in method for transforming (1,None,"Hello!") to
> 1,None,"Hello!"?

As others answered before, the two syntaxes build the same object, so 
there is no need to convert.

Except if you already have the tuple stored in a variable, and want to 
call a function with the tree arguments:
   args = (1,None,"Hello!")

   func(args)  # equivalent to   func((1,None,"Hello!"))
   func(*args) # equivalent to   func(1,None,"Hello!")

Note the '*' on the second call, it will flatten the args, and 3 
arguments are passed to the function.

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


Re: Overriding methods in classes you don't control

2005-03-29 Thread Amaury Forgeot d'Arc
Alex VanderWoude a écrit :
Here's the situation.  I'm using wxPython, and I want to make an enhancement
in the __init__ method of all the frame classes. The ideal place to do this
is in wxFrame.__init__, since any change there will automatically be
inherited by the other frame classes (for example, wxMDIParentFrame).
Obviously I can inherit from wxPython and make the changes in my subclass,
but then I would have to also subclass wxMDIParentFrame and duplicate my
enhancements there, and then use only my subclasses rather than the wx***
classes.
Basically I want to change wxFrame.__init__ so that it looks sort of like
this:
def __init__(self, *args, **kwargs):
# Some enhancements here.
# The original code of this method, including the call to its
ancestor.
# Some more enhancements here.
And then I can replace wxFrame's __init__ with my new version by assigning
it before any frames are instantiated.
Sorry, but this won't work with wxPython.
wxPython classes are just wrappers around C++ classes.
You may well replace wxFrame.__init__ with your own method, but it won't
be called by wxMDIParentFrame: wxMDIParentFrame.__init__ directly calls
the C++ constructor, completely ignoring wxFrame.__init__.
The call to the superclass' constructor is done in C++.
Since replacing C++ method is much more difficult (if possible at all),
I'm afraid you will have to do the replacement you plan for every
derived class.
Amaury.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods in classes you don't control

2005-03-29 Thread Amaury Forgeot d'Arc
Alex VanderWoude a écrit :
Here's the situation.  I'm using wxPython, and I want to make an enhancement
in the __init__ method of all the frame classes. The ideal place to do this
is in wxFrame.__init__, since any change there will automatically be
inherited by the other frame classes (for example, wxMDIParentFrame).
Obviously I can inherit from wxPython and make the changes in my subclass,
but then I would have to also subclass wxMDIParentFrame and duplicate my
enhancements there, and then use only my subclasses rather than the wx***
classes.
>
Basically I want to change wxFrame.__init__ so that it looks sort of like
this:
def __init__(self, *args, **kwargs):
# Some enhancements here.
# The original code of this method, including the call to its
ancestor.
# Some more enhancements here.
And then I can replace wxFrame's __init__ with my new version by assigning
it before any frames are instantiated.
Sorry, but this won't work with wxPython.
wxPython classes are just wrappers around C++ classes.
You may well replace wxFrame.__init__ with your own method, but it won't 
be called by wxMDIParentFrame: wxMDIParentFrame.__init__ directly calls 
the C++ constructor, completely ignoring wxFrame.__init__.
The call to the superclass' constructor is done in C++.

Since replacing C++ method is much more difficult (if possible at all),
I'm afraid you will have to do the replacement you plan for every 
derived class.

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


Re: Psyco performance

2006-06-20 Thread Amaury Forgeot d'Arc
Hello,

Gregory Piñero a écrit :
> What's the reasoning behind requiring everything to be in functions?
> Just curious.

You may want to read this:

http://psyco.sourceforge.net/introduction.html#differences-with-traditional-jit-compilers

Psyco has to run the code at least once to emit code specialized for the 
actual data. It works by replacing blocks of code by other blocks, 
optimized for the kind of data seen the previous times.

On the contrary, the code outside functions is run only once. You'll 
never get the chance to run the optimized version again...

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


Re: psyco+webpy

2006-06-26 Thread Amaury Forgeot d'Arc
a a écrit :
> hi i tried psyco+webpy
> 
> here is the error that i got
> please let me know if any of you has success run psyco+webpy
> thanks
> 
> import web, psyco
> urls = (
>   '/', 'view',
>   '/add','add'
> )
> psyco.full()
> psyco.log()
> psyco.profile()
> 
> Launching server: http://0.0.0.0:8080/
> Traceback (most recent call last):
>   File "C:\Python24\lib\site-packages\web.py", line 2054, in
> run_wsgi_app
> result = self.server.app(env, self.wsgi_start_response)
>   File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc
> result = func()
>   File "C:\Python24\lib\site-packages\web.py", line 1872, in 
> func = lambda: handle(getattr(mod, name), mod)
>   File "C:\Python24\lib\site-packages\web.py", line 1051, in handle
> return tocall(*([urllib.unquote(x) for x in args] + fna))
>   File "C:\mark\web1\codepsyco.py", line 27, in GET
> web.render('view.html')
>   File "C:\Python24\lib\site-packages\web.py", line 1707, in render
> terms.update(sys._getframe(1).f_locals)
>   File "C:\Python24\Lib\site-packages\psyco\support.py", line 129, in
> __getattr__

Functions optimized by Psyco have limitations concerning access of their 
local variables, as stated there: 
http://psyco.sourceforge.net/psycoguide/bugs.html
As a workaround, you should prevent psyco from optimizing the functions 
calling render().

psyco.cannotcompile(web.djangoerror)
psyco.cannotcompile(??.GET)

P.S. I just had a look at the web.py code and it seems that there are 
several uses of _getframe(x).f_locals. I find this trick not very 
pythonic (a function's docstring even says:"""Guido van Rossum doesn't 
want you to use this function.""") and anyway psyco will not appreciate it.

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


Re: psyco+webpy

2006-06-26 Thread Amaury Forgeot d'Arc
a a écrit :
>> psyco.cannotcompile(??.GET) this gives an error message
> invalid syntax

Oh, I assumed that you would replace the ?? by the correct expression.
You need to specify the GET function of the class you've written in the 
file "codepsyco.py" (I don't know the class name. It does not appear in 
the error traceback)
Depending on your architecture, this may be written this way:

import codepsyco
psyco.cannotcompile(codepsyco.YourClassHere.GET)



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


Re: py2exe and libxml

2006-09-04 Thread Amaury Forgeot d'Arc
Laszlo Nagy a écrit :
> 
> I wrote a little win32 console application that uses libxml2. It is 
> working fine. If I create an .exe version, I get this error when I try 
> to start the program:
> 
> Traceback (most recent call last):
>  File "MyProgram.py", line 3, in ?
>  File "mylib\item.pyc", line 5, in ?
> ImportError: dynamic module does not define init function (initlibxml2)
> 
> What is wrong here?
> Thanks
> 

A quick Google search reveals a thread in the py2exe-users list:

http://aspn.activestate.com/ASPN/Mail/Message/py2exe-users/3180430

It seems a regression since py2exe 0.6.5, already corrected in CVS trunk.
And according to another post, version 0.6.3 works fine:
http://permalink.gmane.org/gmane.comp.python.py2exe/1502

Hope this helps,

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


Re: wxPython: StaticText Event

2006-09-07 Thread Amaury Forgeot d'Arc
David a écrit :
> Plaese look at this simple class.
(...code...)
> Hovering mouse over the StaticText Control should generate an
> EVT_ENTER_WINDOW event like the TextCtrl Control, but it does not happen.
> 
> How can I make the StaticText event working?

I quick Google search found the following thread:

http://lists.wxwidgets.org/archive/wx-users/msg31855.html
or
http://lists.wxwidgets.org/archive/wx-users/msg31983.html

It suggest that you use another kind of control instead.
Is a disabled TextCtrl acceptable?

Hope this helps,

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


Re: for: else: - any practical uses for the else clause?

2006-09-26 Thread Amaury Forgeot d'Arc
[EMAIL PROTECTED] a écrit :
> A very old thread:
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/2c5022e2b7f05525/1542d2041257c47e?lnk=gst&q=for+else&rnum=9#1542d2041257c47e
> 
> discusses the optional "else:" clause of the for statement.
> 
> I'm wondering if anyone has ever found a practical use for the else
> branch?
> 

I use it regularly in contructs like:

 for value in someList:
 if someCondition(value):
 print "a matching item was found"
 break
 else:
 print "no matching item"
 return False

 # ... continue with value

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


Re: I'm having trouble understanding scope of a variable in a subclass

2006-12-28 Thread Amaury Forgeot d'Arc
Hello,

Pyenos a écrit :
> Thanks for clarifying the definitions of nested class and
> subclass. However, it did not solve my original problem, and I have
> redefined my question:
> 
> class Class1:
> class Class2:
> class Class3:
> def __init__(self):
> self.var="var"
> class Class4:
> print Class1.Class2.Class3.var
> 
> This code gives me the error:
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 2, in Class1
>   File "", line 3, in Class2
>   File "", line 6, in Class3
>   File "", line 7, in Class4
> NameError: name 'Class1' is not defined
> 
> I have tried:
> 
> class Class1:
> class Class2:
> def __init__(self):
> var="var"
> print Class1.Class2().var #this works
> 
> And, this worked. It is very strange that nested loop somehow fails to
> work when the innermost class has indentation level greater than two.

This has nothing to do with the indentation level.
But please try to copy exactly the code that you actually executed.

- Your first example fails, but with a different error message
(hint: the "print" statement is not inside a function, so it is executed 
as soon as the interpreter sees it - before it defines the classes.)
And it differs with your second example because the parentheses are 
missing after the name "Class3".

- Your second example does not work as you say. 'var' is a local 
variable and cannot be accessed from the outside. I suppose you actually 
entered something like:
   self.var="var"
which works indeed.

Again, it is difficult to guess what you are trying to do.

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


Re: Getting started with Crystal Reports...little help in the far court.

2007-01-08 Thread Amaury Forgeot d'Arc
Good evening,

Mudcat a écrit :
> I am not that familiar with Crystal Reports, but having read some other
> posts I know that the way to integrate the API with Python is through
> the COM interface provide by win32all.
> 
> However, I have been unable to find any other information on how to get
> started. I've used the COM interface before in integrating Excel and a
> couple of other things. So I am familiar with how that works. But there
> are at least 40 options dealing with Crystal and Business Objects. I
> have no idea which makepy file to create or which one provides the
> functionality I need.
> 
> I'm not looking to do much. All I'm really trying to do is provide one
> application where a list of crystal reports can be selected and ran in
> series. Right now we have a lot of reports that all have to be run
> manually (takes a while). So I think all I need api access to is server
> selection, parameter selection, and output formats.
> 
> Any pointers in the right direction would be helpful.


In my previous job we had to to almost the same thing.
If I remember correctly, for batch printing or file export it was enough 
to start with the "CrystalRuntime.Application" class.

It was something along these lines (sorry I don't have any way to test 
it now.):
 app = win32com.client.dynamic.Dispatch("CrystalRuntime.Application")
 report = app.OpenReport("c:/path/to/file.rpt")
 for table in report.Database.Tables:
 table.ConnectionInfo.Password = "passwd"
 ...
The rest is modeled after Visual Basic. There are tons of examples on 
the net.

If you want to show the report on the screen then it is another story.
I only remember the following:
- the application must be a mfc application
- I had to "makepy" a class. I think it was "CrystalReportsViewer".
- create a class derived from both pywin.mfc.activex.Control and 
CrViewer (look at the script generated by makepy).
- create a pywin.mfc.Frame, and put there an instance of the previous class.

Voilà, it's not much.
In the hope that you can do something with it.
But don't give up. At the end, it works...

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


Re: howto make Python list from numpy.array?

2007-05-06 Thread Amaury Forgeot d'Arc
Hello,

John Nagle a écrit :
> dmitrey wrote:
>> howto make Python list from numpy.array?
>> Thx, D.
>>
> 
> lst = map(None, arr)// for 1D arrays.

Which can be expressed more simply as:
   lst = list(arr)


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


Re: c macros in python.

2007-05-06 Thread Amaury Forgeot d'Arc
[EMAIL PROTECTED] a écrit :
> Hey,
> 
> I'm writing a script to generate code. I'm a bit tired of typing
> outfile.write(). Does python have a way to c-like macros? Every
> instance of o(...) in the code will be replaced by outfile.write(...)?

First: Python has no macro facility.

But in this particular case, it is very simple. Just add:
o = outfile.write
after the variable outfile is initialized.
It is not a macro (just another name for a function object)
but it looks the same...

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


Re: help building debug .pyd files

2007-04-11 Thread Amaury Forgeot d'Arc
[EMAIL PROTECTED] a écrit :
> The installation of Python 2.5 comes with a bunch of built-in
> extension modules (.pyd files) under the DLLs directory. I've
> downloaded the Python source code and am trying to build the debug
> versions of all of these files. However, some of the projects won't
> build because they are looking for header files that don't exist
> anywhere. Specifically, the non-building projects are:
> 
> _bsddb
> _sqlite3
> _ssl
> _tkinter
> bz2
> 
> Additionally, the project for the _hashlib module seems to be entirely
> missing from the Python source. Any idea where I can find it?
> 
> Is there a set of pre-built debug versions of all of these modules I
> can download somewhere? It would save me a lot of time trying to
> figure out where all these missing files are supposed to come from...

You should read the file PCBuild/readme.txt.
It explains how to build python from source, and has long explanations 
about the same list of modules you are asking for.

And it works: I regularly use the debug build of python for my own projects.

-- 
Amaury Forgeot d'Arc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx and SOAPpy interaction

2007-04-14 Thread Amaury Forgeot d'Arc
alf a écrit :
> Hi,
> 
> there is problem when I import (python 2.4) wx and SOAPpy at the same 
> time. I narrowed the problem to following (on Linux):
> 
>  >>import wx
>  >>import pyexpat
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> ImportError:
> /apps/public/python_2.4.4/lib/python2.4/lib-dynload/pyexpat.so:
> undefined symbol: XML_StopParser
> 
> 
> any insight?

It seems that the process is trying to load two versions of the "expat" 
XML library:

http://mail.python.org/pipermail/python-list/2006-April/377070.html

The problem is that wxWidgets embeds its own copy of expat. You may have 
to recompile either python or wxWidgets so that they use the same expat 
version.

-- 
Amaury Forgeot d'Arc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lost in __setstate__() in C++ and swig

2007-09-13 Thread Amaury Forgeot d'Arc
Hello,

Martin Drautzburg a écrit :
> I am trying to cPickle/unpickle a C++ extension class with some private
> data members. I wrote __getstate__() and __setstate__ in C++ (I have
> to, due to the private data). Pickling writes the following file:
> 
> ccopy_reg
> _reconstructor
> p1
> (cpyramid
> MidiBytes
> p2
> c__builtin__
> object
> p3
> NtRp4
> (S'some unknown MidiBytes'
> I1
> I2
> I3
> tb.
> 
> But when unpickling I get the following error
> 
> TypeError: in method 'MidiBytes___setstate__', argument 1 of type 
> 'pyramid::MidiBytes *'
> 
> I debugged the swig wrapper and indeed the wrapper is called with just
> one tuple argument. No object seems to be present at the time.
> 
> All the examples I've seen use python functions for __getstate__ and
> __setstate__ and it seems to me that the object itself is already there
> when __setstate__ is called. 

Unpickling an object does not use the normal path for creating the 
object. More precisely, the __init__ method is not called! See
http://docs.python.org/dev/library/pickle.html#pickling-and-unpickling-normal-class-instances

I suggest that you try to play with __getinitargs__ or __getnewargs__.
By calling __init__, it will give a chance to Swig to allocate the C++ 
object.

> 
> In a moment of dispair I declared __setstate__() static and have it
> create and return a MidiBytes object. 
> 
> MidiBytes *MidiBytes:: __setstate__ (PyObject * aTuple) {
> return new MidiBytes();
> }
> 
> Then unpickling no longer complains about "argument 1", but the
> unpickled object does not work
> 
> >>> nn = cPickle.load(FILE)
> >>> nn.len()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/src/sound.d/pyramid/pyramid.py", line 618, in len
> return _pyramid.MidiBytes_len(*args)
> TypeError: in method 'MidiBytes_len', argument 1 of
> type 'pyramid::MidiBytes *'

This message is typical of a swig object whose __init__ method has not 
been called. (No later than today, I forgot to call the base.__init__ in 
a derived class. Maybe we should ask Swig for a better message)
See above for a hint. Hope this helps...


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


Re: Is there a nicer way to do this?

2007-10-04 Thread Amaury Forgeot d'Arc
Hello,
Stefan Arentz a écrit :
> Is there a better way to do the following?
> 
> attributes = ['foo', 'bar']
> 
> attributeNames = {}
> n = 1
> for attribute in attributes:
>attributeNames["AttributeName.%d" % n] = attribute
>n = n + 1
> 
> It works, but I am wondering if there is a more pythonic way to
> do this.
> 
>  S.

You could use enumerate() to number the items (careful it starts with 0):

   attributes = ['foo', 'bar']
   attributeNames = {}
   for n, attribute in enumerate(attributes):
   attributeNames["AttributeName.%d" % (n+1)] = attribute


Then use a generator expression to feed the dict:

   attributes = ['foo', 'bar']
   attributeNames = dict(("AttributeName.%d" % (n+1), attribute)
 for n, attribute in enumerate(attributes))

Hope this helps,

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