Implementing a callbacks in Python using Strategy Design Pattern

Implementing a callbacks in Python using Strategy Design Pattern


"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."


1. Callbacks are used in functional programming which takes an function but calls when certain certain conditions is met later in time.

2. Its similar to "Strategy Pattern" where the same piece of code must have different behavior for different invocation by different clients.

3. Primary use case is to switch implementation in OPEN CLOSED PRINCIPLE.

4. Behavior is selected in RUN-TIME.

#Strategies as CallBacks
class ReverseInt(object):def __init__(self):
        self.description = "Integer Reverse Callbacks"
        self.value = int

    def __call__(self, val):return self.description, str(val)[::-1]

#Strategies as CallBacks
class ReverseStr(object):def __init__(self):
        self.description = "String Reverse Callbacks"
        self.value = str

    def __call__(self, val):return self.description, val[::-1]


#ABSTRACTION Open for Extension
class Reverse(object):

    def __init__(self):# Extensible Implementation of more callbacks
        self._impls = [ReverseInt(),ReverseStr()]

    def __call__(self, reverseme):"""select the strategy based on type parameter"""for impl in self._impls:
          if impl.value == type(reverseme):
            return impl(reverseme)
      else:
          return None

#But close for modification reverseFunction name cannot be changed
reverseFunction = Reverse()

# The Functions are unaware of implementations "Behavior is selected in RUNTIME"
print(reverseFunction(1234))
print(reverseFunction("abcde"))


Download the Complete Code: Code at REPL

To view or add a comment, sign in

More articles by Shivam C.

  • SQLAlchemy ORM Advance Usage

    SQLAlchemy is the most widely used ORM in Python based application; its backend neutral and offers complete flexibility…

  • Finding optimum K for K-Means Clustering

    K-Means is a very common and popular clustering algorithm used by many developers all over the world. When using…

  • GO: Things in parenthesis before function name

    Have you ever wondered what does parameters before the functions means. func (h handler) ServeHTTP(w http.

    1 Comment
  • Python Evil Default Function Arguments

    Sometimes you will want to pass default variables into your Python functions and methods. To do so, you want to fully…

  • Denial of Service & Distributed Denial of Service Attack

    Attacking a website by using various vectors like HTTP and HTTPS floods, SYN flood, SSL attacks to make it unavailable…

Insights from the community

Others also viewed

Explore topics