Jabreal
Jabreal

Reputation: 3

F Strings and Interpolation using a properties file

I have a simple python app and i'm trying to combine bunch of output messages to standardize output to the user. I've created a properties file for this, and it looks similar to the following:

[migration_prepare]
console=The migration prepare phase failed in {stage_name} with error {error}!
email=The migration prepare phase failed while in {stage_name}. Contact support!
slack=The **_prepare_** phase of the migration failed

I created a method to handle fetching messages from a Properties file... similar to:

def get_msg(category, message_key, prop_file_location="messages.properties"):
    """ Get a string from a properties file that is utilized similar to a dictionary and be used in subsequent
    messaging between console, slack and email communications"""
    message = None
    config = ConfigParser()
    try:
        dataset = config.read(prop_file_location)
        if len(dataset) == 0:
            raise ValueError("failed to find property file")
        message = config.get(category, message_key).replace('\\n', '\n')  # if contains newline characters i.e. \n
    except NoOptionError as no:
        print(
            f"Bad option for value {message_key}")
        print(f"{no}")
    except NoSectionError as ns:
        print(
            f"There is no section in the properties file {prop_file_location} that contains category {category}!")
        print(f"{ns}")
    return f"{message}"

The method returns the F string fine, to the calling class. My question is, in the calling class if the string in my properties file contains text {some_value} that is intended to be interpolated by the compiler in the calling class using an F String with curly brackets, why does it return a string literal? The output is literal text, not the interpolated value I expect:

What I get The migration prepare phase failed while in {stage_name} stage. Contact support!

What I would like The migration prepare phase failed while in Reconciliation stage. Contact support!

I would like the output from the method to return the interpolated value. Has anyone done anything like this?

Upvotes: 0

Views: 528

Answers (1)

Lior Cohen
Lior Cohen

Reputation: 5745

I am not sure where you define your stage_name but in order to interpolate in config file you need to use ${stage_name}

Interpolation in f-strings and configParser files are not the same.

Update: added 2 usage examples:

# ${} option using ExtendedInterpolation

from configparser import ConfigParser, ExtendedInterpolation

parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read_string('[example]\n'
                   'x=1\n'
                   'y=${x}')
print(parser['example']['y']) # y = '1'

# another option - %()s

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser()
parser.read_string('[example]\n'
                   'x=1\n'
                   'y=%(x)s')
print(parser['example']['y']) # y = '1' 

Upvotes: 1

Related Questions