[Chicago] FW: Playing with generics
RCRamsdell@gldd.com
RCRamsdell at gldd.com
Wed Nov 16 18:41:05 CET 2005
I have a function that works on a pair of x, y coordinates. I wanted to
be able to pass either a 2-tuple, or x and y. Remembering Ian's
presentation, this sounded like a great case for generics!
So I produced listing 1. Wow, lots of lines there, and some
duplication. Plus I have to add a dependency (to the dispatch module).
I had a similar case in another module from the same project, so I tried
it in-line (Listing 2). Much shorter, particularly when you consider
that I am checking for an additional case, that of no argument passed
in.
Is this just a case where the requirement is too simple to warrant the
overhead? Yes, but: if I later wanted to add support for (x,y,z)
coords, where betaad might have a quite different calculation, then the
dispatch would probably pay off.
# Listing 1:
@dispatch.generic()
def canvasCoords(self, *args):
"""Stub function for canvasCoords"""
@canvasCoords.when("len(args)==2")
def canvasCoords(self, x, y):
"""
Calculate the coordinates on the canvas of the given dredge
coordinates
x, y are coordinates in the dredging scheme, center of rotation
is (0,0)
"""
return x/self.scalefactor+self.xoffset,
y/self.scalefactor+self.yoffset
@canvasCoords.when("len(args)==1")
def canvasCoords(self, xy):
"""
Calculate the coordinates on the canvas of the given dredge
coordinates
(x, y) are coordinates in the dredging scheme, center of
rotation is (0,0)
"""
return xy[0]/self.scalefactor+self.xoffset,
xy[1]/self.scalefactor+self.yoffset
# Listing 2:
def betaad(self, *args):
"""betaa - The angle of the line through the anchor in degrees
the args are either a 2-tuple with the anchor coords, or
anchor
x and y
"""
if len(args)==0:
xa, ya = self.Xa, self.Ya
elif len(args) == 1 and len(args[0])==2:
xa, ya = args[0]
elif len(args) == 2:
xa, ya = args
else:
raise TypeError, "HyAnchor.betaad - Wrong number of
arguments, expects a pair or 2-tuple"
betaa = atan(xa/ya)
return betaa*180/pi
Robert C. Ramsdell III
Production Engineering Manager
Great Lakes Dredge & Dock Company
2122 York Road
Oakbrook, IL 60523
rcramsdell at gldd.com
Phone: (630) 574-3463
Mobile: (630) 805-1776
Fax: (630) 574-2909
More information about the Chicago
mailing list