Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
overrides.py249 linesDownload Raw Back to overrides
1#2#  Copyright 2019 Mikko Korpela3#4#  Licensed under the Apache License, Version 2.0 (the "License");5#  you may not use this file except in compliance with the License.6#  You may obtain a copy of the License at7#8#      http://www.apache.org/licenses/LICENSE-2.09#10#  Unless required by applicable law or agreed to in writing, software11#  distributed under the License is distributed on an "AS IS" BASIS,12#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13#  See the License for the specific language governing permissions and14#  limitations under the License.15#16 17import dis18import functools19import inspect20import sys21from types import FrameType, FunctionType22from typing import Callable, List, Optional, Tuple, TypeVar, Union, overload23 24__VERSION__ = "7.7.0"25 26from overrides.signature import ensure_signature_is_compatible27 28_WrappedMethod = TypeVar("_WrappedMethod", bound=Union[FunctionType, Callable])29_DecoratorMethod = Callable[[_WrappedMethod], _WrappedMethod]30 31 32@overload33def overrides(34    method: None = None,35    *,36    check_signature: bool = True,37    check_at_runtime: bool = False,38) -> _DecoratorMethod:39    ...40 41 42@overload43def overrides(44    method: _WrappedMethod,45    *,46    check_signature: bool = True,47    check_at_runtime: bool = False,48) -> _WrappedMethod:49    ...50 51 52def overrides(53    method: Optional[_WrappedMethod] = None,54    *,55    check_signature: bool = True,56    check_at_runtime: bool = False,57) -> Union[_DecoratorMethod, _WrappedMethod]:58    """Decorator to indicate that the decorated method overrides a method in59    superclass.60    The decorator code is executed while loading class. Using this method61    should have minimal runtime performance implications.62 63    How to use:64    from overrides import overrides65 66    class SuperClass(object):67        def method(self):68          return 269 70    class SubClass(SuperClass):71 72        @overrides73        def method(self):74            return 175 76    :param check_signature: Whether or not to check the signature of the overridden method.77    :param check_at_runtime: Whether or not to check the overridden method at runtime.78    :raises AssertionError: if no match in super classes for the method name79    :return: method with possibly added (if the method doesn't have one)80        docstring from super class81    """82    if method is not None:83        return _overrides(method, check_signature, check_at_runtime)84    else:85        return functools.partial(86            overrides,87            check_signature=check_signature,88            check_at_runtime=check_at_runtime,89        )90 91 92@overload93def override(94    method: None = None,95    *,96    check_signature: bool = True,97    check_at_runtime: bool = False,98) -> _DecoratorMethod:99    ...100 101 102@overload103def override(104    method: _WrappedMethod,105    *,106    check_signature: bool = True,107    check_at_runtime: bool = False,108) -> _WrappedMethod:109    ...110 111 112def override(113    method: Optional[_WrappedMethod] = None,114    *,115    check_signature: bool = True,116    check_at_runtime: bool = False,117) -> Union[_DecoratorMethod, _WrappedMethod]:118    """Decorator to indicate that the decorated method overrides a method in119    superclass.120    The decorator code is executed while loading class. Using this method121    should have minimal runtime performance implications.122 123    How to use:124    from overrides import override125 126    class SuperClass(object):127        def method(self):128          return 2129 130    class SubClass(SuperClass):131 132        @override133        def method(self):134            return 1135 136    :param check_signature: Whether or not to check the signature of the overridden method.137    :param check_at_runtime: Whether or not to check the overridden method at runtime.138    :raises AssertionError: if no match in super classes for the method name139    :return: method with possibly added (if the method doesn't have one)140        docstring from super class141    """142    if method is not None:143        return _overrides(method, check_signature, check_at_runtime)144    else:145        return functools.partial(146            overrides,147            check_signature=check_signature,148            check_at_runtime=check_at_runtime,149        )150 151 152def _overrides(153    method: _WrappedMethod,154    check_signature: bool,155    check_at_runtime: bool,156) -> _WrappedMethod:157    setattr(method, "__override__", True)158    global_vars = getattr(method, "__globals__", None)159    if global_vars is None:160        global_vars = vars(sys.modules[method.__module__])161    for super_class in _get_base_classes(sys._getframe(3), global_vars):162        if hasattr(super_class, method.__name__):163            if check_at_runtime:164 165                @functools.wraps(method)166                def wrapper(*args, **kwargs):167                    _validate_method(method, super_class, check_signature)168                    return method(*args, **kwargs)169 170                return wrapper  # type: ignore171            else:172                _validate_method(method, super_class, check_signature)173                return method174    raise TypeError(f"{method.__qualname__}: No super class method found")175 176 177def _validate_method(method, super_class, check_signature):178    super_method = getattr(super_class, method.__name__)179    is_static = isinstance(180        inspect.getattr_static(super_class, method.__name__), staticmethod181    )182    if getattr(super_method, "__final__", False):183        raise TypeError(f"{method.__name__}: is finalized in {super_class}")184    if not method.__doc__:185        method.__doc__ = super_method.__doc__186    if (187        check_signature188        and not method.__name__.startswith("__")189        and not isinstance(super_method, property)190    ):191        ensure_signature_is_compatible(super_method, method, is_static)192 193 194def _get_base_classes(frame, namespace):195    return [196        _get_base_class(class_name_components, namespace)197        for class_name_components in _get_base_class_names(frame)198    ]199 200 201def _get_base_class_names(frame: FrameType) -> List[List[str]]:202    """Get baseclass names from the code object"""203    current_item: List[str] = []204    items: List[List[str]] = []205    add_last_step = True206 207    for instruction in dis.get_instructions(frame.f_code):208        if instruction.offset > frame.f_lasti:209            break210        if instruction.opcode not in dis.hasname:211            continue212        if not add_last_step:213            items = []214            add_last_step = True215 216        # Combine LOAD_NAME and LOAD_GLOBAL as they have similar functionality217        if instruction.opname in ["LOAD_NAME", "LOAD_GLOBAL"]:218            if current_item:219                items.append(current_item)220            current_item = [instruction.argval]221 222        elif instruction.opname == "LOAD_ATTR" and current_item:223            current_item.append(instruction.argval)224 225        # Reset on other instructions226        else:227            if current_item:228                items.append(current_item)229            current_item = []230            add_last_step = False231 232    if current_item:233        items.append(current_item)234    return items235 236 237def _get_base_class(components, namespace):238    try:239        obj = namespace[components[0]]240    except KeyError:241        if isinstance(namespace["__builtins__"], dict):242            obj = namespace["__builtins__"][components[0]]243        else:244            obj = getattr(namespace["__builtins__"], components[0])245    for component in components[1:]:246        if hasattr(obj, component):247            obj = getattr(obj, component)248    return obj249 
codekingpro/portable-devtools · Team Ai