Home > OS >  PYTHON string with variables in Enum
PYTHON string with variables in Enum

Time:06-19

I am trying to do something like this:

class SomeEnum(str, Enum):
    STRING_A = 'This is a string A with variable '   variable
    STRING_B = 'This is a string B with variable '   variable

and use it like a template, for instance:

some_list.append(SomeEnum.STRING_A(variable))

is this even possible in Enums since it defies the purpose of Enums a bit? Or what else would you suggest instead of Enums? Thanks a lot!

CodePudding user response:

I'd say define a __call__ method along with some string formatting

class SomeEnum(str, Enum):
    STRING_A = 'This is a string A with variable %s %s '
    STRING_B = 'This is a string B with variable %s %s'

    def __call__(self, *args):
        return self % args

print(SomeEnum.STRING_A("a", "b"))  # This is a string A with variable a b
print(SomeEnum.STRING_B("c", "d"))  # This is a string B with variable c d

The only rule : provide the same amount of paramater, as the string expects


Dynamic formatting

class SomeEnum(str, Enum):
    STRING_A = 'This is a string A with variable '
    STRING_B = 'This is a string B with variable '

    def __call__(self, *args):
        if len(args) == 1:
            return self   args[0]
        return self   ', '.join(args[:-1])   " and "   args[-1]


print(SomeEnum.STRING_A("a"))            # This is a string A with variable a
print(SomeEnum.STRING_B("a", "b"))       # This is a string B with variable a and b
print(SomeEnum.STRING_B("a", "b", "c"))  # This is a string B with variable a, b and c

CodePudding user response:

No!. You can't do like that. It is not practical. The code you're writing cannot see intellisense. If you want to see it in public, then you can use self.

class SomeEnum:

    def __init__(self, enum):
        self.Enum = enum
        self.STRING_A = f'This is a string A with variable {enum}'
        self.STRING_B = f'This is a string B with variable {enum}'


num = 6

p1 = SomeEnum(num)

print(p1.STRING_A)
print(p1.STRING_B)
  • Related