functional programming - Optimal way of defining constants in a python function -
this might more theoretic question practical one, not make significant difference in runtime of program. @ least not in case.
i have received python code imports different ("homemade") functions. 1 function (call func) called 5 times main script (call main).
in func lot of constants defined in beginning of function. example:
import numpy np def func(x,y,z): c0 = np.array([1,2,3]) c1 = np.array([1,2,3]) c2 = np.array([1,2,3]) c3 = np.array([1,2,3]) #do stuff variables x,y,z #return stuff
i wondering: when calling function, constants c0,...,c3 defined each time function called, or "fixed" when compiled bytecode when running main script, defined once?
yes, defined each time function called.
the dynamic nature of python means value of np.array
may have changed in time between function's definition , call (and betweeen calls), compiler has no opportunity evaluate them "in advance".
if save them in closure, can make them evaluated once without introducing them globals.
example:
def _func(): c0 = np.array([1,2,3]) c1 = np.array([1,2,3]) c2 = np.array([1,2,3]) c3 = np.array([1,2,3]) def actual_func(x, y, z): # stuff # return stuff return actual_func _func_closure = _func() def func(x, y, z): return _func_closure(x, y, z)
the last definition there avoid making global variable out of function - func = _func()
works equally if don't mind that.
this can written more elegantly, illustrates idea, "add level of indirection".
disclaimer: have absolutely no idea whether has better performance.
(if you're interested in "tricks" this, there's plenty in decent book on lisp.)
Comments
Post a Comment