Python: Passing argument from top-level function to embedded function

Viewed 64

This is a simplified example. But basically, I have function within a function. I want to pass the argument from the top-level function to the embedded function, but it doesn't work. How do I solve this?

Thank you

def Check(file_name, mh_criticalval):
    test_file=file_name

    def eval_value(excel_sht, excel_col, mh_value):
            if excel_sht.cell(row=i, column=excel_col) > mh_value:
                cell_cny_b=excel_sht.cell(
                    row=i,
                    column=excel_col
                ).value='OK'
 
    eval_value(sht, 9, mh_criticalval)
 
 
Check('test.xlsm',1)
1 Answers

Method 1: De-Nesting

The most obvious method here is to remove the nested functions. Doing this is simple:

def eval_mh(excel_sht, excel_col, mh_value):
    if excel_sht.cell(row=i, column=excel_col)>mh_value:
        cell_cny_b=excel_sht.cell(row=i, column=excel_col).value='OK'
    
def CheckDiag(file_name, mh_criticalval):
    test_file=file_name
    eval_mh(sht, 9, mh_criticalval)
 
CheckDiag('test.xlsm',1)

All we did here was move the inner function out. However, if you still wanted them to be nested, try the following.

Method 2: Local/Global Variable Exploitation

Here, we replace all instances of mh_value with mh_criticalval

def CheckDiag(file_name, mh_criticalval):
    test_file=file_name
    def eval_mh(excel_sht, excel_col):
        if excel_sht.cell(row=i, column=excel_col)>mh_criticalval:
            cell_cny_b=excel_sht.cell(row=i, column=excel_col).value='OK'

    eval_mh(sht, 9)
 
CheckDiag('test.xlsm',1)

Method 3: Why 2 functions?

In this method, we remove the function entirely!

    
def CheckDiag(file_name, mh_criticalval):
    test_file=file_name
    if sht.cell(row=i, column=9)>mh_criticalval:
        cell_cny_b=sht.cell(row=i, column=9).value='OK'

    eval_mh(sht, 9)
 
CheckDiag('test.xlsm',1)
Related