Home > Back-end >  How to fine tune the redundant code in python
How to fine tune the redundant code in python

Time:01-31

I am trying to create two set of databases every time inside my python script for the same of which I have written the below set of code which looks redundant to me since I am initializing the variable ext 2 times and hence if anyone can suggest some better alternatives, that would be really helpful.

def create_datasets(database, ext):
    try:
        dataset = "bq --location=US mk -d "   database   ext

        try:
            return_cd, out, err = run_sys_command(dataset)

        except Exception as e:
            print(e)

    except Exception as e:
        print(e)
        raise

ext = ''
create_datasets(database, ext)
ext = '_stg'
create_datasets(database, ext)

CodePudding user response:

Use a loop?

for ext in ['', '_stg']:
    create_datasets(database, ext)

About your function:

def create_datasets(database, ext):
    try:
        dataset = f"bq --location=US mk -d {database}{ext}"
        return_cd, out, err = run_sys_command(dataset)
    except Exception as e:  # <- you should catch sub exception!
        print(e)

CodePudding user response:

Any exception Exception raised in your function is caught and handled by the inner try block. The outer therefore seems redundant.

def create_datasets(database, ext):
    try:
        dataset = "bq --location=US mk -d "   database   ext
        return_cd, out, err = run_sys_command(dataset)
    except Exception as e:
        print(e)
  •  Tags:  
  • Related