保留向后兼容性的函数重命名

2024-04-29 01:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我重构了我的旧代码,并希望根据pep8更改函数名。但我想保持与系统旧部分的向后兼容性(因为函数名是API的一部分,有些用户使用旧的客户端代码,所以不可能对项目进行完全重构)。

简单示例,旧代码:

def helloFunc(name):
    print 'hello %s' % name

新的:

def hello_func(name):
    print 'hello %s' % name

但这两种功能都应该起作用:

>>hello_func('Alex')
>>'hello Alex'
>>helloFunc('Alf')
>>'hello Alf'

我在想:

def helloFunc(name):
    hello_func(name)

,但我不喜欢它(在项目中大约有50个函数,我想它看起来会很凌乱)。

最好的方法是什么(不包括重复购买)?有可能创造一个通用的装饰器吗?

谢谢。


Tags: 项目函数代码nameapihello系统def
3条回答

虽然其他答案肯定是正确的,但将函数重命名为新名称并创建一个发出警告的旧名称可能会很有用:

def func_new(a):
    do_stuff()

def funcOld(a):
    import warnings
    warnings.warn("funcOld should not be called any longer.")
    return func_new(a)

可以将函数对象绑定到模块命名空间中的另一个名称,例如:

def funcOld(a):
    return a

func_new = funcOld

我认为目前最简单的事情就是创建对旧函数对象的新引用:

def helloFunc():
    pass

hello_func = helloFunc

当然,如果将实际函数的名称更改为hello_func,然后将别名创建为:

helloFunc = hello_func

这仍然有点混乱,因为它不必要地扰乱了模块名称空间。为了解决这个问题,还可以有一个子模块提供这些“别名”。然后,对于您的用户来说,将import module更改为import module.submodule as module非常简单,但您不会使模块名称空间变得混乱。

你甚至可以使用inspect自动地(未经测试的)做类似的事情:

import inspect
import re
def underscore_to_camel(modinput,modadd):
    """
       Find all functions in modinput and add them to modadd.  
       In modadd, all the functions will be converted from name_with_underscore
       to camelCase
    """
    functions = inspect.getmembers(modinput,inspect.isfunction)
    for f in functions:
        camel_name = re.sub(r'_.',lambda x: x.group()[1].upper(),f.__name__)
        setattr(modadd,camel_name,f)

相关问题 更多 >