Any way to program custom syntax to python prompt? >> I want to edit matrices.

Stargaming stargaming at gmail.com
Mon Dec 10 23:14:09 EST 2007


On Mon, 10 Dec 2007 16:54:08 -0800, mosi wrote:

> Python matrices are usually defined with numpy scipy array or similar.
> e.g.
>>>> matrix1 = [[1, 2], [3, 4], [5, 6]]
> I would like to have easier way of defining matrices, for example:
>>>> matrix = [1, 2; 3, 4; 5, 6]
> 
>>>> matrix =
> [ 1, 2;
>   3, 4;
>   5, 6;]
> 
> Any ideas how could this be done? The ";" sign is reserved, the "[ ]" is
> used for lists.

You could have some class `Matrix` with a constructor taking a string, as 
in ``Matrix("[1, 2; 3, 4; 5, 6]")``. A very naive parser could just strip 
trailing/leading brackets and all spaces, split on ';', split again on 
',', done.

> Also, how to program custom operations for this new "class?" matrix ???
> 
> For example:
>>>> matrix + 2
> [ 3, 4;
>   5, 6;
>   7, 8;]
> 
> Possibly with operator overloading?

Yes, by simply overloading __add__ et al. See http://docs.python.org/ref/
specialnames.html for details (certainly, "Emulating numeric types" 
should be interesting to you).

> I appreciate all your comments, directions, pointers. mosi

Cheers,



More information about the Python-list mailing list