3

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
Christian
  • 515
  • 1
  • 6
  • 17
  • You may find [this](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) useful. – shayaan Nov 15 '18 at 15:31

1 Answers1

3

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.

jpp
  • 159,742
  • 34
  • 281
  • 339