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

左心房为你撑大大i 提交于 2019-12-13 17:16:20

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/42593589/cant-access-global-variable-from-inside-a-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!