Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass one variable as another variable in a function in python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading