Search code examples
pythonenums

Is there a way to assign enum values from variable in Python?


Here's my problem. At first, I implemented in the code something like this:

class HttpMethod(enum.Enum):
    GET = requests.get
    POST = requests.post
    ...

    def __call__(self, *args, **kwargs):
        return self.value(*args, **kwargs)

But now I want to call session.get instead of requests.get from the following class, but I don't want to make session a global variable to my module.

class HttpPooling:
    def __init__(self, **kwargs):
        self.session = requests.Session()
        retries = Retry(**kwargs)
        self.session.mount("http://", HTTPAdapter(max_retries=retries))
        self.session.mount("https://", HTTPAdapter(max_retries=retries))

I tried many solutions to do obtain such result, but never succeeded, any idea ? I focused my tests on __ignore__ from aenum and __init_subclass__ but I feel like there might be a simplistic way that I can't figure out myself.

Is there a way to do something like this:

    class HttpMethod(enum.Enum):
        pool = HttpPooling()
        GET = pool.session.get
        POST = pool.session.post

2 years later solution:

class Method(IntEnum):
    """This enum represents the HTTP methods supported by the API."""

    GET, POST, PUT, PATCH, DELETE, HEAD = range(6)

    @property
    def func(self) -> Callable[..., Any]:
        """Retrieve the partial function from its enum name.

        Returns:
            function: the function callable if the attribute exists, raises an error otherwise.
        """
        return getattr(requests, self.name.lower())

    def __call__(self, *args, **kwargs) -> requests.Response:
        """Calls the function associated with the enum.

        Returns:
            requests.Response: the result of the function.
        """
        return self.func(*args, **kwargs)

    def __repr__(self) -> str:
        """Returns the representation of the enum.

        Returns:
            str: the representation of the enum.
        """
        return self.func.__repr__()

    def __str__(self) -> str:
        """Returns the string representation of the enum.

        Returns:
            str: the string representation of the enum.
        """
        return self.func.__str__()
    ```

Solution

  • I did finally come to a solution with the package aenum which comes with an __ignore__ field for enums.

    class HttpMethod(Enum):
        POST, GET, PUT, PATH, DELETE = range(1, 6)
    
        __pool = HttpPooling()
        __ignore__ = ("__pool",)
    
        def __repr__(self):
            return self.value.__repr__()
    
        @property
        def value(self):
            return partial(getattr(self.__pool.session, self.name.lower()))
    
        def __call__(self, *args, **kwargs):
            self.value(*args, **kwargs)
    
        @classmethod
        def keys(cls):
            return cls.__members__.keys()