I have a project that parses pushes from pushbullet and executes functions based on input. Here is my Push class:
class Push():
def __init__(self, push):
r = push
self.iden = r['iden']
self.type = r['type']
if self.type == 'note':
self.body = r['body']
def register(self):
self.is_processed = False
push_log.append_iden(self.iden)
def expire(self):
self.is_processed = True
push_log.update_status(self.iden)
def is_command(self):
if '!' in self.body:
return True
else:
return False
So when the program detects a command, it runs another set of class function:
def process_command(self):
if 'shoot' in self.body:
try:
shoot()
self.expire()
except:
self.expire()
elif 'getip' in self.body:
try:
get_ip()
self.expire()
except:
self.expire()
elif 'wol' in self.body:
try:
ip = self.body.split(" ")[1]
wake_on_lan(ip)
self.expire()
except:
self.expire()
Notice that get_ip(), wake_on_lan(ip) and shoot() are not defined in class. However i'd like to avoid code repetition as much as possible. So i'm trying to re-write the process_command(self) function. I specifically want to avoid repeating self.expire() try/except clauses.
def process_command(self):
command_list = ['shoot', 'getip', 'wol']
for command in command_list:
if command in self.body:
try:
# do something
self.expire()
else:
self.expire()
except:
self.expire
Which partially solves my problem. Is this a sane approach? I want to improve it by providing a tuple of (input command, function to execute) e.g.
command_list = [('shoot', shoot()), ('getip', get_ip()), ('wol', wake_on_lan(self.body.split(" ")[1]))]
However functions are executed on the go. Is there a better way of doing this?
EDIT
Based on responses here's the edited process_command. Thanks @deceze, @Jean and @Thierry.
def process_command(self):
command_count = 0
command_dict = {
'shoot': shoot,
'getip': get_ip,
'wol': wake_on_lan
}
for command in command_dict.keys():
if command in self.body:
try:
if command_count < 2:
# do something
else:
# do something else
except:
# raise/catch exception
finally:
self.expire()
self.expire
inside thetry
block, since you want to run it unconditionally in any case, and just put it after the entireif..else
block…!? – deceze♦ Dec 9 '19 at 8:15self.expire()
should be put in afinally:
block for it to run no matter what. – Jean-François Corbett Dec 9 '19 at 8:18if..else
block, there's no big need for a grandfinally
. But yes, perhaps this can be restructured intotry: if .... finally: self.expire()
. – deceze♦ Dec 9 '19 at 8:19