I'd like to write kind of CPS code higher functions. They should take a function code, encapsulate it in the object and add means for combining this objects.
Something like this:
myFunction=MyFunction(
a = b+c
print(c)
return a)
But there is only one pythonic expression for anonymous functions - lambda statement. It suits not too well.
Python is a powerful language, it has different expressions: decorators, eval, etc... Is there a good way to write anonymous functions like in the mentioned example?
Other way is to extend lambda expressions with special functions like monadic bind and return, and other higher-order functions for writing complex expressions single-lined.
The main purpose is to create custom throw control expressions.
class TimeoutExpression:
def __init__(self,name,function,timeout):
...
def eval(self):
""" eval functions, print result and error message
if functions failed to calculate in time """
...
def andThen(self,otherExpression):
""" create complex sequential expression"
...
def __call__(self):
...
And it is used in the follow way:
TimeoutExpression( time consuming calculation ).andThen(
file object access).andThen(
other timer consuming calcualtion )
What is the best python idiomatic way for creating custom control flow constructions?
I've read the discussion: How to make an anonymous function in Python without Christening it? There were mentioned several decisions with same approach: generating function from triple quoted strings. It is seemed quite cumbersome while absolutely correctly behave. Is it the best approach engineered for now?
Update:
I was told there is no problem, python allows you use def in any context. I've assumed that my python experience tricks me and tried to use def in any scope as suggested. I've got an error. How exactly should I place def in any context?
def compose(f):
return lambda k: lambda x: f(k(x))
test = compose( def sqr(x) :
print ("sqr "+str(x))
return x*x
return sqr) ( def x2(x):
print("x2 "+str(x))
return x*2
return x2 )
The error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "anonFunction.py", line 4
test = compose( def sqr(x) :
^
SyntaxError: invalid syntax