[Python-ideas] adding possibility for declaring a function in Matlab's way

Géza kgeza7 at gmail.com
Mon Feb 14 10:47:59 CET 2011


All,

Thank you for the constructive remarks,
especially Bruce Leban for pointing out the TOOWTDI principle, which is why 
it wouldn't fit into the Python philosophy,
and Stephen J. Turnbull for the idea of doing it with decorators.

I could actually implement something similar to what I wanted with 
decorators,
although it still needs improvement.

All the best, Géza

P.S. This is somewhat off-topic, but if someone has ideas on improving it, 
personal replies are welcome.

Two things that are not really nice about it:
one, you need to specify the variable names between quotes,
two, you may get "unused variable" warnings for the return variables.
See the code below.

(I intentionally did not try to initialize the local variables to None,
as I realized that this is the behavior of Matlab, too, which makes sense:
You should be told if you forget to calculate the value of a return 
variable.)

'''
MtFn.py version 1.0
Uses code from persistent_locals2 by Pietro Berkes and Andrea Maffezzoli.
@author: Geza Kiss
'''
import sys

class MtFn:
  def __init__(self, sRetVars):
    self.lRetVars=[s.strip() for s in sRetVars.split(',')]
    self._locals = {}

  def __call__(self, function):
    def Mt2PyFn(*args):
      def tracer(frame, event, arg):
        if event=='return':
          self._locals = frame.f_locals.copy()
      prev_tracer=sys.setprofile(tracer)
      try:
        res=function(*args)
      finally:
        sys.setprofile(prev_tracer)
      if res:
        raise ValueError("You must not return a value in Matlab-like (@MtFn) 
function '%s'." % (function.__name__))
      try:
        return tuple([self._locals[var] for var in self.lRetVars])
      except KeyError as exc:
        raise KeyError("Return value '%s' is not set in Matlab-like (@MtFn) 
function '%s'." % (exc.args[0], function.__name__))

    return Mt2PyFn

----------------
'''
MtFnTest.py
'''

from MtFn import MtFn

@MtFn('a,b')
def fun(x,y):
  a=x+y
  b=x-y

print fun(5,6)




More information about the Python-ideas mailing list