Search code examples
pythonconfigconfiguration-filesconfigparser

Using a config file to specify operations to execute in Python


I'm trying to build dynamic operations using a config file, python and ConfigParser. I'm fairly new to Python (2 weeks old) so I'm not sure if this is even possible, which is why I thought I'd ask.

Here's a sample config file:

[General]
Volume File = C:\Users\O\Desktop\Sanjeev\Python\Solution\volume.xlsx
New Variables File = C:\Users\O\Desktop\Sanjeev\Python\Solution\newvar.xlsx
Desired Variable Name = Price,Age
Merging Variables = Category,State
[Operations]
Operation1 = Price*Volume,Revenue
Operation2 = Revenue/Age,Annual Revenue

So here I would use the merging variables to merge the first and second dataset, retaining and possibly aggregating the desired variables. Then, based on the operations specified in the operations section, I would execute and store them in a variable with the same name as the second item in the list.

The reason I want to specify these operations in a config file rather in a python script is because the number and type of these operations will vary. I need to create dynamic code that will be able to parse this option in the config file as if it were code and execute it.

I would like some direction on how to get started.


Solution

  • You can use code introspection using the design pattern "Factory" https://en.wikipedia.org/wiki/Factory_method_pattern if you are familiar with object oriented programming.

    Otherwise, you can look at the eval and the exec functions: https://docs.python.org/3/library/functions.html#eval

    Here is an example of using the eval function:

    >>> first_parameter = 10
    >>> second_parameter = 2
    >>> result = eval("first_parameter * second_parameter")
    >>> result
    20