2012-08-16 22 views
11

我重构了我的旧代码,并希望根据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个函数,它会看起来很乱,我认为)。

这样做的最佳方式是什么(不包括重复的资源)?是否有可能创建一个普遍的装饰器?

谢谢。

回答

7

我认为,就目前而言,最简单的办法是只创建一个新的参照旧函数对象:

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) 
+0

哦,我怎么能忘记它!谢谢! – vlad 2012-08-16 12:36:50

+1

@vlad - 我已经添加了一个函数,我认为它会自动从模块modinput中将'function_with_underscores'添加到'modadd'中作为'functionWithUnderscores'(但它不会真的与'lambda'函数一起工作,因为它们没有可视名称(AFAIK) – mgilson 2012-08-16 12:42:36

4

您可以将函数对象绑定到另一个名字在你的模块的名字空间,例如:

def funcOld(a): 
    return a 

func_new = funcOld 
5

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

def func_new(a): 
    do_stuff() 

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

由于您的问题听起来很像是弃用或类似的问题,所以我想强烈建议使用装饰器来实现更简洁的代码。事实上,另一个线程中的某个人已经有created this for you