Python: Dynamically calling Method in separate script
Question: I'm currently working on a project to control a 6 legged robot. I've got my
scripts set up for the individual joint control and it's working fine. I have
individual scripts for the joint controllers for each leg,
leg_1_joint_control, leg_2_joint_control etc ..., all of these scripts have 3
PID controllers for the motors on each leg called PID1, PID2 & PID3. What I
want to do is dynamically call my PID1,2&3 methods in my
leg_'leg_no'_joint_control.py script (where 'leg_no' is the leg number [1 -
6]) without having to write a separate case for each leg.

Here's an ideal snippet of my leg control code to try and explain:

    
    
    import leg_1_joint_control
    import leg_2_joint_control
    import leg_3_joint_control
    ...
    
    def leg(args, leg_no):
        ...
        e1[t] = leg_'leg_no'_joint_control.PID1(args)
        ...
    

and my leg_'leg_no'_joint_control script

    
    
    ...
    def PID1(args):
        ...
        return ek
    

So what I want to do is when I change the leg_no variable, I want to call PID1
in the scripts for the relevant leg. is this possible? I've tried methods such
as getattr() but have had no success.


Answer: Do not try to use dynamic names for variables it will cause headaches to
develop and nightmares to maintain. Just use an array :

    
    
    import leg_1_joint_control
    import leg_2_joint_control
    import leg_3_joint_control
    ...
    
    legs_joint_control = [ leg_1_joint_control, leg_2_joint_control, ... ]
    
    def leg(args, leg_no):
        ...
        e1[t] = legs_joint_control[leg_no].PID1(args)
        ...
    

