|
1
|
|
|
''' |
|
2
|
|
|
check_self_class_call - This is a package of self when the validation class is called. |
|
3
|
|
|
Copyright (C) 2019 sosei |
|
4
|
|
|
|
|
5
|
|
|
This program is free software: you can redistribute it and/or modify |
|
6
|
|
|
it under the terms of the GNU Affero General Public License as published |
|
7
|
|
|
by the Free Software Foundation, either version 3 of the License, or |
|
8
|
|
|
(at your option) any later version. |
|
9
|
|
|
|
|
10
|
|
|
This program is distributed in the hope that it will be useful, |
|
11
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
13
|
|
|
GNU Affero General Public License for more details. |
|
14
|
|
|
|
|
15
|
|
|
You should have received a copy of the GNU Affero General Public License |
|
16
|
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>. |
|
17
|
|
|
''' |
|
18
|
|
|
|
|
19
|
|
|
import inspect |
|
20
|
|
|
|
|
21
|
|
|
__all__ = ['check_self_class_call'] |
|
22
|
|
|
|
|
23
|
|
|
class check_self_class_call(object): |
|
24
|
|
|
'''Check the class name pattern of the class instance method called the self.''' |
|
25
|
|
|
def __init__(self, original_class): |
|
26
|
|
|
super().__init__() |
|
27
|
|
|
self.__original_class = original_class |
|
28
|
|
|
def __call__(self, *args, **kwargs): |
|
29
|
|
|
return self.__original_class(*args, **kwargs) |
|
30
|
|
|
def __getattribute__(self, name): |
|
31
|
|
|
if name == '_check_self_class_call__original_class': |
|
32
|
|
|
return object.__getattribute__(self, '_check_self_class_call__original_class') |
|
33
|
|
|
elif name == '_check_self_class_call__class_function_wrapper': |
|
34
|
|
|
return object.__getattribute__(self, '_check_self_class_call__class_function_wrapper') |
|
35
|
|
|
else: |
|
36
|
|
|
original_class = object.__getattribute__(self, '_check_self_class_call__original_class') |
|
37
|
|
|
original_class_attribute = getattr(original_class, name) |
|
38
|
|
|
if inspect.isfunction(original_class_attribute): |
|
39
|
|
|
return self.__class_function_wrapper(original_class_attribute) |
|
40
|
|
|
else: |
|
41
|
|
|
return original_class_attribute |
|
42
|
|
|
def __class_function_wrapper(self, func): |
|
43
|
|
|
def is_self(original_class, first_arg): |
|
44
|
|
|
if isinstance(first_arg, original_class): |
|
45
|
|
|
return True |
|
46
|
|
|
else: |
|
47
|
|
|
return False |
|
48
|
|
|
def wrapper(*args, **kwargs): |
|
49
|
|
|
original_class = self.__original_class |
|
50
|
|
|
first_arg = args[0] |
|
51
|
|
|
if is_self(original_class, first_arg): |
|
52
|
|
|
return func(*args, **kwargs) |
|
53
|
|
|
else: |
|
54
|
|
|
raise TypeError(f"descriptor '{func.__name__}' requires a '{original_class.__name__}' object but received a '{first_arg.__class__.__name__}'") |
|
55
|
|
|
return wrapper |
|
56
|
|
|
|