Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a function attribute as python object as well as string

Basically my code looks like this surrounded by some logging:

df_name.to_sql('df_name', engine, index=False)

What I would like to do is to wrap it into a function and use df_name twice:

def df_2_sql(df):
   df.to_sql(f'{df}', engine, index=False)

df_list = [df_table_a, df_table_b, df_table_c]

for df in df_list: 
    df_2_sql(df)

...I've expected f'{df}' to work, but it sadly doesn't. I want to use df_list as as pandas objects as well as part of the table name in the to_sql() function.

I've already tried to use two lists

df_list = [df_table_a, df_table_b, df_table_c]
df_list = ['df_table_a', 'df_table_b', 'df_table_c']

..and a function which expects two arguments, but it doesn't feel right or smart. What am I doing wrong?

like image 786
Christian Avatar asked Mar 25 '26 14:03

Christian


1 Answers

Use a dictionary

It's not a good idea to convert variable names to strings. If you need this functionality, construct a dictionary and feed key-value pairs to your function:

def df_2_sql(df, name):
   df.to_sql(name, engine, index=False)

df_dict = {'df_table_a': df_table_a,
           'df_table_b': df_table_b,
           'df_table_c': df_table_c}

for name, df in df_dict.items():
    df_2_sql(df, name)

If this seems verbose and inefficient, note you must have defined df_table_a, df_table_b, etc earlier in your code somewhere. Just use a dictionary from the very beginning and assign to df_dict['df_table_a'], df_dict['df_table_b'], etc.

like image 63
jpp Avatar answered Mar 28 '26 05:03

jpp