Enum in micropython - alternative?

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
martynwheeler
Posts: 8
Joined: Thu Jan 28, 2021 10:36 pm

Enum in micropython - alternative?

Post by martynwheeler » Fri Jan 29, 2021 10:41 pm

Hi,

Is there a way to handle enum classes in micropython?

I am porting a library which has an enum class.

Code: Select all

class ModemConfig(Enum):
    Bw125Cr45Sf128 = (0x72, 0x74, 0x04)
    Bw500Cr45Sf128 = (0x92, 0x74, 0x04)
    Bw31_25Cr48Sf512 = (0x48, 0x94, 0x04)
    Bw125Cr48Sf4096 = (0x78, 0xc4, 0x0c)
I guess I could replace with an if elif but was wondering if there was a neater way?

Thank you

Martyn

Sent from my LLD-L31 using Tapatalk

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: Enum in micropython - alternative?

Post by stijn » Sat Jan 30, 2021 7:42 am

How do you use it? I mean if you just erase the (Enum) part he class itself will work fine, right?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Enum in micropython - alternative?

Post by pythoncoder » Sat Jan 30, 2021 8:45 am

The enum.Enum class is part of the CPython library but not the MicroPython one.
Peter Hinch
Index to my micropython libraries.

martynwheeler
Posts: 8
Joined: Thu Jan 28, 2021 10:36 pm

Re: Enum in micropython - alternative?

Post by martynwheeler » Sat Jan 30, 2021 10:09 am

Hi,

It is used a little later on to access values from the tuple by

Code: Select all

        # set modem config (Bw125Cr45Sf128)
        self._spi_write(REG_1D_MODEM_CONFIG1, self._modem_config.value[0])
        self._spi_write(REG_1E_MODEM_CONFIG2, self._modem_config.value[1])
        self._spi_write(REG_26_MODEM_CONFIG3, self._modem_config.value[2])
I am not sure, but does this guarantee the order of values to always be the same?

Thanks

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: Enum in micropython - alternative?

Post by stijn » Sat Jan 30, 2021 5:14 pm

Which values? The Bw125Cr45Sf128 etc values are tuples, they have a fixed order. Not sure why you'd even need an enum for this. Might as well use a dict mapping strings to tuple or so. But looking at this piece of code, it doesn't show why you'd need the different constants - especially not because the comment says it's doing something for Bw125Cr45Sf128 but it doesn't reference that fact by accessing ModemConfig.Bw125Cr45Sf128. tldr; many alternatives, but without seeing how it's supposed to be used it's hard to tell what fits best.

martynwheeler
Posts: 8
Joined: Thu Jan 28, 2021 10:36 pm

Re: Enum in micropython - alternative?

Post by martynwheeler » Sat Jan 30, 2021 5:18 pm

Hi,

Thanks for the reply. It seems that enum was not needed and i could just access values from the tuple.

Thanks again

Post Reply