Short but complete, summary
I want to allow users of my function (factory class) to enter / overwrite global imports when using my function (more detailed explanation of the explanation below). But there are about 10 different variables that can be passed, and it adds several repeating lines to the code. (provided, also makes calling difficult: P) Now I am doing something like the following (just simplifying all this). To make it doable, I use a dummy class, but in the actual script I would use import pkg1, etc. I realized that it was clearer and shorter than the factory class, etc.
class Dummy(object): pass
pkg1, pkg2 = Dummy(), Dummy()
pkg1.average = lambda *args : sum(args) / len(args)
pkg2.get_lengths = lambda *args : map(len, args)
def get_average(*args, **kwargs):
average = kwargs.get("average") or pkg1.average
get_lengths = kwargs.get("get_lengths") or pkg2.get_lengths
return average(*get_lengths(*args))
adjusted_length = lambda *args: map(len, args) + [15]
print get_average([1,2], [10, 4, 5, 6]) == 3
print get_average([1,2], [10, 4, 5, 6], get_lengths=adjusted_length) == 7
Related SO Questions
: Python, , , locals, (1) didn , , (2) , . , , .
( python), , , . ( - python: ` globals` - , ( ) ).
, exec (, - python exec()), , , // ..
, . (: from pkg1 import average AND from pkg2 import get_lengths
, ( pkg1 pkg2 , ))
average = pkg1.average
get_lengths = pkg2.get_lengths
def get_average(*args, **kwargs):
localvars = locals()
for k in ("get_lengths", "average"):
if kwargs.get(k, None) and kwargs[k] is not None:
localvars[k] = kwargs[k]
return average(*get_lengths(*args))
print get_average([1,2], [10, 4, 5, 6]) == 3
print get_average([1,2], [10, 4, 5, 6], get_lengths=adjusted_length) == 7
factory ( SQLAlchemy mixin), , SQLAlchemy, ..
, Flask-SQLAlchemy , SQLAlchemy, / (db), SQLAlchemy, .