Python Forum
simplifying a stack of elifs
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
simplifying a stack of elifs
#2
Skaperen Wrote:every command involves accessing and modifying local variables
Make these variables members of a class instance and dispatch things on instance methods.
class CommandHandler:
    dispatch = {
        'spam': 'on_spam',
        'eggs': 'on_eggs',
    }

    def __init__(self, ...):
        self.foo = ...
        self.bar = ...

    def __call__(self, msg):
        getattr(self, self.dispatch[msg[0]])()

    def on_spam(self):
        self.foo = 3452

    def on_eggs(self):
        self.foo = 1233
Instance variables are the normal way to share data between several functions.

You can also use new classes to manage individual commands

class Command:
    def __init__(self, handler):
        self.handler = handler

class Spam(Command):
    def run(self):
        self.handler.foo = 1023

class Eggs(Command):
    def run(self):
        self.handler.foo = 1048

class CommandHandler:
    dispatch = {
        'spam': Spam,
        'eggs': Eggs,
    }

    def __init__(self, ...):
        self.foo = ...
        self.bar = ...

    def __call__(self, msg):
        self.dispatch[msg[0]](self).run()
Reply


Messages In This Thread
simplifying a stack of elifs - by Skaperen - Aug-14-2019, 04:23 AM
RE: simplifying a stack of elifs - by Gribouillis - Aug-14-2019, 07:05 AM
RE: simplifying a stack of elifs - by Skaperen - Aug-14-2019, 06:13 PM
RE: simplifying a stack of elifs - by Gribouillis - Aug-15-2019, 06:15 AM
RE: simplifying a stack of elifs - by Skaperen - Aug-15-2019, 08:22 PM
RE: simplifying a stack of elifs - by Gribouillis - Aug-15-2019, 09:16 PM
RE: simplifying a stack of elifs - by Skaperen - Aug-15-2019, 11:51 PM
RE: simplifying a stack of elifs - by Gribouillis - Aug-16-2019, 06:51 AM
RE: simplifying a stack of elifs - by Skaperen - Aug-17-2019, 04:13 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Help for simplifying code mmk1995 8 4,327 Sep-24-2019, 02:04 PM
Last Post: perfringo
  a stack of elifs and a try/except Skaperen 2 2,048 Sep-12-2019, 11:39 PM
Last Post: Skaperen
  Simplifying my code ilondire05 5 3,877 Jul-21-2019, 03:21 AM
Last Post: scidam
  My program subtracts fractions, but for some reason isn't simplifying them RedSkeleton007 9 6,076 Mar-03-2018, 11:45 AM
Last Post: Gribouillis
  Simplifying multiple "or" conditions in if statement. rhubarbpieguy 8 102,526 Jul-22-2017, 12:19 PM
Last Post: rhubarbpieguy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020