Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8700349
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T02:09:10+00:00 2026-06-13T02:09:10+00:00

I have a long if-elif chain, like this: class MyClass: def my_func(self, item, value):

  • 0

I have a long if-elif chain, like this:

class MyClass:
    def my_func(self, item, value):
        if item == "this":
            self.do_this(value)
        elif item == "that":
            self.do_that(value)
        # and so on

I find that difficult to read, so I prefer to use a dictionary:

class MyClass:
    def my_func(self, item, value):
        do_map = {
            "this" : self.do_this,
            "that" : self.do_that,
            # and so on
        }

        if item in do_map:
            do_map[item](value)

It’s silly to recreate the map every time the function is called. How can I refactor this class so that the dictionary is only created once, for all instances? Can I somehow turn do_map into a class member, yet still map to instance methods?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T02:09:10+00:00Added an answer on June 13, 2026 at 2:09 am

    You have lots of options!

    You could initialize the map in the __init__ method:

    def __init__(self):
        self.do_map = {"this": self.do_this, "that": self.do_that}
    

    Now the methods are bound to self, by virtue of having been looked up on the instance.

    Or, you could use a string-and-getattr approach, this also ensures the methods are bound:

    class Foo(object):
        do_map = {"this": "do_this", "that": "do_that"}
    
        def my_func(self, item, value):
            if item in self.do_map:
                getattr(self, self.do_map[item])(value)
    

    Or you can manually bind functions in a class-level dictionary to your instance using the __get__ descriptor protocol method:

    class Foo(object):
        def do_this(self, value):
            ...
    
        def do_that(self, value):
            ...
    
        # at class creation time, the above functions are 'local' names
        # so can be assigned to a dictionary, but remain unbound
        do_map = {"this": do_this, "that": do_that}
    
        def my_func(self, item, value):
            if item in self.do_map:
                # __get__ binds a function into a method
                method = self.do_map[item].__get__(self, type(self))
                method(value)
    

    This is what self.method_name does under the hood; look up the method_name attribute on the class hierarchy and bind it into a method object.

    Or, you could pass in self manually:

    class Foo(object):
        def do_this(self, value):
            ...
    
        def do_that(self, value):
            ...
    
        # at class creation time, the above functions are 'local' names
        # so can be assigned to a dictionary, but remain unbound
        do_map = {"this": do_this, "that": do_that}
    
        def my_func(self, item, value):
            if item in self.do_map:
                # unbound functions still accept self manually
                self.do_map[item](self, value)
    

    What you pick depends on how comfortable you feel with each option (developer time counts!), how often you need to do the lookup (once or twice per instance or are these dispatches done a lot per instance? Then perhaps put binding the methods in the __init__ method to cache the mapping up front), and on how dynamic this needs to be (do you subclass this a lot? Then don’t hide the mapping in a method, that’s not going to help).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How do you handle user stories/acceptance tests that have long chains like this one,
I have long strings. Like this {{ name = name prodcuer =producer writer =
I have the following decorator in a base class: class BaseTests(TestCase): @staticmethod def check_time(self,
I have a configuration class that I would like to use for a variety
Perhaps any of you can help me with this anoying problem. I have long
i have long running task that gets called using jquery ajax. i am using
I have a class that is a manager sort of class. One of it's
I have long integer value ( ex: 2705758126 ) in NSString. When i try
I have long text . And I'm converting this string to dict. Here is
I have long known that you can load style rules into a page dynamically

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.