Sitemap

Pythonic Forwardable

2 min readAug 14, 2019

--

When I started acclimatising myself with a project in Ruby, i came across an inbuilt module in ruby called the Forwardable. The Forwardable module provides delegation of specified methods to a designated object.

Get vivek soundrapandi’s stories in your inbox

Join Medium for free to get updates from this writer.

For example, lets say we have class for ADT Queue. For simplicity let us consider an Array based Queue. In its core the Queue class will have an array and perform queue specific operations on top of it.

class Queue
def initialize
@q = []
end

def
enqueue

end

def
dequeue

end

end

Though enqueue/dequeue are operations specific to a Queue by nature they can be translated to an array’s push and shift operations respectively thereby avoid the re-implementation of those logic. Hence, we could just delegate the methods of Queue to the array class as desired.

class Queue
extend Forwardable

def_delegator :@q, :push, :enqueue
def_delegator :@q, :shift, :dequeue

def initialize
@q = []
end
end

q = Queue.new
q.enqueue 1, 2, 3, 4, 5

The below would be a basic equivalent of forwardable module as a python Mixin.

The setup:

A module in ruby is ruby’s way of extending a class’s capability with additional behaviours[closest equivalent could be Mixins in python]. So, we start with writing a Mixin class.

class Forwardable(object):
def __init__(self, *args, **kwargs):
self._delegates = []
return super().__init__(*args, **kwargs)

The class has a delegates attribute which will be an array of tuples(NamedTuples can also be used for better readability)with

  • composed object name at index 0
  • attribute to listen for at index 1and
  • delegated attribute at index 2.

Now let us add getter and setter for our delegates attribute:

class Forwardable(object):
def __init__(self, *args, **kwargs):
self._delegates = []
return super().__init__(*args, **kwargs)
@property
def delegates(self):
return self._delegates
@delegates.setter
def delegates(self, delegates):
self._delegates = delegates

The next step will be to listen on the attribute call and delegate it to the composed object if it is in our _delegates ADT. To achieve this, we can make use of python’s getattr method.

__getattr___:

In Python, when we try to access an attribute within an object , first the attribute is looked up upon in the following hierarchy:

  1. Current objects scope
  2. Current class’s scope
  3. Parent classes based on MRO principle[a strategy used by python to avoid the problem of multiple inheritance]

Now, when an attribute is not found in ay of the above, python makes a call to __getattr__ method which in turn raises an AttributeError.

Core Logic:

We can tap into this behaviour of python, by overriding the getattr method and introduce a simple lookup into the _delegates array and delegate if necessary.

The raise part at the end is a mandate as we override default methods like getattr , we will not be able to call super.

Usage:

As this is a mixin i can plug and play with any class down the inheritance and it will work fine.

class Queue(Forwardable):
def __init__(self):
self.q = []
self.delegates = [("q","enqueue", "append")]
que = Queue()
que.enqueue(1)
print que.q
Output:
>>>[1]

Gist to full code:

--

--