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
asked Feb 8, 2022 at 22:04
Tushaar
3171 gold badge4 silver badges12 bronze badges
2 Answers 2
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
Sign up to request clarification or add additional context in comments.
1 Comment
Barmar
I recommend adding parentheses around the conditional expressions to make the boundaries clear.
Answer to the first part
if dc != '-1':
sep = '_'
else:
sep = ''
dc = '/'
table_id = table_id + sep + dc + '_stg'
gcp_path = gcp_path + dc + "dt=" + date_folder + "/*.parquet"
I don't know what type of exception you can raise. You could have anything from dc not being a string to gcp path no existing.
answered Feb 8, 2022 at 22:11
cup
8,5584 gold badges25 silver badges48 bronze badges
1 Comment
frederick-douglas-pearce
This looks like the right idea, just missing
/ in front of dt for gcp_path when dc != '-1'lang-py
tryand do the rest after. maybe justgcp_pathdef in try/except, then test some different ways of breaking the string subs to see what exceptions to include?__repr__and/or__str__method that will be printed, including functions, classes, ints, etc. I may pose this as an SO question because I'm curious