python - How to avoid boilerplate when writing wrapper classes or functions? -


i have found myself writing wrapper class on many back-end classes implement similar interfaces. rudimentary version looks this:

class wrapper(backendinterface):     def __init__(self, **kwargs):         # instantiate/initialize backend classes         self._b1 = backendone(...)         self._b2 = backendtwo(...)         ...      def _select_backend(self, ...):         # select backend based on runtime requirements         if condition_one:             return self._b1         elif condition_two:             return self._b2         ...      def method_one(self, foo, bar, baz, alpha, beta, gamma, delta, ...):         b = self._select_backend(...)         b.method_one(foo, bar, baz, alpha, beta, gamma, delta, ...)      def method_two(self, a, b, c, d, ...):         b = self._select_backend(...)         b.method_two(a, b, c, d, ...)      ... 

as shown above, many (but not all) of methods boil down back-end selection followed call same method on back-end object. in many cases, method signature identical. there way avoid boilerplate mess?

i have considered using locals() @ top of each method.

... def method_one(self,  foo, bar, baz, alpha, beta, gamma, delta, ...):     args = locals() # must first line!     del args['self']     b = self._select_backend(...)     b.method_one(**args) ... 

i believe similar results can obtained using inspect module.

there problems approach though. 1. there still lot of boilerplate. 2. locals() call must on first line. pretty sure try 'optimize' method @ point , mess up.

is there better approach can use??

i interested in knowing how deal such situation in java.

note: using python 2.7.11, if matters.

edit: removed java tag. i'll ask question separately java. way python developers don't have read java code , vice-versa.

surely can accept *args - or *args, **kwargs - in methods , pass backend?

def method_one(self, *args, **kwargs):     b = self._select_backend(...)     b.method_one(*args, **kwargs) 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -