Home > other >  How to pass one variable as another variable in a function in python
How to pass one variable as another variable in a function in python

Time:01-03

I have a SQL variable mem_dep When I am using it directly in variable sql then it is working absolutely fine. It is printing proper SQL statement but when I am passing another variable cat in variable sql with the value "mem_dep" then it is not working fine. It is just printing value of cat

mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
cob = "20223456"
cat = "mem_dep"

Below code is working absolutely fine

def calc():
    sql = mem_dep.format(Business_date = cob)
    print(sql)

Output:

calc() # calling function
SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456' # printing sql

But below code is not working if I am passing variable cat in a function with the same value as variable name mem_dep

def calc(cat):
    sql = cat.format(Business_date = cob)
    print(sql)

Output:

calc(cat) # calling function
mem_dep #printing sql

How can I pass SQL variable as a variable in the function in this case?

I tried below code also but not working

def calc(cat):
    tmp_sql = "{}".format(cat)
    sql = tmp_sql.format(Business_date = cob)
    print(sql)

Output:

calc(cat) # calling function
mem_dep #printing sql

Expected output:

SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456' # printing sql

CodePudding user response:

Thanks!!! I got it resolved by using eval(cat)

answer would be

sql = eval(cat).format(Business_date = cob)

CodePudding user response:

From what I understand cat has the name of the SQL variable which contains your SQL string. And you want to access the SQL string from cat without knowing the value of cat. You can use getattr for this purpose and wrap everything in a class like below:

class SQLCalc:
    def __init__(self):
        self.mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
        self.cob = "20223456"
        self.cat = "mem_dep"

    def calc(self):
        sql = getattr(self, self.cat).format(Business_date = self.cob)
        print(sql)

sql_calc = SQLCalc()
sql_calc.calc()

CodePudding user response:

for this output

SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456'

You have to give mem_dep as an argument in the calc()

calc(mem_dep)

CodePudding user response:

Maybe like this:

mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
cob = "20223456" 

def calc(sql_template, buisness_date): 
    return sql_template.format(Business_date = buisness_date)
    
mem_dep_result = calc(mem_dep, cob)
print(mem_dep_result)
  • Related