0
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.

3
  • Put the global declaration at the top of the function definition, not in each if block Commented Nov 10, 2024 at 17:39
  • Tried that didnt work Commented Nov 10, 2024 at 17:39
  • It works for me. Commented Nov 10, 2024 at 17:40

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.