I thought it would be interesting to try to implement Scheme SRFI 39 (Parameter 
objects) in Python.

The idea is that you define a function that returns a default value. If you 
call that function with no arguments, it returns the current default. If you 
call it with an argument, it resets the default to the value passed in. Here's 
a working implementation:

# http://www.artima.com/weblogs/viewpost.jsp?thread=240845

from functools import wraps

class Param(object):
    def __init__(self, default):
        self.default = default
        #self.func = func

    def __call__(self, func, *args):
        @wraps(func)
        def wrapper(*args):
            #print 'calling hi'
            if len(args) >0:
                self.default = args[0]
            #print len(args),  ' ', args
            return self.default # self.func(*args)
        return wrapper


@Param(42)
def hi(newval):
    pass

print hi() # 42
print hi(12) # 12
print hi() # 12
hi(13) # sets it to 13
print hi() # 13


Can anyone suggest a better implementation?
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to