My goal is to have two functions with the same implementation but with different docstrings.
大多数用户都会这样做,假设原始函数位于old_module.py:def implementation(arg1, arg2):
"""this is a killer function"""
在new_module.py中from old_module import implementation as _implementation
def implementation(arg1, arg2):
"""a different docstring"""
return _implementation(arg1, arg2)
这是重用功能的最直接的方法。它很容易阅读和理解的意图。
不过,也许你有一个很好的理由来回答你的主要问题:How can I make a deepcopy of a function in Python?
为了保持与Python 2和3兼容,我建议使用函数的特殊__dunder__属性。例如:import types
def copy_func(f, name=None):
'''
return a function with same code, globals, defaults, closure, and
name (or provide a new name)
'''
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
# in case f was given attrs (note this dict is a shallow copy):
fn.__dict__.update(f.__dict__)
return fn
下面是一个使用示例:def main():
from logging import getLogger as _getLogger # pyflakes:ignore, must copy
getLogger = copy_func(_getLogger)
getLogger.__doc__ += '\n This function is from the Std Lib logging module.\n '
assert getLogger.__doc__ is not _getLogger.__doc__
assert getLogger.__doc__ != _getLogger.__doc__
一位评论者说:This can’t work for built‑in functions
我不会为了一个内置函数而这样做。对于用纯Python编写的函数,我没有什么理由这么做,我的怀疑是,如果你这样做,你可能做了非常错误的事情(尽管我在这里可能是错的)。
如果您希望某个函数能像内置函数那样执行操作,并像副本那样重用实现,那么您应该用另一个函数包装该函数,例如:_sum = sum
def sum(iterable, start=0):
"""sum function that works like the regular sum function, but noisy"""
print('calling the sum function')
return _sum(iterable, start)