dynamiccode-generationpython

Is it possible to generate and execute Python code in a Python script? [Dynamic Python code]


I am working on some reports (counts) and I have to fetch counts for different parameters. Pretty simple but tedious.

A sample query for one parameter :

qCountsEmployee = (
    "select count(*) from %s where EmployeeName is not null"
     % (tablename)
     )
CountsEmployee = execute_query(qCountsEmployee)

Now I have few hundred such parameters!

What I did was : create a list of all the parameters and generate them using a quick Python script and then copy that text and put it in the main script to avoid the tedious lines.

columnList = ['a', 'b', ............'zzzz']

for each in columnList:
   print (
            'q' + each + ' ='
            + '"select count(*) from %s where' + each
            + 'is not null" % (tablename)'
         )
   print each + '   = execute_query(' + 'q' + each + ')'

While this approach works, I was wondering if instead of a separate script to generate lines of code and copy paste into main program, can I generate them in the main script directly and let the script treat them as lines of code? That will make the code much more readable is what I think. Hope I made sense! Thank you...


Solution

  • It would be possible, but is not useful here.

    Just do something like

    columnList = ['a', 'b', ............'zzzz']
    
    results = {}
    for column in columnList:
        query = (
                "select count(*) from " + tablename
                + " where " + column + " is not null"
                )
        result = execute_query(qCountsEmployee)
        results[column] = result
    

    You as well can put all this together in a generator function and do

    def do_counting(column_list):
        for column in column_list:
            query = (
                "select count(*) from " + tablename
                + " where " + column + " is not null"
                )
            result = execute_query(qCountsEmployee)
            yield column, result
    
    result_dict = dict(do_counting(['...']))