python: stateless function library design -



python: stateless function library design -

i building library of various functions reused in project. each function stateless (doesn't require parameters @ creation, , doesn't have memory). functions utilize others.

these functions passed around arguments in rest of project.

which of next approaches better?

1.define functions global functions in module:

def f1(x): # utilize x def f2(x): # utilize x , f1

2.define functions methods in classes, , arrange classes in hierarchy based on use:

class f1: def __call__(x): # utilize x f1 = f1() class f2(f1): def __call__(x): # utilize x , f1 f2 = f2()

the reason considered alternative 2 of functions have in common. e.g., functions f2, f3, f11 start calling f1. thinking might want this:

class f1: def __call__(self, x): self.f1(x) self.calc(x) def f1(self, x): # # don't define calc here; f1 abstract base of operations class class f2(f1): def calc(self, x): # class f3(f1): def calc(self, x): #

option 1 lot simpler. alternative 2 needlessly complex!!

another suggestion may create testing easier:

1.1. define them methods of single class in 1 module. utilize @staticmethod , @classmethod decorators appropriate. can create them easier substitute mocks or override alternate implementations providing new class or subclass later.

spam.py:

class spam(object): @staticmethod def f1(x): # utilize x @classmethod def f2(cls, x): # utilize x , cls.f1

this still more complex may want stick alternative 1 until have need above.

python design python-3.x

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -