utils.py 1.53 KB
Newer Older
1
# Copyright (c) 2022-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#
# See LICENSE for license information.
"""The utilities for Transformer Engine"""
import inspect
import warnings
from enum import Enum

warnings.simplefilter('default')


class DeprecatedEnum:    # pylint: disable=too-few-public-methods
    """DeprecatedEnum"""

    def __init__(self, enum_cls, msg):
        self.enum_cls = enum_cls
        self.msg = msg

    def __iter__(self):
        return iter(list(self.enum_cls.__members__.values()))

    def __getattr__(self, name):
        if name in self.enum_cls.__members__:
            warnings.warn(self.msg, DeprecationWarning)
            return self.enum_cls.__members__[name]
        raise AttributeError(f"{self.enum_cls} does not contain {name}")


def deprecate_wrapper(obj, msg):
    """Deprecate wrapper"""
    if inspect.isclass(obj):
        if issubclass(obj, Enum):
            return DeprecatedEnum(obj, msg)

        class DeprecatedCls(obj):    # pylint: disable=too-few-public-methods
            """DeprecatedCls"""

            def __init__(self, *args, **kwargs):
                warnings.warn(msg, DeprecationWarning)
                super().__init__(*args, **kwargs)

        return DeprecatedCls

    if inspect.isfunction(obj):

        def deprecated(*args, **kwargs):
            warnings.warn(msg, DeprecationWarning)
            return obj(*args, **kwargs)

        return deprecated

    raise NotImplementedError(
        f"deprecate_cls_wrapper only support Class and Function, but got {type(obj)}.")