function return_values=function_name(function params)
If you would like to have a similar format in Python,
you can use a decorated function with a little script I wrote (see below).
It still needs to be improved, and I welcome constructive comments on this.
Two very simple examples on how to use it:
from MtFn import returns
@returns('a,b')
def fun(x,y):
a=x+y
b=x-y
@returns('e')
def approximateEulersNumber(steps):
e=1.0
factorial=1
for i in range(1,steps+1):
factorial*=i
e+=1.0/factorial
print fun(1,2)
print approximateEulersNumber(100)
Two things that could be improved:
1. You need to add quotes around the names of the return variables.
2. You may get "unused variable" warnings for the return variables.
And finally, the module you can import to be able to use it:
'''
Created on Feb 11, 2011
Uses code from persistent_locals2 by Pietro Berkes and Andrea Maffezzoli.
@author: Geza Kiss
'''
import sys
class returns:
def __init__(self, sRetVars):
self.lRetVars=[sVar.strip() for sVar in sRetVars.split(',')]
def __call__(self, fnDecorated):
def Mt2PyFn(*args):
def tracer(frame, event, arg):
if event=='return':
try:
self.tRetVars = tuple([frame.f_locals[var] for var in self.lRetVars])
except KeyError as excKey:
raise KeyError("Return value '%s' is not set in function '%s'." % (excKey.args[0], fnDecorated.__name__))
fnPrevTracer=sys.getprofile()
sys.setprofile(tracer)
try:
res=fnDecorated(*args)
finally:
sys.setprofile(fnPrevTracer)
if res is not None:
raise ValueError("You must not return a value explicitly in function '%s'." % (fnDecorated.__name__))
if 1==len(self.tRetVars):
return self.tRetVars[0]
else:
return self.tRetVars
return Mt2PyFn
This post has been edited by Geza: 19 February 2011 - 11:24 PM

New Topic/Question
This topic is locked




MultiQuote









|