如何使用参数别名在python中实现弃用

前端之家收集整理的这篇文章主要介绍了如何使用参数别名在python中实现弃用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们正在开发一个 python库,并希望改变某些函数中某些函数参数的命名方式.

我们希望保持向后兼容性,因此我们希望找到一种为函数参数创建别名的方法.

这是一个例子:

旧版:

  1. class MyClass(object):
  2. def __init__(self,object_id):
  3. self.id = object_id

新版本:

  1. class MyClass(object):
  2. def __init__(self,id_object):
  3. self.id = id_object

我们如何使类与两种调用方式兼容:

  1. object1 = MyClass(object_id=1234)
  2. object2 = MyClass(id_object=1234)

我当然可以创建这样的东西:

  1. class MyClass(object):
  2. def __init__(self,object_id=None,id_object=None):
  3. if id_object is not None:
  4. self.id = id_object
  5. else:
  6. self.id = object_id

但是,它会改变参数的数量,我们严格要避免这种情况.

有没有办法声明方法别名或参数别名?

解决方法

你可以写一个装饰者:
  1. import functools
  2. import warnings
  3.  
  4. def deprecated_alias(**aliases):
  5. def deco(f):
  6. @functools.wraps(f)
  7. def wrapper(*args,**kwargs):
  8. rename_kwargs(f.__name__,kwargs,aliases)
  9. return f(*args,**kwargs)
  10. return wrapper
  11. return deco
  12.  
  13. def rename_kwargs(func_name,aliases):
  14. for alias,new in aliases.items():
  15. if alias in kwargs:
  16. if new in kwargs:
  17. raise TypeError('{} received both {} and {}'.format(
  18. func_name,alias,new))
  19. warnings.warn('{} is deprecated; use {}'.format(alias,new),DeprecationWarning)
  20. kwargs[new] = kwargs.pop(alias)
  21.  
  22. class MyClass(object):
  23. @deprecated_alias(object_id='id_object')
  24. def __init__(self,id_object):
  25. self.id = id_object

或者,由于您使用的是Python 3,因此可以使object_id成为仅限关键字的参数:

  1. import warnings
  2.  
  3. class MyClass(object):
  4. # v Look here
  5. def __init__(self,id_object=None,*,object_id=None):
  6. if id_object is not None and object_id is not None:
  7. raise TypeError("MyClass received both object_id and id_object")
  8. elif id_object is not None:
  9. self.id = id_object
  10. elif object_id is not None:
  11. warnings.warn("object_id is deprecated; use id_object",DeprecationWarning)
  12. self.id = object_id
  13. else:
  14. raise TypeError("MyClass missing id_object argument")

猜你在找的Python相关文章