保留向后兼容性的功能重命名 [英] Renaming of functions with preservation of backward compatibility
问题描述
我重构了我的旧代码,想按照 pep8 更改函数名称.但我想保持与系统旧部分的向后兼容性(无法完全重构项目,因为函数名称是 API 的一部分,并且一些用户使用旧的客户端代码).
I refactor my old code and want to change the names of functions in accordance with pep8. But I want to maintain backward compatibility with old parts of system (a complete refactoring of the project is impossible because function names is a part of the API and some users use the old client code).
简单示例,旧代码:
def helloFunc(name):
print 'hello %s' % name
新:
def hello_func(name):
print 'hello %s' % name
但是这两个函数都应该可以工作:
But both functions should work:
>>hello_func('Alex')
>>'hello Alex'
>>helloFunc('Alf')
>>'hello Alf'
我在考虑:
def helloFunc(name):
hello_func(name)
,但我不喜欢它(在项目中大约有 50 个函数,我认为它看起来会很乱).
, but I do not like it (in project about 50 functions, and it will look a messy, I think).
最好的方法是什么(不包括重复的课程)?是否有可能创建一个通用的装饰器?
What is the best way to do it(excluding duplication ofcource)? Is it possible the creation of a some universal decorator?
谢谢.
推荐答案
我认为目前最简单的方法是创建一个对旧函数对象的新引用:
I think that for the time being, the easiest thing is to just create a new reference to the old function object:
def helloFunc():
pass
hello_func = helloFunc
当然,如果您将实际函数的名称更改为 hello_func
然后将别名创建为:
Of course, it would probably be more slightly more clean if you changed the name of the actual function to hello_func
and then created the alias as:
helloFunc = hello_func
这还是有点乱,因为它不必要地弄乱了你的模块命名空间.为了解决这个问题,您还可以拥有一个提供这些别名"的子模块.然后,对于您的用户来说,就像将 import module
更改为 import module.submodule as module
一样简单,但您不会弄乱您的模块命名空间.
This is still a little messy because it clutters your module namespace unnecessarily. To get around that, you could also have a submodule that provides these "aliases". Then, for your users, it would be as simple as changing import module
to import module.submodule as module
, but you don't clutter your module namespace.
您甚至可以使用 inspect
自动执行这样的操作(未经测试):
You could probably even use inspect
to do something like this automagically (untested):
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)
这篇关于保留向后兼容性的功能重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!