8
\$\begingroup\$

I suspect that this can be done in a much neater way using list comprehension in python:

poses = []
for x,y in get_points(spline):
    pose = Pose2D()
    pose.theta = 0
    pose.x=x
    pose.y=y
    poses.append(pose)
return poses

Is there a way to create a nice one liner for the above? (I do not have a constructor that takes the three arguments for Pose2D)

\$\endgroup\$
10
\$\begingroup\$
def make_pose(pt):
    pose = Pose2D()
    pose.theta = 0
    pose.x, pose.y = pt
    return pose

poses = [make_pose(pt) for pt in get_points(spline)]

Alternatively, you could subclass Pose2D to give it an appropriate constructor.

\$\endgroup\$
1
  • \$\begingroup\$ I'm wondering why this solution isn't accepted (yet) \$\endgroup\$ – Thomas Junk Jan 20 '14 at 20:35
2
\$\begingroup\$

for completeness sake there's also the map builtin in pythong 2.x. Using @hughbothwell's example:

poses = map (make_pose, points)

which is essentially the same as

poses = [makePose(pt) for pt in get_points(spline)]

Map is handy for shortening ths common pattern, but I think Guido has officially disowned it for the future

\$\endgroup\$
1
\$\begingroup\$

In case it's useful you could write a more general object maker function for classes that don't have constructors of the type you want.

def make_object(Class, **kwargs):
    """ Returns a new object from Class, with the attributes specified as keyword arguments """
    object = Class()
    for key, value in kwargs.items():
        setattr(object, key, value)
    return object

poses = [make_object(Pose2D, x=x, y=y, theta=0) for x, y in get_points(spline)]
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.