Macro like functionality for shorthand variable names

Larry Bates larry.bates at`
Sat Jun 7 21:44:33 CEST 2008

Tilman Kispersky 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.

Names in Python point to objects so you can bind several names to the same location.

 >>>>  self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1])

The following will work.

a = self.a
b = self.b
u = self.y[0]
V = self.y[1]

self.dytd[1] = a * (b * V - u)

In addition to making the lines shorter, I'm pretty sure they will be slightly 
faster because lookups on the local variables is slightly faster than on the 
instance variables (self.?).

Note: I think your parenthesis are incorrect in the equation above.  If they 
aren't then no parenthesis are necessary since multiplication takes precedence 
over subtraction.

Hope this helps.


More information about the Python-list mailing list