1

I know eval is bad, I'm pretty new to coding.

I'm using config parser to define motors that open output gates to divert parts

from my config file:

 [Motor]out1=["Screw", "board0.motor1"]

Code

    out1=json.loads(config['Motor']['out1'])
    board0 = MotorKit(address= int(config['Motor']['board0'], 16))
    def openMotor(m):
        eval(m).throttle = 1
        time.sleep(0.1)
        eval(m).throttle = 0.2
    
    def open_gate(part):
        if part == out1[0]:
            openMotor(out1[1])
    open_gate("screw")

How do I not use eval? but be able to set the attritbute board0.motor1.throttle in the openMotor function?

furas
  • 134,197
  • 12
  • 106
  • 148
Nick S
  • 25
  • 2
  • 2
    Honestly, this is why lists of things should be stored in lists, instead of variables called thing0, thing1, thing2, etc. If they were lists, it would just be `board[i][j].throttle = 0.2`. How much control do you have over that? – Tim Roberts May 10 '21 at 03:47
  • What is the value of out1[1]? – ankurbohra04 May 10 '21 at 03:47
  • 2
    Use a list or dict of objects instead. – DeGo May 10 '21 at 03:51
  • @TimRoberts I'm using the adafruit motorkit library, unfortunatly I don't have any control over the MotorKit class. – Nick S May 10 '21 at 04:07
  • @ankurbohra04 out1=["Screw", "board0.motor1"], so out1[1] should be board0.motor1 – Nick S May 10 '21 at 04:08
  • you could add link to `adafruit motorkit library` . If it is created in Python then you always can change it. – furas May 10 '21 at 07:45
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Tomerikoo May 10 '21 at 07:49
  • you can use `if/else` like `if m == "board0.motor1": m = board0.motor1`. Or you can keep it as dictionary `{"board0.motor1": board0.motor1}` – furas May 10 '21 at 07:53
  • source code uses "hidden" function [_motor(motor_name, ...)](https://github.com/adafruit/Adafruit_CircuitPython_MotorKit/blob/master/adafruit_motorkit.py#L70) to convert string name to object. And it uses `gettattr(class, variable_name`) - `gettattr(board0, "motor1")` – furas May 10 '21 at 07:56
  • 2
    eventually you should use class `MotorKit` to create own class `class MyMotorKit(MotorKit)` with all metods to access motors using string `screw` – furas May 10 '21 at 08:04

0 Answers0