0

I need to configure a script with a command line switch and/or environment variable (-> string) to a list of enums in order to define a selection of already existing enums. I found the following to work:

from enum import Enum

class Provider(Enum):
    NONE = 0, ''
    Amazon = 40, 'Amazon'
    Netflix = 42, 'Netflix'
    SkyTicket = 104, 'Sky Ticket'
    AmazonChannels = 140, 'Amazon Channels'
    Disney = 176, 'Disney+'

    def __new__(cls, value, name):
        member = object.__new__(cls)
        member._value_ = value
        member.fullname = name
        return member

    def __int__(self):
        return self.value

    def __str__(self):
        return self.fullname

providers = []
#input from cli option
test = "Amazon, Disney"

#create [Provider.Amazon, Provider.Disney] 
for t in test.split(','):
    providers.append(Provider[t.strip()])
 
print(providers)
#[<Provider.Amazon: 40>, <Provider.Disney: 176>]

I would prefer a more direct input string like "Provider.Amazon, Provider.Netfilx" Any idea?

Or even a better way from cli option (argparse) to enum list?

Josef
  • 232
  • 3
  • 12
  • If it's a command line, you wouldn't normally expect commas, they would already be split. You are relying on the user to make an exact match to your enum -- might want to have a lookup function, maybe use upper() in addition to strip so you can make the enum constants capitalized (pep8). Do you need an enum and an ID number? You're packing a lot of info in that provider. Maybe it should be a class? I think I'm rambling because you asked a bunch of different questions. – Kenny Ostrom Aug 21 '21 at 16:46
  • The ID number will be used in a http get request as parameter. The name is just a nice add-on, but the addition of extra data is also described in the Enum documentation, so should be okay. I'm just looking for a clean solution for the user to define his selection of providers in a cli option and environment variable. Handing over the string works, but it's maybe not pythonic. ;-) – Josef Aug 21 '21 at 17:44
  • I'd be happy to post an answer to any one specific question that isn't opinion based. This feels more like a code review question https://codereview.stackexchange.com/ except you can't post there yet because you haven't done any of the work you plan to do (argparse, environment variables, etc). – Kenny Ostrom Aug 21 '21 at 17:58
  • Where would the "more direct input string" be used? On the command line? As a user I would rather type in "Netflix" than "Provider.Netflix". – Ethan Furman Aug 21 '21 at 18:42
  • `argparse` lets you specify a list of choices, which you can easily convert to `enums` or other id. – hpaulj Aug 21 '21 at 23:10
  • But not a list of choices, right? – Josef Aug 22 '21 at 08:43

0 Answers0