func_register.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. from functools import wraps
  15. from . import logging
  16. class FuncRegister(object):
  17. def __init__(self, register_map):
  18. assert isinstance(register_map, dict)
  19. self._register_map = register_map
  20. def __call__(self, key=None):
  21. """register the decoratored func as key in dict"""
  22. def decorator(func):
  23. actual_key = key if key is not None else func.__name__
  24. self._register_map[actual_key] = func
  25. logging.debug(
  26. f"The func ({func.__name__}) has been registered as key ({actual_key})."
  27. )
  28. @wraps(func)
  29. def wrapper(*args, **kwargs):
  30. return func(*args, **kwargs)
  31. return wrapper
  32. return decorator