Python возвращает оболочку данных определенного типа ⇐ Python
-
Гость
Python возвращает оболочку данных определенного типа
I have the below code
from dataclasses import dataclass from typing import List, Optional, Any from enum import Enum, auto class Type(Enum): Red = auto() Green = auto() Blue = auto() @dataclass class Container: type: Type value: Optional[Any | List[Any]] = None @property def single_value(self) -> Any: return self.value # type: ignore @property def multi_value(self) -> List[Any]: return self.value # type: ignore class Test(): def test(self) -> Container: return Container(Type.Green, 42) # return Container(Type.Red, None) # return Container(Type.Blue, [42, 42, 44]) t = Test() res = t.test() match res.type: case Type.Red: print('perform action for red') case Type.Green: print('perform action for green') print(res.single_value) case Type.Blue: print('perform action for blue') print(res.multi_value) A function test will return a wrapper container object with a given type according to which the value object is populated with a specific data type (in this case None, single value or list).
The caller will have to determine the type first to then be able to fetch the value as the type is the indicator of what the value contains.
This whole approach seems very non Pythonic, is there a better way of writing this code?
Источник: https://stackoverflow.com/questions/781 ... cific-type
I have the below code
from dataclasses import dataclass from typing import List, Optional, Any from enum import Enum, auto class Type(Enum): Red = auto() Green = auto() Blue = auto() @dataclass class Container: type: Type value: Optional[Any | List[Any]] = None @property def single_value(self) -> Any: return self.value # type: ignore @property def multi_value(self) -> List[Any]: return self.value # type: ignore class Test(): def test(self) -> Container: return Container(Type.Green, 42) # return Container(Type.Red, None) # return Container(Type.Blue, [42, 42, 44]) t = Test() res = t.test() match res.type: case Type.Red: print('perform action for red') case Type.Green: print('perform action for green') print(res.single_value) case Type.Blue: print('perform action for blue') print(res.multi_value) A function test will return a wrapper container object with a given type according to which the value object is populated with a specific data type (in this case None, single value or list).
The caller will have to determine the type first to then be able to fetch the value as the type is the indicator of what the value contains.
This whole approach seems very non Pythonic, is there a better way of writing this code?
Источник: https://stackoverflow.com/questions/781 ... cific-type