could ildg wrote: > I think decorator is a function which return a function, is this right? > e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. > > def accepts(*types): > def check_accepts(f): > assert len(types) == f.func_code.co_argcount > def new_f(*args, **kwds): > for (a, t) in zip(args, types): > assert isinstance(a, t), \ > "arg %r does not match %s" % (a,t) > return f(*args, **kwds) > new_f.func_name = f.func_name > return new_f > return check_accepts > > After I saw all the examples, I concluded that every decorator must > define an inner function which takes only one argument, the > function to decorate. Is this right? >
Yes, but you may want to look at my decorator module: http://www.phyast.pitt.edu/~micheles/python/decorator.zip Your example would be written as follows: from decorator import decorator def accepts(*types): def check_accepts(f, *args, **kw): assert len(types) == f.func_code.co_argcount for a, t in zip(args, types): assert isinstance(a, t), "arg %r does not match %s" % (a,t) return f(*args, **kw) return decorator(check_accepts) with the following advantages: 1. one-level of nesting is saved ("flat is better than nested") 2. name, docstring and dictionary of the original function are preserved; 3. the signature of the original function is preserved (this one is nontrivial). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list