Using decorators with argument in Python
Ian Kelly
ian.g.kelly at gmail.com
Wed Jun 29 17:26:22 EDT 2011
On Wed, Jun 29, 2011 at 3:29 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> 8<----------------------------------------------------------------
> class enclose(object):
> func = None
> def __init__(self, char='#'):
> self.char = char
> if callable(char): # was a function passed in directly?
> self.char = '#' # use default char
> self.func = char
> def __call__(self, func=None, *args, **kwargs):
> if self.func is None:
> self.func = func
> return self
> if func is not None:
> args = (func, ) + args
> return self._call(*args, **kwargs)
> def _call(self, *args, **kwargs):
> print("\n" + self.char * 50)
> self.func(*args, **kwargs)
> print(self.char * 50 + '\n')
> if __name__ == '__main__':
> @enclose
> def test1():
> print('Spam!')
> @enclose('-')
> def test2():
> print('Eggs!')
> @enclose
> def test3(string):
> print(string)
> @enclose('^')
> def test4(string):
> print(string)
> test1()
> test2()
> test3('Python')
> test4('Rules! ;)')
> 8<----------------------------------------------------------------
@enclose
def test5(string, func):
print(func(string))
test5('broken', func=str.upper)
More information about the Python-list
mailing list