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
  • 28,057
  • 62
  • 134
  • 188

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
  • 126,289
  • 21
  • 250
  • 231
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
  • 6,095
  • 10
  • 45
  • 54