Skip to content
Advertisement

Is it possible to change the attribute value in the enum?

I need to reassign the attribute value in Enum.

from enum import Enum    

class Number(Enum):
    number = "1"
    
Number.number = "2" # AttributeError: cannot reassign member 'number'

I tried to reassign the attribute, but I got:

AttributeError: cannot reassign member ‘number’

Advertisement

Answer

Author’s note: This is a horrible idea.


Let’s just delete the string "1" from Python and replace it with "2"

from ctypes import c_byte
from enum import Enum
from sys import getsizeof


def change_enum_value(old: object, new: object) -> None:
    """
    Assigns contents of new object to old object.
    The size of new and old objection should be identical.

    Args:
        old (Any): Any object
        new (Any): Any object
    Raises:
        ValueError: Size of objects don't match
    Faults:
        Segfault: OOB write on destination
    """
    src_s, des_s = getsizeof(new), getsizeof(old)
    if src_s != des_s:
        raise ValueError("Size of new and old objects don't match")
    src_arr = (c_byte * src_s).from_address(id(new))
    des_arr = (c_byte * des_s).from_address(id(old))
    for index in range(len(des_arr)):
        des_arr[index] = src_arr[index]


class Number(Enum):
    number = "1"


change_enum_value(Number.number.value, "2")
print(Number.number.value)  # 2

You don’t have the "1" anymore, quite literally.

>>> "1"
'2'
>>>

which sure is a tad concerning…

Advertisement