OMPC tricks

Python's power comes from the packages that come with it. You can use Python to interface external libraries but you can use it to inspect Python itself. Much of what you find on this page

The nargin, nargout emulation


The inspect module allows to look at the context in which a function is executed.



An example is implemented in 'test_nargin.py'.

Anonymous functions '@' and lambda


Python 'lambda' has a very similar functionality to MALTAB's '@' symbol. There are however subtle differences in treatment of local variables variables. Python uses references

Python and numpy (no OMPC)
MATLAB
>>> a = zeros([1,5]);
>>> b = lambda x: a+x;
>>> b(2)

array([[ 2.,  2.,  2.,  2.,  2.]])

>>> a[:] = ones([1,5]);
>>> a

array([[ 1.,  1.,  1.,  1.,  1.]])

>>> b(2)

array([[ 3.,  3.,  3.,  3.,  3.]])
>> a = zeros(1,5);
>> b = @(x) a+x;
>> b(2)
ans =
     2     2     2     2     2

>> a(:) = ones(1,5);
>> a
a =
     1     1     1     1     1

>> b(2)
ans =
     2     2     2     2     2



The possible solution is to implement 'anonymous' function that takes MATLAB's '@' and returns a regular python function with local variables that are copies of the parameter values.

Strings


All strings have to compiled using the raw operator

'\1' ---> r'\1'

espacially in the case above, common in regular expressions, Python interprets '\1' as '\x01'.


Comments