4

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 ?

Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313
  • 2
    Possible duplicate of [Using global variables in a function other than the one that created them](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – parsethis Mar 04 '17 at 08:07

1 Answers1

11

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.

Community
  • 1
  • 1
Taku
  • 31,927
  • 11
  • 74
  • 85