自动补全最常利用dir()
函数的输出,它可以被钩住。只需实现一个__dir__()
方法:
def __dir__(self):
res = dir(type(self)) + list(self.__dict__.keys())
res.extend(['dynamic1', 'dynamic2'])
return res
至于在匹配签名的同时包装函数,您需要基于该签名构建一个外观。我已经为 Zope 安全功能做到了这一点:
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__
字符串,因为我们的外观显式使用它自己的文档字符串。