Issue
I am using Python 3.5.2 (the one used for MS SQL Server Machine Learning Services). I would like to have a lambda
expression that uses with so not to repeat an expensive calculation in a tuple. A minimal example is
lambda x :
with x**2 as x2, x**3 as x3 :
[ (x2**3)*x3-x3 , x2, (x3-5)**x2 ]
However, this returns a syntax error. How is a with
statement used in a lambda
expression?
I am coming from Wolfram Language where this can be done. For example
With[{x2 = #^2, x3 = #^3},
{ (x2^3)*x3-x3 , x2, (x3-5)^x2 }
]&
I have a collection of these tiny calculations that are only needed in a small part of the code (within another function). I want to hold these as lambda functions to select and apply
/map
based particular conditions in that function.
Solution
In python, this is spelled:
def fun1(x):
x2 = x**2
x3 = x**3
return [(x2**3) * x3 - x3 , x2, (x3 - 5) ** x2]
EDIT:
A couple more points...
First: someone mentions in a comment tha you could cache computation results for improved performances. It's indeed a common pattern usually named memoization, which is rather easy to implement in Python. Just note that this only works properly with pure functions, and is of course only beneficial if the memoized function is repeatedly called with the same arguments.
Second point, you mention that:
I have taken this route and defined the mini functions within the function.
You have to know that in Python, def
is an executable statement that creates a new function
object (yes, Python functions are objects - actually everything in Python is an object) when executed.
This means that "top-level" functions (functions defined at the top-level of a module) are created once when the module is first imported in the current process, but that inner (nested) functions are created anew each time the outer (enclosing) function is called.
Also, Python functions are closures, so a nested function can capture the environment of the outer function (and it's the main - and only as far as I'm concerned - reason for using nested functions in Python).
This means that you can use inner functions as another way to cache some precomputed values and make them available to a set of functions, ie:
def outer(x, y):
x2 = x ** 2
x3 = x ** 3
def func1():
return [(x2**3) * x3 - x3 , x2, (x3 - 5) ** x2]
def func2(z):
# dummy example
return (x2**y) + (y - x3 ** z)
# etc
results = [func2(i) for i in func1()]
return results
On the other hand, if your "helper" functions are not dependant on their enclosing scope, the only thing you get from defining them within the outer function is the overhead of creating the same functions again and again and again each time the outer function is called. It's of course not a problem if the outer func is only called once or twice per process, but if it's invoked in a tight loop the overhead can quickly become an issue.
Answered By - bruno desthuilliers
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.