3

I've been reading a Python textbook, and I see the following code:

class Database:
# the database implementation
    pass

database = None

def initialize_database():
    global database
    database = Database()

Now, why is there a global declaration inside initialize_database function? We had defined database outside the function, doesn't it make it global already?

Best Regards,

alwbtc
  • 25,815
  • 57
  • 129
  • 182

2 Answers2

9

You can reference a global when it's not declared global in a function, but you can only read it; writing it will create a new local variable hiding the global variable. The global declaration makes it able to write to the global.

icktoofay
  • 122,243
  • 18
  • 242
  • 228
1

'global x' doesn't make x global, it should be read as "from now on in this namespace, treat all references to x as as references to x in a higher namespace."

Remember you're not permanently doing anything to x, your just making x point to something different within a function.

Nathan
  • 5,955
  • 10
  • 44
  • 54