Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create enum using other property name's value

how can I create enum class that its property use the value from other member? Like my following code

from enum import Enum
class ProjectPath(Enum):
    home = '~/home'
    app = '~/home/app'
    prefix = '~/home/app/prefix'
    postfix = '~/home/app/postfix'

'''
try to do something like
from enum import Enum
class ProjectPath(Enum):
    home = '~/home'
    app = f'{self.home.value}/app'
    prefix = f'{self.app.value}/prefix'
    postfix = f'{self.app.value}/postfix'
'''
like image 853
jacobcan118 Avatar asked Nov 22 '25 15:11

jacobcan118


2 Answers

Just use:

class ProjectPath(Enum):
    home = '~/home'
    app = f'{home}/app'
    prefix = f'{app}/prefix'
    postfix = f'{app}/postfix'
like image 116
shayan rok rok Avatar answered Nov 25 '25 11:11

shayan rok rok


Dont try to refer to the variables inside as an enum, just uses them like local variables.

from enum import Enum


class ProjectPath(Enum):
    home = '~/home'
    app = f'{home}/app'
    prefix = f'{app}/prefix'
    postfix = f'{app}/postfix'


print(*[f"{var=}" for var in ProjectPath], sep="\n")

Output

var=<ProjectPath.home: '~/home'>
var=<ProjectPath.app: '~/home/app'>
var=<ProjectPath.prefix: '~/home/app/prefix'>
var=<ProjectPath.postfix: '~/home/app/postfix'>
like image 30
Chris Doyle Avatar answered Nov 25 '25 11:11

Chris Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!