cls_utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. def _get_class_default_kwargs(cls, *args, **kwargs):
  15. """
  16. Get default arguments of a class in dict format, if args and
  17. kwargs is specified, it will replace default arguments
  18. """
  19. varnames = cls.__init__.__code__.co_varnames
  20. argcount = cls.__init__.__code__.co_argcount
  21. keys = varnames[:argcount]
  22. assert keys[0] == 'self'
  23. keys = keys[1:]
  24. values = list(cls.__init__.__defaults__)
  25. assert len(values) == len(keys)
  26. if len(args) > 0:
  27. for i, arg in enumerate(args):
  28. values[i] = arg
  29. default_kwargs = dict(zip(keys, values))
  30. if len(kwargs) > 0:
  31. for k, v in kwargs.items():
  32. default_kwargs[k] = v
  33. return default_kwargs