point_to_managedDB = None
def _get_correct_DB_flag():
if ENV == "dev":
global point_to_managedDB
point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_DEV")
elif ENV == "stg":
global point_to_managedDB
point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_STG")
elif ENV == "prod":
global point_to_managedDB
point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_PROD")
_get_correct_DB_flag()
Whats wrong in this code? Im getting :
File "/oia_application/scripts/database/env/sql_environments.py",
line 37
global point_to_managedDB
^
SyntaxError: name 'point_to_managedDB' is assigned to before global declaration
I know there are similar issue asked in SO but I whats wrong in my code I cant figure out. I've declared global inside the method only.
The error is because the global
declaration in the elif
block is after the assignment in the if
block. You can't have a global
declaration for a variable that's used earlier in the function. The documentation says:
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
It doesn't matter whether the if
block is executed or not; this is a compile-time declaration, not an executable statement.
You should just have one global
declaration for the variable before all the uses:
def _get_correct_DB_flag():
global point_to_managedDB
if ENV == "dev":
point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_DEV")
elif ENV == "stg":
point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_STG")
elif ENV == "prod":
point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_PROD")