/
_decorators.py
70 lines (52 loc) · 2.32 KB
/
_decorators.py
1
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from google.cloud.aiplatform.helpers import value_converter
from proto.marshal import Marshal
from proto.marshal.rules.struct import ValueRule
from google.protobuf.struct_pb2 import Value
class ConversionValueRule(ValueRule):
def to_python(self, value, *, absent: bool = None):
return super().to_python(value, absent=absent)
def to_proto(self, value):
# Need to check whether value is an instance
# of an enhanced type
if callable(getattr(value, "to_value", None)):
return value.to_value()
else:
return super().to_proto(value)
def _add_methods_to_classes_in_package(pkg):
classes = dict(
[(name, cls) for name, cls in pkg.__dict__.items() if isinstance(cls, type)]
)
for class_name, cls in classes.items():
# Add to_value() method to class with docstring
setattr(cls, "to_value", value_converter.to_value)
cls.to_value.__doc__ = value_converter.to_value.__doc__
# Add from_value() method to class with docstring
setattr(cls, "from_value", _add_from_value_to_class(cls))
cls.from_value.__doc__ = value_converter.from_value.__doc__
# Add from_map() method to class with docstring
setattr(cls, "from_map", _add_from_map_to_class(cls))
cls.from_map.__doc__ = value_converter.from_map.__doc__
def _add_from_value_to_class(cls):
def _from_value(value):
return value_converter.from_value(cls, value)
return _from_value
def _add_from_map_to_class(cls):
def _from_map(map_):
return value_converter.from_map(cls, map_)
return _from_map
marshal = Marshal(name="google.cloud.aiplatform.v1beta1")
marshal.register(Value, ConversionValueRule(marshal=marshal))