Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legal enum usage in python

Recently I have started to use python3 and found out that there is built-in Enum type and it is possible to use it like it is used in Java, say for singleton creation. I can load a config of my telegram bot like this:

class Config(Enum):

    DATA = 'data'

    def __init__(self, dummy):
        with open('./app/config/data.yml', 'r') as f:
            self.__data = yaml.load(f)

    def __getitem__(self, item):
        """
        May be too expensive, but config should not be mutable
        so it returns a defensive copy for mutable sequences. 
        :param item: requested item
        :return: value of the item
        """
        value = self.__data[item]
        return deepcopy(self.__data[item]) if isinstance(value, (MutableMapping, MutableSequence)) else value

    @property
    def authorized_url(self):
       return '{}/bot{}'.format(self['base_url'], self['token'])

    @property
    def updates_url(self):
       return self.authorized_url + self['endpoints']['get_updates']

    @property
    def send_message_url(self):
       return self.authorized_url + self['endpoints']['send_message']

I assume it appropriate as config is a kind of a singleton, and I don't have to bother with instance creation. It is created automatically during module import and encapsulated inside of the class. So I get everything just out of the box, plus I can define handy methods for aggregation of values.

So I am curious whether it is OK to use enums like this in python? If not, I would like to hear why not.

like image 281
Atomikin Avatar asked Oct 20 '25 02:10

Atomikin


1 Answers

This is not the purpose of enums. This is using a side effect of enums to do something else entirely.

.. and I don't have to bother with instance creation.

Instance creation in this case is one line of code:

my_config = Config()

And the inclusion of this one line would allow the elimination of one line, as this:

from enum import Enum
class Config(Enum):

becomes simply:

class Config():

So this construct actually requires more code to express, and seems to be rather overdone. If I ran across this in a code review I would reject it.

like image 98
Stephen Rauch Avatar answered Oct 21 '25 17:10

Stephen Rauch