So I have this code below of categories and I will sometimes update it by adding a new category, then I have to manually add that category to the list at the bottom INITIAL_GOAL_CATEGORIES it’d be much easier if this list was automatically updated whenever I create a new dict variable. Is there a way to do this? I export the INITIAL_GOAL_CATEGORIES variable and use it elsewhere so if I can set that variable name to a list of all other variables that’d be great. This file will only contain dicts of categories and the list of all of them at the bottom.
categories.py
# Categories
ART = dict(name='Art', emoji='🎨')
CULINARY = dict(name='Culinary', emoji='🍳')
DIET = dict(name='Diet', emoji='🥗')
DIY = dict(name='DIY', emoji='🔨')
FINANCE = dict(name='Finance', emoji='💰')
FITNESS = dict(name='Fitness', emoji='👟')
GAMING = dict(name='Gaming', emoji='🕹️')
MARTIAL_ARTS = dict(name='Martial Arts', emoji='🥋')
MUSIC = dict(name='Music', emoji='🎵')
RELATIONSHIP = dict(name='Relationship', emoji='💗')
SELF_CARE = dict(name='Self-Care', emoji='🤗')
SELF_IMPROVEMENT = dict(name='Self-Improvement', emoji='✨')
STREAMING = dict(name='Streaming', emoji='⏺️')
TRAVEL = dict(name='Travel', emoji='✈️')
WEIGHT_TRAINING = dict(name='Weight Training', emoji='🏋️')
INITIAL_GOAL_CATEGORIES = [ART, CULINARY, DIET, DIY, FITNESS, GAMING, MARTIAL_ARTS, MUSIC,
RELATIONSHIP, SELF_IMPROVEMENT, SELF_CARE, STREAMING, TRAVEL,
WEIGHT_TRAINING]
>Solution :
If you want to create a list that update itself when you add this kind of global values, here what you need:
# Categories
ART = dict(name='Art', emoji='🎨')
CULINARY = dict(name='Culinary', emoji='🍳')
DIET = dict(name='Diet', emoji='🥗')
DIY = dict(name='DIY', emoji='🔨')
FINANCE = dict(name='Finance', emoji='💰')
FITNESS = dict(name='Fitness', emoji='👟')
GAMING = dict(name='Gaming', emoji='🕹️')
MARTIAL_ARTS = dict(name='Martial Arts', emoji='🥋')
MUSIC = dict(name='Music', emoji='🎵')
RELATIONSHIP = dict(name='Relationship', emoji='💗')
SELF_CARE = dict(name='Self-Care', emoji='🤗')
SELF_IMPROVEMENT = dict(name='Self-Improvement', emoji='✨')
STREAMING = dict(name='Streaming', emoji='⏺️')
TRAVEL = dict(name='Travel', emoji='✈️')
WEIGHT_TRAINING = dict(name='Weight Training', emoji='🏋️')
INITIAL_GOAL_CATEGORIES = [value for name, value in globals().items() if
name.isupper()]
This go through all values in globals() and
check if the name of the value is upper case. If it met the criteria, it is a category and we add it to the categories list.
But as said in comments: a dictionary is better:
# Categories
INITIAL_GOAL_CATEGORIES = {
'Art': {'emoji': '🎨'},
'Culinary': {'emoji': '🍳'},
'Diet': {'emoji': '🥗'},
'DIY': {'emoji': '🔨'},
'Finance': {'emoji': '💰'},
'Fitness': {'emoji': '👟'},
'Gaming': {'emoji': '🕹️'},
'Martial Arts': {'emoji': '🥋'},
'Music': {'emoji': '🎵'},
'Relationship': {'emoji': '💗'},
'Self-Care': {'emoji': '🤗'},
'Self-Improvement': {'emoji': '✨'},
'Streaming': {'emoji': '⏺️'},
'Travel': {'emoji': '✈️'},
'Weight Training': {'emoji': '🏋️'},
}