Use package `multipledispatch` to expose R's S4 methods

Issue #254 new
Laurent Gautier created an issue

R's S4 methods work with multiple dispatch.

Consider the following example in R:

setClass("NormalDistribution", contains="Distribution",
               representation(mu="numeric", sigma="numeric"))

setMethod("+", signature(n1="NormalDistribution", n2="NormalDistribution"),
              function(n1, n2) {
                              mu = n1@mu + n2@mu,
                              sigma = sqrt( (n1@sigma)^2 + (n2@sigma)^2 )

The translation in Python (using multipledispatch) would be (there is an added nicety because Python has the special method __add__:

from multipledispatch import dispatch
class Distribution(object):
class NormalDistribution(Distribution):
    mu = None
    sigma = None
    def __init__(self, mu, sigma): = mu
        self.sigma = sigma
    def __add__(self, nd):
        return add(self, nd)
import math
@dispatch(NormalDistribution, NormalDistribution)
def add(n1, n2):
    return NormalDistribution( +,
                              math.sqrt(n1.sigma**2 + n2.sigma**2))

Using metaprogramming, it should be possible to generate on the fly from R definitions. There is already an effort in that sense in the code base but the solution is both an inelegant implementation and unpleasant one to use.

Comments (5)

  1. Log in to comment