0

I have code which was written in C# now i need to port it to PYTHON. The C# code has enums which cannot be implemented directly in python

Is there any work around to implement enum in python and creating instance of it, as shown in the c# code below SerialProcessState serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;

Can anyone help me in implementing this stuff in python ?

enum SerialProcessState
    {
        SERIAL_PROCESS_SEARCH_START,
        SERIAL_PROCESS_VERIFY_ELEMENTS,
        SERIAL_PROCESS_DATA,
        SERIAL_PROCESS_SEARCH_END}

    ;
SerialProcessState serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;

enum SerialProcessValue
    {
        SERIAL_PACKET_START = 0xF0,
        SERIAL_PACKET_END = 0xF1,
        SERIAL_PACKET_ESCAPE = 0xF2,
        SERIAL_PACKET_ESCAPE_START = 0x00,
        SERIAL_PACKET_ESCAPE_END = 0x01,
        SERIAL_PACKET_ESCAPE_ESCAPE = 0x02,
        SERIAL_PACKET_ELEMENTS = 0x06}

    ;

private void SerialProcess(byte serialData)
    {
        UInt16 Dummy;

        for (Dummy = 0; Dummy < 63; Dummy++) {
            serialhistory[Dummy] = serialhistory[Dummy + 1];
        }
        serialhistory[63] = serialData;

        if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) {
            serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;
            serialEscaped = false;
        }

        switch (serialProcessState) {
            case SerialProcessState.SERIAL_PROCESS_SEARCH_START:
                if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) {
                    checksum = 0;
                    serialProcessState = SerialProcessState.SERIAL_PROCESS_VERIFY_ELEMENTS;
                }
                break;
  .
  .

}
user2345
  • 537
  • 1
  • 5
  • 22

1 Answers1

0

Using the backported Enum*:

from enum import Enum, IntEnum

class SerialProcessState(Enum):
    search_start = 1
    verify_elements = 2
    data = 3
    search_end = 4

class SerialProcessValue(IntEnum):
    packet_start = 0xF0
    packet_end = 0xF1
    ...

You can then access them as SerialProcessValue.packet_start or SerialProcessState.search_end.

* The package name for the backport is enum34.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • just curious is there any other way to implement, without importing other modules and make it minimalistic – user2345 Jul 30 '15 at 01:08
  • @SaiGanesh: Many other ways -- See the 'related' link above. However, modules are a good thing, don't be afraid of them. :) – Ethan Furman Jul 30 '15 at 02:29
  • how does c# verify and compare the values inside the enum `if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START)` Where `SerialProcessValue` is enum and `serialData` is a varible which contains the serail buffer data, It has to check whether the `serialData` contains any start byte / stop byte in it – user2345 Aug 05 '15 at 13:23