Shiva Krishna Bavandla
Shiva Krishna Bavandla

Reputation: 26668

can't access global variable from inside a function in python

Below is my code

global PostgresDatabaseNameSchema
global RedShiftSchemaName

PostgresDatabaseNameSchema = None
RedShiftSchemaName = None

def check_assign_global_values():
    if not PostgresDatabaseNameSchema:
        PostgresDatabaseNameSchema = "Superman"
    if not RedShiftSchemaName:
        RedShiftSchemaName = "Ironman"

check_assign_global_values()

But i am getting an error saying

Traceback (most recent call last):
  File "example.py", line 13, in <module>
    check_assign_global_values()
  File "example.py", line 8, in check_assign_global_values
    if not PostgresDatabaseNameSchema:
UnboundLocalError: local variable 'PostgresDatabaseNameSchema' referenced before assignment

So can't we access or set the global variables from inside a function ?

Upvotes: 5

Views: 24407

Answers (1)

Taku
Taku

Reputation: 33724

global should always be defined inside a function, the reason for this is because it's telling the function that you wanted to use the global variable instead of local ones. You can do so like this:

PostgresDatabaseNameSchema = None
RedShiftSchemaName = None

def check_assign_global_values():
    global PostgresDatabaseNameSchema, RedShiftSchemaName
    if not PostgresDatabaseNameSchema:
        PostgresDatabaseNameSchema = "Superman"
    if not RedShiftSchemaName:
        RedShiftSchemaName = "Ironman"

check_assign_global_values()

You should have some basic understanding of how to use global. There is many other SO questions out there you can search. Such as this question Using global variables in a function other than the one that created them.

Upvotes: 12

Related Questions