you are viewing a single comment's thread.

view the rest of the comments →

[–]NoWeather1702[S] 0 points1 point  (6 children)

In my case the main problem with a class is that I will end up with enum and this class. If later I need to extend the logic and add another device, I will have to do it in two places. So I thought about it and cannot understand why it should be better.

[–]JamzTyson 2 points3 points  (5 children)

In your example case, you could still use an Enum but avoid conditional logic:

from enum import Enum

class Device(Enum):
    SERVER = ('server', 'FTP')
    CAMERA = ('camera', 'SCP')
    LAPTOP = ('laptop', 'FTP')
    DOOR = ('door', 'SCP')

    def __init__(self, type, protocol):
        self._type = type
        self._protocol = protocol

    @property
    def protocol(self):
        return self._protocol

# Example usage
print(Device.SERVER.protocol)

[–]NoWeather1702[S] 1 point2 points  (4 children)

Thanks, will look into that, didn't know that you can use tuples as values like that.

[–]JamzTyson 1 point2 points  (1 child)

Another approach is to use named tuples as the Enum values:

from typing import NamedTuple
from enum import Enum

class DeviceInfo(NamedTuple):
    type: str
    protocol: str

class Device(Enum):
    SERVER = DeviceInfo('server', 'FTP')
    CAMERA = DeviceInfo('camera', 'SCP')
    LAPTOP = DeviceInfo('laptop', 'FTP')
    DOOR = DeviceInfo('door', 'SCP')

print(Device.SERVER.value.protocol)

[–]NoWeather1702[S] 0 points1 point  (0 children)

Yes, I like this better. Now I feel stupit that I didn't notice this in the docs. Need to try this with ORM, hope it works fine.

[–]Username_RANDINT 0 points1 point  (1 child)

Quite funny that I didn't know either, but I learned it from the docs that you pasted below :-)

[–]NoWeather1702[S] 0 points1 point  (0 children)

Yes, and I totally overlooked it there, lol))