How to Reduce Code Duplication of If-Else Statements in Python from below function. Also, which specific exception can i raise here?
def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
try:
table_id=f"{database}_stg.{table}"
gcp_path = f"gs://{env}/{database}/{table}/"
if dc != '-1':
table_id = table_id + '_' + dc + '_stg'
gcp_path = gcp_path + dc + "/dt=" + date_folder + "/*.parquet"
else:
table_id = table_id + '_stg'
gcp_path = gcp_path + "dt=" + date_folder + "/*.parquet"
except Exception as e:
print(e)
raise
return table_id, gcp_path
>Solution :
def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
try:
table_id=f"{database}_stg.{table}"
gcp_path = f"gs://{env}/{database}/{table}/"
table_id = table_id + '_' + dc + '_stg' if dc != '-1' else table_id + '_stg'
gcp_path = gcp_path + dc + "/dt=" + date_folder + "/*.parquet" if dc != '-1' else gcp_path + "dt=" + date_folder + "/*.parquet"
except Exception as e:
print(e)
raise
return table_id, gcp_path
or in one line
def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
try:
table_id=f"{database}_stg.{table}"
gcp_path = f"gs://{env}/{database}/{table}/"
gcp_path,table_id = (gcp_path + dc + "/dt=" + date_folder + "/*.parquet" , table_id + '_' + dc + '_stg') if dc != '-1' else (gcp_path + "dt=" + date_folder + "/*.parquet",table_id + '_stg')
except Exception as e:
print(e)
raise
return table_id, gcp_path