Home > other >  What is the best practice to avoid code duplication on this code?
What is the best practice to avoid code duplication on this code?

Time:10-13

I have the following code snippets for a Flask application:

import flask import Flask


app = Flask(__name__)


@app.route('/')
def index():

    # Some code...

    on_heroku = 'DYNO' in os.environ
    if on_heroku:
        # Do something
    else:
        # Do something

    return ("SUCCESS", 200)


def open_browser():
    on_heroku = 'DYNO' in os.environ
    if on_heroku:
        # Do something
    else:
        # Do something


if __name__ == "__main__":
    open_browser()
    app.run(debug=True)

I find the on_heroku = 'DYNO' in os.environ and the checking of the value of on_heroku are written twice in the code.

How can I improve the code (e.g., passing on_heroku as a parameter?) such that the program can still run without problems?

CodePudding user response:

Make it a standalone function:

def check():
    on_heroku = 'DYNO' in os.environ
    if on_heroku:
        # Do something
    else:
        # Do something

def index():
    check()
def open_browser():
    check()

Also you could do the environ check within the if statement instead of assigning.

if 'DYNO' in os.environ:
    ...

Or even just assign it once globally at runtime:

on_heroku = 'DYNO' in os.environ

# then run the rest of the program

CodePudding user response:

My suggestion is to use a configuration class and import the configurations globally and use it as needed. If you have a larger project consider using a library, there are plenty of options for this. (https://www.dynaconf.com/, pydantic-settings)

if you are using pydantic consider using https://pydantic-docs.helpmanual.io/usage/settings/, you could also create a .env file to do local development easily, check the example below.

class Settings(BaseSettings):
    """Application settings."""

    dyno: str = Field(env="DYNO")

    class Config:
        env_file = f".env"


SETTINGS = Settings()

you could now use your settings globally in your application.

  • Related