?
=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=
Jacek Generowicz said:==== Example 1: a debugging aid ================================
=== Example 2: Alexander Schmolck's updating classes ===============
Here's another example of a real life situation
where I thought it'd be good to have macros in Python.
I was writing a GUI system and I had to define lots of
code twice, both for the x-axis and y-axis. Such
as
if y > self.y - bs and y < self.y + bs + self.height:
return (abs(x - self.x) < bs,
abs(x - (self.x + self.width)) < bs)
else:
return False, False
and then
if x > self.x - bs and x < self.x + bs + self.width:
return (abs(y - self.y) < bs,
abs(y - (self.y + self.height)) < bs)
else:
return False, False
Obviously this was quite unsatisfactory. I ended up
putting the axis code in a separate class so I could
use them interchangeably. I.e. If I passed
func(self.y, self.x)
and then
func(self.x, self.y)
I would get the same effect on both axises. But this
would've been an excellent place for macros IMO (unless
there's a more clever solution as a whole). Using macros
that combine both function call and "code block" syntax,
I could've written a simple function like this:
defBoth getSize(self):
return self.size
And it would've been expanded to
def getWidth(self):
return self.width
def getHeight(self):
return self.height
The macro would've had to change all "size" to either
"width" or "height", and also change "pos" to either "x"
or "y" and so on.
This way, I could've got no duplicated code but
also a more intuitive interface than I currently have
(to get width, one needs to type obj.x.getSize() instead
of obj.getWidth()). And it's obvious this kind of "defBoth"
wouldn't be added as a language level construct -- Thus
macros are the only good solution.