Reputation: 619
I have a working code built around RPi.GPIO module and want to optimize a certain part that I feel it does not fit well cosmetically (not the whole, only a part of the code) -- except that I don't know how.
Here is a code to exemplify the context. The "offending" lines are just below the comment # question: how to optimize these lines?
. I explicitly need the calls to be individual, one of the reasons being "in this case, the callback functions are run sequentially, not concurrently" (quote from docs), which I prefer for my particular usage.
Documentation for RPi.GPIO can be found here, but there's not much to read and I assume the callback style can be found in other situations too.
#!/usr/bin/env python
# RPi.GPIO module for Raspberry Pi https://pypi.python.org/pypi/RPi.GPIO
import RPi.GPIO as GPIO
import sys
import os
import time
class test(object):
def __init__(self):
pass
def main(self):
# consider BCM port numbering convention
GPIO.setmode(GPIO.BCM)
ports = [16, 20, 23] # 3 ports only for this example, might be n ports
# actual port number is not relevant to question
for i, port in enumerate(ports):
# setup port direction & internal pull-up
GPIO.setup(port, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# setup interrupt movement sense
GPIO.add_event_detect(port, GPIO.FALLING)
# question: how to optimize these lines? (compact in a loop or something)
GPIO.add_event_callback(16, self.do_something_1)
GPIO.add_event_callback(20, self.do_something_2)
GPIO.add_event_callback(23, self.do_something_3)
# etc. (might be n event callbacks, not just 3)
while True:
time.sleep(1)
# some internal calls or even as separate external file(name) modules
def do_something_1(self, from_port): # for first port in ports
print("called from port %s" % (from_port))
def do_something_2(self, from_port): # for second port in ports
print("called from port %s" % (from_port))
def do_something_3(self, from_port): # for third port in ports
print("called from port %s" % (from_port))
# etc. (might be n defined functions, not just 3)
if __name__ == "__main__":
try:
app = test()
app.main()
except KeyboardInterrupt:
print (" exit via Ctrl+C")
finally:
GPIO.cleanup()
try:
sys.exit(0)
except SystemExit:
os._exit(0)
So, question: what should I do with those 3 (or generic other random number) lines ?
Upvotes: 2
Views: 241
Reputation: 3208
How are the numbers/names in the callbacks determined? If it's arbitrary, you're probably doing it just fine at the moment.
That said, you could create a list of numbers-function tuples and then call them all in a for loop? But this isn't much better imho.
callback_pairs = [(16, "do_something_1"), (20, "do_something_2"), (23, "do_something_3")]
for n, fname in callback_pairs:
GPIO.add_event_callback(n, getattr(self, fname))
You could get rid of the getattr
nastiness by just directly referencing self.do_something_[123]
in the list of pairs, too.
What you're doing now isn't wrong though.
Upvotes: 2