Tushaar
Tushaar

Reputation: 307

How to Reduce redundant code of If-Else Statements in Python

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

Upvotes: 1

Views: 460

Answers (2)

cup
cup

Reputation: 8299

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.

Upvotes: 1

tomerar
tomerar

Reputation: 860


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

Upvotes: 1

Related Questions