3 ms·
I find the wildcards most useful when implementing decorators or other cross-cutting metaprogramming features. For example, you could easily do a tracing decor
by nostrademons 13y ago
I find the wildcards most useful when implementing decorators or other cross-cutting metaprogramming features. For example, you could easily do a tracing decorator like this:
def trace(fn):
def worker(*args):
logging.info('Called %s with args %r', fn.__name__, args)
return fn(*args)
worker.__name__ = fn.__name__
# other decorator boilerplate
return worker
@trace
def foo(bar, baz):
...
@trace
def foo2(x1, x2, x3):
...
(Note that logging.info itself takes args & kwargs as its arguments, and passes them along as formatting arguments for the string.)
If you've ever looked at AspectJ or even Haskell, this sort of functionality is virtually impossible in a statically-typed language. You go through all sorts of contortions to be able to say "I want to operate on any type of function, and I don't care how many or what type of arguments it has", and then come out with something insanely complicated that satisfies nobody. For certain use-cases, you really don't care what type of arguments it takes, you just want to pass it through to some other function.
I do wonder if there's some other language feature that could be used to achieve this without breaking documentation or static analysis, though.
- lclarkmichalek 13y agoYou can use the `functools.wraps` decorator to deal with copying all (most) metadata from the wrapped function: def trace(fn): @functools.wraps(fn) def worker(*args): logging.info('Called %s with args %r', fn.__name__, args) return fn(*args) return worker Docs: http://docs.python.org/3/library/functools.html#functools.wraps http://docs.python.org/3/library/functools.html#functools.wr...
- darth_aardvark 13y agoI've been looking for something exactly like this. It's so tedious trying to remember what metadata needs to be copied from a function when making a decorator. Thanks!