You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Some utils."""
  16. import inspect
  17. from functools import wraps
  18. def cell_attr_register(fn=None, attrs=None):
  19. """
  20. Cell init attributes register.
  21. Registering the decorator of the built-in operator cell __init__
  22. function will add save all the parameters of __init__ as operator attributes.
  23. Args:
  24. fn (function): __init__ function of cell.
  25. attrs (list(string) | string): attr list.
  26. Returns:
  27. function, original function.
  28. """
  29. def wrap_cell(fn):
  30. @wraps(fn)
  31. def deco(self, *args, **kwargs):
  32. arguments = []
  33. if attrs is None:
  34. bound_args = inspect.signature(fn).bind(self, *args, **kwargs)
  35. arguments = bound_args.arguments
  36. del arguments['self']
  37. arguments = arguments.values()
  38. fn(self, *args, **kwargs)
  39. if attrs is not None:
  40. if isinstance(attrs, list):
  41. for item in attrs:
  42. if not isinstance(item, str):
  43. raise ValueError(f"attr must be a string")
  44. if hasattr(self, item):
  45. arguments.append(getattr(self, item))
  46. elif isinstance(attrs, str):
  47. if hasattr(self, attrs):
  48. arguments = getattr(self, attrs)
  49. else:
  50. raise ValueError(f"attrs must be list or string")
  51. self.cell_init_args = type(self).__name__ + str(arguments)
  52. return deco
  53. if fn is not None:
  54. return wrap_cell(fn)
  55. return wrap_cell