| 
 | 1 | +# Licensed to the Software Freedom Conservancy (SFC) under one  | 
 | 2 | +# or more contributor license agreements.  See the NOTICE file  | 
 | 3 | +# distributed with this work for additional information  | 
 | 4 | +# regarding copyright ownership.  The SFC licenses this file  | 
 | 5 | +# to you under the Apache License, Version 2.0 (the  | 
 | 6 | +# "License"); you may not use this file except in compliance  | 
 | 7 | +# with the License.  You may obtain a copy of the License at  | 
 | 8 | +#  | 
 | 9 | +#   http://www.apache.org/licenses/LICENSE-2.0  | 
 | 10 | +#  | 
 | 11 | +# Unless required by applicable law or agreed to in writing,  | 
 | 12 | +# software distributed under the License is distributed on an  | 
 | 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY  | 
 | 14 | +# KIND, either express or implied.  See the License for the  | 
 | 15 | +# specific language governing permissions and limitations  | 
 | 16 | +# under the License.  | 
 | 17 | + | 
 | 18 | +from dataclasses import dataclass  | 
 | 19 | +from dataclasses import fields  | 
 | 20 | +from dataclasses import is_dataclass  | 
 | 21 | + | 
 | 22 | + | 
 | 23 | +@dataclass  | 
 | 24 | +class BidiObject:  | 
 | 25 | +    def to_json(self):  | 
 | 26 | +        json = {}  | 
 | 27 | +        for field in fields(self):  | 
 | 28 | +            key = field.name[1:] if field.name.startswith("_") else field.name  | 
 | 29 | +            value = getattr(self, key)  | 
 | 30 | +            if value is None:  | 
 | 31 | +                continue  | 
 | 32 | +            if is_dataclass(value):  | 
 | 33 | +                value = value.to_json()  | 
 | 34 | +            elif isinstance(value, list):  | 
 | 35 | +                value = [v.to_json() if hasattr(v, "to_json") else v for v in value]  | 
 | 36 | +            elif isinstance(value, dict):  | 
 | 37 | +                value = {k: v.to_json() if hasattr(v, "to_json") else v for k, v in value.items()}  | 
 | 38 | +            json[key] = value  | 
 | 39 | +        return json  | 
 | 40 | + | 
 | 41 | +    @classmethod  | 
 | 42 | +    def from_json(cls, json):  | 
 | 43 | +        return cls(**json)  | 
 | 44 | + | 
 | 45 | + | 
 | 46 | +@dataclass  | 
 | 47 | +class BidiEvent(BidiObject):  | 
 | 48 | +    def __init__(self, *args, **kwargs):  | 
 | 49 | +        super().__init__(*args, **kwargs)  | 
 | 50 | + | 
 | 51 | + | 
 | 52 | +@dataclass  | 
 | 53 | +class BidiCommand(BidiObject):  | 
 | 54 | +    def __init__(self, *args, **kwargs):  | 
 | 55 | +        super().__init__(*args, **kwargs)  | 
 | 56 | + | 
 | 57 | +    def cmd(self):  | 
 | 58 | +        result = yield self.to_json()  | 
 | 59 | +        return result  | 
0 commit comments