A common pattern I do on functions is, tip before answering the question, adding an "else
" defeats the purpose of reducing nesting:
def fun(param):
if param is None:
return
return do_something_with_param(param)
This allows me to reduce nesting by exiting out of the function returning None
... Now on a module definition how to "return
" in the module earlier?
Here's an example loosely based on what I'm trying to accomplish:
settings.py:
import os
from dotenv import load_dotenv
PROJECT_NAME = "Default Project Name"
ENV = os.getenv("ENV")
HOST = os.getenv("HOST")
PORT = os.getenv("PORT")
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
raise Exception("Figure out how to exit from the module earlier...")
DATABASE_URL += "?sslmode=disable"
As you can see if the DATABASE_URL
is not provided (or any env variable) I would like to get out of the module and not run the rest of the code, without an else
condition.
The module itself should be able to be imported, without the code that's at the end if the DATABASE_URL
is not found.