2

How would I format:

self.bot = servo.Robot({
        'waist': servo.Servo(3, 90, .02, 0),
        'shoulder': servo.Servo(4, 130, .03, 15),
        'elbow': servo.Servo(5, 110, .02, 19),
        'wrist': servo.Servo(6, 20, .01, 9),
        'claw': servo.Servo(7, 40, .01, 0)
    }, [5, 15, 25])

In case that was too much of a mouthful, create a variable called self.bot, make it equal to the return value of self.Robot(servo_dict, num_list), which takes a dict and a list as parameters.

I have already looked in PEP8 and this other Stack Overflow question. I would encourage answers to link to style guides...

Community
  • 1
  • 1
charmoniumQ
  • 5,214
  • 5
  • 33
  • 51

1 Answers1

1

Using the dict constructor, you can at least eliminate typing a bunch of quotes:

self.bot = servo.Robot(dict(
        waist = servo.Servo(3, 90, .02, 0),
        shoulder = servo.Servo(4, 130, .03, 15),
        elbow = servo.Servo(5, 110, .02, 19),
        wrist = servo.Servo(6, 20, .01, 9),
        claw = servo.Servo(7, 40, .01, 0)
    ), [5, 15, 25])

Of course, you can also write a helper function like this:

def servos(**kwargs):
    for k, v in kwargs.iteritems():
        kwargs[k] = servo.Servo(*v)
    return kwargs

And then:

self.bot = servo.Robot(servos(
        waist = (3, 90, .02, 0),
        shoulder = (4, 130, .03, 15),
        elbow = (5, 110, .02, 19),
        wrist = (6, 20, .01, 9),
        claw = (7, 40, .01, 0)
    ), [5, 15, 25])

If you will be doing a lot of dicts-of-instances with different types of instances, you can make the helper generic:

def instance_dict(typ, **kwargs):
    for k, v in kwargs.iteritems():
        kwargs[k] = typ(*v)
    return kwargs

# later...
self.bot = servo.Robot(
               instance_dict(servo.Servo,
                   waist = (3, 90, .02, 0),
                   shoulder = (4, 130, .03, 15),
                   elbow = (5, 110, .02, 19),
                   wrist = (6, 20, .01, 9),
                   claw = (7, 40, .01, 0) ),
               [5, 15, 25])
kindall
  • 178,883
  • 35
  • 278
  • 309