我几乎有我想要的东西......
此动态对象使用动态docstring生成封装通用函数调用:
def add_docs(tool):
def desc(func):
func.__doc__ = "Showing help for %s()" % tool
return func
return desc
class Dynamic(object):
def __getattr__(self, value):
@add_docs(value)
def mutable_f(*args, **kwargs):
print "Calling:", value
print "With arguments:", args, kwargs
return mutable_f
它按预期工作:
>>> Dynamic().test(1, input='file')
Calling: test
With arguments: (1,) {'input': 'file'}
>>> Dynamic().test.__doc__
'Showing help for test()'
唯一的两个问题是帮助显示mutable_f
签名
>>> help(Dynamic().test)
Help on function mutable_f in module __main__:
mutable_f(*args, **kwargs)
Showing help for test()
(END)
并且没有自动完成(我可以在运行中获得有效函数列表,并缓存它,因为该操作很昂贵)
我认为第一个是无法解决的,但我对第二个不太确定。 想法?
答案 0 :(得分:6)
自动完成通常会使用可以挂钩的dir()
function输出。只需实现__dir__()
方法:
def __dir__(self):
res = dir(type(self)) + list(self.__dict__.keys())
res.extend(['dynamic1', 'dynamic2'])
return res
至于在匹配签名时包装函数,您需要根据该签名构建一个外观。我done exactly that for a Zope security feature:
import inspect
import functools
class _Default(object):
def __init__(self, repr):
self._repr = repr
def __repr__(self):
return self._repr
def _buildFacade(name, spec, docstring):
"""Build a facade function, matching the decorated method in signature.
Note that defaults are replaced by instances of _Default, and _curried
will reconstruct these to preserve mutable defaults.
"""
args = inspect.formatargspec(
formatvalue=lambda v: '=_Default({0!r})'.format(repr(v)), *spec)
callargs = inspect.formatargspec(formatvalue=lambda v: '', *spec)
return 'def {0}{1}:\n """{2}"""\n return _curried{3}'.format(
name, args, docstring, callargs)
def add_docs(tool):
spec = inspect.getargspec(tool)
args, defaults = spec[0], spec[3]
arglen = len(args)
if defaults is not None:
defaults = zip(args[arglen - len(defaults):], defaults)
arglen -= len(defaults)
def _curried(*args, **kw):
# Reconstruct keyword arguments
if defaults is not None:
args, kwparams = args[:arglen], args[arglen:]
for positional, (key, default) in zip(kwparams, defaults):
if isinstance(positional, _Default):
kw[key] = default
else:
kw[key] = positional
return tool(*args, **kw)
name = tool.__name__
doc = 'Showing help for {0}()'.format(name)
facade_globs = dict(_curried=_curried, _Default=_Default)
exec _buildFacade(name, spec, doc) in facade_globs
wrapped = facade_globs[name]
wrapped = functools.update_wrapper(wrapped, tool,
assigned=filter(lambda w: w != '__doc__', functools.WRAPPER_ASSIGNMENTS))
return facade_globs[name]
对于方法签名,几乎,这将是正确的。你不能在这里绕过可变的默认值,并且需要明确地处理它们以保留它们。
小型演示:
>>> def foo(bar, spam='eggs', foobarred={}):
... foobarred[bar] = spam
... print foobarred
...
>>> documented = add_docs(foo)
>>> help(documented)
Help on function foo:
foo(bar, spam='eggs', foobarred={})
Showing help for foo()
>>> documented('monty', 'python')
{'monty': 'python'}
>>> documented('Eric', 'Idle')
{'Eric': 'Idle', 'monty': 'python'}
整个_Default
舞蹈需要保留可变的默认值,虽然这通常是一个坏主意,但确实需要继续按原定的方式工作。建造的立面将像原始一样看起来,并且会像它一样,但是变体仍然存在于“正确”的位置。
请注意,立面会尽可能地更新以匹配原件;通过使用functools.update_wrapper
,各种元数据将从原始元素复制到外观,但我们会小心地从中排除__doc__
字符串,因为我们的外观明确地使用了它自己的文档字符串。