unittest.assertRaise and keyword arguments?

2005-12-02 Thread Bo Peng
Dear list, The syntax for using assertRaise is assertRaise(exception, function, para1, para2,...) However, I have a long list of arguments (>20) so I would like to test some of them using keyword arguments (use default for others). Is there a way to do this except for manually try...except?

Re: unittest.assertRaise and keyword arguments?

2005-12-02 Thread Bo Peng
Giovanni Bajo wrote: > You can pass keyword arguments to assertRaises without problems: > > self.assertRaises(ValueError, myfunc, arg1,arg2, arg3, arg4, abc=0, foo=1, > bar="hello") Well, I though abc=0 would be keyword arguments for assertRaisers and never tried it! > > Or you can always do s

exposing C array to python namespace: NumPy and array module.

2004-12-31 Thread Bo Peng
Dear list, I am writing a Python extension module that needs a way to expose pieces of a big C array to python. Currently, I am using NumPy like the following: PyObject* res = PyArray_FromDimsAndData(1, int*dim, PyArray_DOUBLE, char*buf); Users will get a Numeric Array object and can change it

Re: exposing C array to python namespace: NumPy and array module.

2005-01-01 Thread Bo Peng
Craig Ringer wrote: On Sat, 2005-01-01 at 08:18, Bo Peng wrote: Python's array module is built-in, easy to use, but *without* a FromLenAndData function! Even the buffer interface provides only 'get buffer' but no 'set buffer' functions. Could anyone tell me how I ca

Re: exposing C array to python namespace: NumPy and array module.

2005-01-01 Thread Bo Peng
Scott David Daniels wrote: Python's array module is not built to do this well. It can re-size the array, delete elements inside the array, and other things that don't work very well with C-managed data. I wrote "blocks and views" to overcome this problem. As always the case, this problem have b

compiler version mismatch when building ext_modules with MSVC

2005-01-09 Thread Bo Peng
Dear list, I was using autoconf/automake etc to build my python extension. Since distutil seems to be easier, I have switched to this method. However, when I build the module under windows, I am told that compiler version mismatch... I am using msvc 7 and python was build by msvc 6.0. I am not

mixing SWIG generated and Python-level usertype?

2005-02-01 Thread Bo Peng
Dear list, My SWIG generated module (myModule) needs an array-like object (carray) to work. Carray objects are created both internally (in C++ level) and through Python so I have to load it when myModule initializes. carray is modified from arraymodule.c and is quite simple: static PyMethodDef a

changing local namespace of a function

2005-02-04 Thread Bo Peng
Dear list, I have many dictionaries with the same set of keys and I would like to write a function to calculate something based on these values. For example, I have a = {'x':1, 'y':2} b = {'x':3, 'y':3} def fun(dict): dict['z'] = dict['x'] + dict['y'] fun(a) and fun(b) will set z in each dicti

Re: changing local namespace of a function

2005-02-04 Thread Bo Peng
M.E.Farmer wrote: def fun(d): ... __dict__ = d ... return __dict__ hth, Does not work? >>> a = { 'x':1, 'y':2} >>> b = { 'x':2, 'y':9} >>> def fun(d): ... __dict__ = d ... print locals() ... z = x + y >>> fun(a) {'__dict__': {'y': 2, 'x': 1}, 'd': {'y': 2, 'x': 1}} Traceback (most re

Re: changing local namespace of a function

2005-02-04 Thread Bo Peng
Michael Spencer wrote: As you no doubt have discovered from the docs and this group, that isn't doable with CPython. Too bad to know this. >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} ... >>> def funa(x,y, **kw): ... del kw #Careful of unwanted names in locals with this approach ...

Re: changing local namespace of a function

2005-02-04 Thread Bo Peng
Jeff Shannon wrote: This sounds to me like you're trying to re-implement object orientation. I have no control over the big dictionaries. All I need to do is processing them in situ --- that is to say, go into each map and manipulate numbers. Parameter passing should be avoid whenever possible s

Re: changing local namespace of a function

2005-02-04 Thread Bo Peng
Thank all for your suggestions. I have tried all methods and compared their performance. >>> import profile >>> a = {'x':1, 'y':2} >>> N = 10 >>> # solution one: use dictionary directly ... def fun1(d): ... for i in xrange(0,N): ... d['z'] = d['x'] + d['y'] ... >>> # solution two: use e

Re: changing local namespace of a function

2005-02-04 Thread Bo Peng
M.E.Farmer wrote: I really don't see your need. Maybe it is just my laziness. It is almost intolerable for me to write lines and lines of code like d['z'] = func(d['x']+d['y']+d['whatever']['as']+d[a][0] ) It is ugly, unreadable and error prone. If I have to use this code, I would write _z

Re: changing local namespace of a function

2005-02-04 Thread Bo Peng
Maybe it is just my laziness. It is almost intolerable for me to write lines and lines of code like d['z'] = func(d['x']+d['y']+d['whatever']['as']+d[a][0] ) By the way, will 'with statement', like the one in pascal and many other languages, be a good addition to python? For example, with d d

Re: changing local namespace of a function

2005-02-05 Thread Bo Peng
Nick Coghlan wrote: If you want to add more calculated properties to the data manipulator, simply define additional calculator methods, and define the attribute with make_prop. This has became really appealing You know, I have a deep root in C/C++ so performance is the king and hacking is pa

Re: changing local namespace of a function

2005-02-05 Thread Bo Peng
Kent Johnson wrote: You can part way there using keyword arguments. You just have to use dictionary syntax for changing values in the dictionary: >>> def f(d, x=None, y=None): ... d['z'] = x + y ... >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} >>> >>> f(a, **a) >>> a {'y': 2, 'x': 1, '

Re: changing local namespace of a function

2005-02-05 Thread Bo Peng
Exec is slow since compiling the string and calls to globals() use a lot of time. The last one is most elegant but __getattr__ and __setattr__ are costly. The 'evil hack' solution is good since accessing x and y takes no additional time. Previous comparison was not completely fair since I could

Re: changing local namespace of a function

2005-02-05 Thread Bo Peng
Kent Johnson wrote: Bo Peng wrote: Exec is slow since compiling the string and calls to globals() use a lot of time. The last one is most elegant but __getattr__ and __setattr__ are costly. The 'evil hack' solution is good since accessing x and y takes no additional time. Previous

Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Bo Peng
Hi, I need to pass a bunch of parameters conditionally. In C/C++, I can do func(cond1?a:b,cond2?c:d,.) In Python, I am using temporary variables like if cond1: para1 = a else: para1 = b # # a bunch of such if/else func(para1, para2,...) Is there an easier way to do this in Pyt

Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Bo Peng
>>In Python, I am using temporary variables like >> >>if cond1: >> para1 = a >>else: >> para1 = b >> >># >># a bunch of such if/else >> >>func(para1, para2,...) > > > Yeah, that's how I would do it. How many of these things do you have? I have around 10 of them. Using these if/else, it

Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-19 Thread Bo Peng
Roy Smith wrote: > Can you give us some idea of what it is that you're trying to do? It pretty > unusual to see > a requirement like that. def func(type_of_obj1, type_of_obj2, .): callfunc( [ type_of_obj1 and obj1a() or obj1b(), type_of_obj2 and obj2a() or obj2b(),

How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
Dear list, I have a long list of commands in the form of a script and would like to obtain a log file as if I enter the commands one by one. (The output will be used in a tutorial.) What would be the best way to do it? Copy and paste is not acceptable since I make frequent changes tot he scri

Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
Thank you for the suggestions and code! > import code > > SCRIPT = [line.rstrip() for line in open("myscript.py")] > > script = "" > prompt = ">>>" > > for line in SCRIPT: > print prompt, line > script = script + line + "\n" > co = code.compile_command(script, "", "exec") > if

Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
[EMAIL PROTECTED] wrote: > The 'code' module contains 'Utilities needed to emulate Python's interactive > interpreter.'. By subclassing code.InteractiveConsole and replacing the > raw_input method with one which reads from a file, I think you can get what > you > want. This method works fine wit

Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
Fredrik Lundh wrote: > replacing sys.stdin with something that isn't a TTY will fix this. This works like magic! Thank you! Bo -- http://mail.python.org/mailman/listinfo/python-list

Big latex subscript using python.sty and manual.cls

2005-02-15 Thread Bo Peng
Dear list, I am writing a manual for my python extension using Python (2.4) latex classes. Everything seems to be fine except that the subscripts are as big as normal text ( see page 55 of http://bp6.stat.rice.edu:8080/simuPOP_doc/userGuide.pdf ). I doubt that the following piece of code in pyt

default value for list access?

2005-02-27 Thread Bo Peng
Dear list, My program needs to do calculation based on a giving data structure (like a sparse matrix) with lots of missing values (invalid indices/keys of lists/dictionaries). The programing is difficult in that I have to use a try...except block for every item access. I have written a functio

Re: default value for list access?

2005-02-27 Thread Bo Peng
To clearify the problem: The data is the count of something, for example a[90]=10. a may be a dictionary if the range is huge and a list when the range is reasonably small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 does not exist. In the list case, I have to check the lengt

Re: default value for list access?

2005-02-27 Thread Bo Peng
Sounds to me like the best solution is to simplify the implementation and dispense with the list alternative. Why use a list if a dictionary is suitable? Don't say performance: that's premature optimization. Dictionaries already have what you need, apparently, with setdefault(), so just use them

parameter name conflict. How to solve?

2005-03-07 Thread Bo Peng
Dear list, If you ask: why do you choose these names? The answer is: they need to be conformable with other functions, parameter names. I have a function that pretty much like: def output(output=''): print output and now in another function, I need to call output function, with again keyword p

Re: parameter name conflict. How to solve?

2005-03-08 Thread Bo Peng
Delaney, Timothy C (Timothy) wrote: Is this a style guide thing? Why not just: def func(output_param=''): output(output=output_param) This is exactly the problem. There are a bunch of other functions that use output='' parameter. Changing parameter name for this single function may cause conf

Re: parameter name conflict. How to solve?

2005-03-08 Thread Bo Peng
Kent Johnson wrote: Bo Peng wrote: def func(output=''): output(output=output) Naturally, I get 'str' object is not callable. Is there a way to tell func that the first output is actually a function? (like in C++, ::output(output) ) You could use a default argum

How to pass parameter when importing a module?

2005-03-20 Thread Bo Peng
Dear list, What I would like to do is something like: In myModule.py ( a wrapper module for different versions of the module), if lib == 'standard': from myModule_std import * elsif lib == 'optimized' from myModule_op import * but I do not know how to pass variable lib to myModule.py to

Re: How to pass parameter when importing a module?

2005-03-20 Thread Bo Peng
Take a look at wxPython versioning: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls The most simple usage looks like import wxversion wxversion.select("2.4") import wx Serge. This is essentially my second method: using another module to set parameter for myModule. Si

Testing the availability of a module

2005-12-19 Thread Bo Peng
Dear list, Is there a better way than doing try: import aModule except: has_aModule = False else: has_aModule = True The main concern here is that loading aModule is unnecessary (and may take time). Many thanks in advance. Bo -- http://mail.python.org/mailman/listinfo/python-list

Re: Testing the availability of a module

2005-12-19 Thread Bo Peng
Peter Hansen wrote: > Bo Peng wrote: > >> Is there a better way than doing >> >> try: >>import aModule >> except: >>has_aModule = False >> else: >>has_aModule = True >> >> The main concern here is that loading aModule i

Re: Testing the availability of a module

2005-12-19 Thread Bo Peng
> if the user happens to prefer the command line interface, why bother looking > for a GUI ? sounds like you haven't really thought this through... > > here's an outline that matches your use case: > > if user wants command line: > command line only > else: > if wxPython

Weird memory consumption problem.

2005-12-19 Thread Bo Peng
Dear list, I spent the last 12 hours in catching this bug (?) and what I found out is very difficult to explain: Basically, I need to call a user-provided function many times, with a tuple as parameter. C/C++ side: (class A, constructed using a python function m_func) // create in the con

Re: Weird memory consumption problem.

2005-12-20 Thread Bo Peng
Steven D'Aprano wrote: > Sorry, are you saying that the code you posted does NOT have a memory > leak, but you want us to find the memory leak in your real code sight > unseen? valgrind does not detect anything so it does not look like memory leak. I just can not figure out why val[0], readonl

Re: Weird memory consumption problem.

2005-12-20 Thread Bo Peng
Bo Peng wrote: >> Sorry, are you saying that the code you posted does NOT have a memory >> leak, but you want us to find the memory leak in your real code sight >> unseen? Problem found. It is hidden in a utility function that converts the return value to a double. The re

Why does Rpy/R-plot work under PythonWin, but not under commandline/IDLE?

2006-01-08 Thread Bo Peng
Dear list, I am using rpy, a python module to control statistical package R from python. Running the following commands >>> from rpy import * >>> r.plot(0) will pass command 'plot' to R and run it. I notice that the R-plot will not refresh (a window is created but the figure is not drawn) un

Re: Why does Rpy/R-plot work under PythonWin, but not under commandline/IDLE?

2006-01-08 Thread Bo Peng
Bo Peng wrote: > Does anyone know why commandline/IDLE cause this > problem, while PythonWin does not? I am interested to know what I can do > in commandline (or in rpy) to fix this problem. Just note that R/plot works fine both from command window and a R-GUI. Bo -- http://mail.p

How to distribute an additional DLL to site-packages?

2006-12-21 Thread Bo Peng
Dear Python experts, I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory along with my extension modules? It seems that data_files parameter can do this, but I do not know how to get the absolute destination d

Building python C++ extension modules using MS VC++ 2005?

2006-12-21 Thread Bo Peng
Dear list, I have been using mingw to build a python extension module. I had to jump through a number of hooks like the _ctype problem caused by the use of msvcr71.dll, but the module was mostly usable. Things become complicated when I use more and more boost libraries and mingw can not work w

Re: Building python C++ extension modules using MS VC++ 2005?

2006-12-22 Thread Bo Peng
Sandra-24 wrote: > You can use 2005 to build extensions for Python 2.5. I've done this > with several extensions, both my own and others. I do not know if you > can use it for Python 2.4, so I won't advise you on that. I thought > Microsoft made its C/C++ compiler, version 7.1 (2003) freely availab

Re: How to distribute an additional DLL to site-packages?

2006-12-22 Thread Bo Peng
> I am writing a python extension module that needs to link with a > third-party DLL. How can I copy this DLL to the site-packages directory > along with my extension modules? It seems that data_files parameter can > do this, but I do not know how to get the absolute destination > directory. Af

Re: How to distribute an additional DLL to site-packages?

2006-12-22 Thread Bo Peng
> Use the package_data option. setup(..., packages=['yyy'], > package_data={'yyy':['xxx.dll']}, ...) > (Distutils documentation may be arcane sometimes, but this is easily > found at http://docs.python.org/dist/node12.html) > Absolute dirs are almost never necesary, usually all distutils commands >

Is there a way to profile underlying C++ code?

2006-01-24 Thread Bo Peng
Dear list, I have a C++-SWIG-wrapped python module. The running time for one of the functions is pretty unpredictable so I would like to profile it. However, the python profiler does not seem to enter the compiled module (.so file). Is there a way to profile the C++ functions? Many thanks in a

Re: Is there a way to profile underlying C++ code?

2006-01-25 Thread Bo Peng
Travis E. Oliphant wrote: > On Linux you can use oprofile (which is pretty nice and easy to use --- > no recompiling. Just start the profiler, run your code, and stop the > profiler). Thank you very much for the tip. This is a great tool. The source of the problem has been found: cache misses

Re: Start a python interactive shell from python.

2006-01-26 Thread Bo Peng
I think I find what I need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355319 Bo -- http://mail.python.org/mailman/listinfo/python-list

Start a python interactive shell from python.

2006-01-26 Thread Bo Peng
Dear list, This may sound strange but I need to start a python shell from python. The motivation is that I have a bunch of (numeric) python functions to provide to a user. The best way I can think of is packing my python module using py2exe, and because it is easiest to let him run the functio

Module written in C does not repond to Ctrl-C interruption.

2006-02-24 Thread Bo Peng
Dear list, I have not done a thorough test, but it occurs to me that 1. python code can be interrupted by Ctrl-C. 2. A C module, if I add a main() function and run independently, can be interrupted by Ctrl-C. 3. If I load the C module in python and run, the program will not respond to Ctrl-C in

Re: Module written in C does not repond to Ctrl-C interruption.

2006-02-24 Thread Bo Peng
Daniel Dittmar wrote: > > You could set up your own signal handler when entering the C extension. > This should abort the extension (tricky) and call the Python signal > handler. This can be done under linux using things in signal.h but I am not sure whether or not there is a portable way to do

Re: Suggestions for documentation generation?

2006-03-04 Thread Bo Peng
kpd wrote: > Hello, > > I have written a C++ library that I've then wrapped with Pyrex. > Any suggestions to the best-in-class tool to create documentation for > the libraries? > > I would love to document things in one spot (could be the code) and > generate html and PDF from there. > > Doxygen

control precision for str(obj) output?

2005-05-03 Thread Bo Peng
Dear list, I have enjoyed the convenience to output any object with str(obj) for a while. However, I get long output for things like str([0.0002]) in my output (which bothers my users more than me though). I also do not understand why the following is happening: >>> str([0.0002]) '[0.0002

Re: control precision for str(obj) output?

2005-05-03 Thread Bo Peng
> The unfortunate side effect of this is to make str(list of floats) > ugly, but... Yeah, Nothing is perfect. I can control the damage as long as I know what is going on. I guess this would fit in a faq list quite well. I would have to thank Mike and Dan for your quick and detailed reply. As a

Re: control precision for str(obj) output?

2005-05-04 Thread Bo Peng
Dan Bishop wrote: > Andrew Dalke wrote: > >>Mike Meyer wrote: >> >>>Someone want to tell me the procedure for submitting FAQ entries, > > so I > >>>can do that for this? >> >>You mean more than what already exists at >> > > http://www.python.org/doc/faq/general.html#why-are-floating-point-calcu

Python distutil: build libraries before modules

2006-05-01 Thread Bo Peng
Dear list, My python modules depend on a few boost libraries. For convenience, I include the source code of these libraries with my distribution and treat them as standard source files. This results in huge cc.exe command lines and I get an error saying error: command 'cc' failed: Invalid ar

Re: Python distutil: build libraries before modules

2006-05-01 Thread Bo Peng
Bo Peng wrote: > How can I let setup.py build these boost libraries separately so that I > can link them to my modules? This will also save some link time because > all my python modules link to the same boost libraries. Although this is nowhere documented, I find that I can