Renaming of functions with preservation of backward compatibility

后端 未结 4 1619
轻奢々
轻奢々 2021-02-19 15:12

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 refa

4条回答
  •  情话喂你
    2021-02-19 15:37

    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
    

    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
    

    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.

    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)
    

提交回复
热议问题