Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #36940

Param decorator - can you suggest improvements

Newsgroups comp.lang.python
Date 2013-01-17 06:35 -0800
Message-ID <00a6f42e-58e9-4e5e-b124-5b315990829c@googlegroups.com> (permalink)
Subject Param decorator - can you suggest improvements
From Mark Carter <alt.mcarter@gmail.com>

Show all headers | View raw


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?

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Param decorator - can you suggest improvements Mark Carter <alt.mcarter@gmail.com> - 2013-01-17 06:35 -0800
  Re: Param decorator - can you suggest improvements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-17 15:21 +0000
    Re: Param decorator - can you suggest improvements Dan Sommers <dan@tombstonezero.net> - 2013-01-18 03:38 +0000
      Re: Param decorator - can you suggest improvements Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-18 09:10 +0000
        Re: Param decorator - can you suggest improvements Dan Sommers <dan@tombstonezero.net> - 2013-01-18 14:18 +0000

csiph-web