import ast import inspect FUNC_NAME = "__lambda__" def λ(*args): prev_frame = inspect.currentframe().f_back body = ast.parse(args[-1], "", "exec").body args = args[:-1] def make_arg(a): a = ast.arg(a, None, None) a.lineno = 0 a.col_offset = 0 return a arguments = ast.arguments(posonlyargs=[], args=[make_arg(a) for a in args], kwonlyargs=[], kw_defaults=[], defaults=[]) arguments.lineno = 0 arguments.col_offset = 0 func = ast.FunctionDef(FUNC_NAME, arguments, body, []) func.lineno = 0 func.col_offset = 0 toplevel = ast.Interactive([func]) toplevel.lineno = 0 toplevel.col_offset = 0 func = compile(toplevel, "", "single") exec(func, prev_frame.f_globals, prev_frame.f_locals) func = prev_frame.f_locals[FUNC_NAME] del prev_frame.f_locals[FUNC_NAME] return func # Examples: # # λ("""print("haha multiline lambdas") # return 1337""")() # # -------------------------------------- # # λ("a", "b", "c", """if a: # return b # else: # return c""")(False, 1, 2) # # -------------------------------------- # # meow = 10 # λ("a", "b", "c", """if a: # return b + meow # else: # return c + meow""")(False, 1, 2) # # -------------------------------------- # # def my_func(): # meow = 20 # return λ("cnd", """if cnd: # return meow # else: # return 'nope'""") # # meow = 30 # my_func()(True) # # -------------------------------------- # # def my_func(): # meow = 20 # return λ("cnd", """global meow # if cnd: # return meow # else: # return 'nope'""") # # meow = 30 # my_func()(True) #