Search code examples
pythonconstants

How can I create a list of constants so that if I change the constant in one place it will change everywhere it is referenced?


So I am referencing a number of dates (as strings) throughout my code, and I am worried that in the future if I change this string date in one place I may forget to change it in all the places.

I would like to create some kind of constant, so that when I change it in one place, it changes it everywhere.

For example:

CBOE_INDEX_START_DATES = {
    'v20220101': _dt(2020, 7, 31),
    'v20220505': _dt(2020, 7, 31)}


random = {'v20220101': 'Jason', ... } 


random2 = {'pat': 'v20220101', ...} 

So you can see I reference v20220101 in 3 different places, and lets say I am referencing this in 100 places, but I don't want to type this all out in the example.

How can I create some sort of constant so that when I change it in this constant, it will change everywhere?


Solution

  • I think it would be wise to create a list or dictionary of sorts where you define the name once, and then use that as a reference:

    string_dates = [
        'v20220101',
        'v20220505'
    ]
    
    # OR
    
    string_dates = {
        0: 'v20220101',
        1: 'v20220505'
    }
    
    CBOE_INDEX_START_DATES = {
        string_dates[0]: _dt(2020, 7, 31),
        string_dates[1]: _dt(2020, 7, 31)
    }
    
    
    random = {string_dates[0]: 'Jason', ... } 
    
    
    random2 = {'pat': string_dates[0], ... }