Macro like functionality for shorthand variable names

Kay Schluehr kay.schluehr at gmx.net
Sat Jun 7 01:37:03 EDT 2008


On 6 Jun., 23:13, Tilman  Kispersky <tilman... at gmail.com> wrote:
> I have python code in a class method translated from C++ that looks
> sort of like this:
>
> >>>  self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1])
>
> To make this more readable in C++ I had made macros to achieve this:
> #define du (dydt[1])
> #define u (y[1])
> #define V (y[0])
>
> du = a * (b * V - u);
>
> I realize the value of not having macros in Python.  They've tripped
> me up more than once in C++.  My question is:
> Is there any way to write a shorterhand more readable version of the
> python code above?  I'm doing several calculations one after the other
> and some of the lines are quite long.

There is no entirely generic way but you can define a function that
produces a string from an object that contains assignments and then
use exec:

def tovars(obj):
    return ";".join("%s=%s"%(n,v) for (n,v) in obj.__dict__.items())

# example

class A:pass

>>> a = A()
>>> a.x = 0
>>> a.y = 1
>>> exec tovars(a)
>>> y
1
>>> x
0

In your own case the tovars) function might be defined as:

def tovars(obj):
    assign = []
    assign.append("du = %s"%obj.dydt[1])
    assign.append("u = %s"%obj.y[1])
    assign.append("V = %s"%obj.y[0])
    return ";".assign






More information about the Python-list mailing list