mardi 14 août 2018

Design pattern for implementing different "bundles" of functions in Python 3.6

so I have a set of distance functions and respective calculations, e.g. average, comparison

and I want to be able to iterate over those different distances to compute their values/averages/whatevers, and make it easy to add new distances

Right now, I'm doing that by using nested dictionaries, however this depends on all the functions existing and working properly, so I was wondering whether there is a design pattern that solves that?

My first idea was a metaclass that defines which functions need to exist and classes that implement these functions. However, then there would be no meaningful instances of those Distance classes. My second idea then was defining a Distance class and have the functions as attributes of that class, but that seems bad style. Example for the second Idea:

class Distance:
    def __init__(self, distf, meanf):
        self.distf = distf
        self.meanf = meanf

    def dist(self, x1,x2):
        return self.distf(x1,x2)

    def mean(self, xs):
         return self.meanf(xs)

    d = Distance(lambda x,y: abs(x-y), np.mean)

    d.dist(1,2) ##returns 1 as expected
    d.dist([1,2]) ## returns 1.5 as expected

this works (and also enforces the existence/maybe even properties of the functions), but as stated above feels like rather bad style. I do not plan to publish this code, its just about keeping it clean and organized if that is relevant. I hope the question is clear, if not pleas dont hesitate to comment and I will try to clarify.

Aucun commentaire:

Enregistrer un commentaire