Reputation: 29495
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,
Upvotes: 3
Views: 773
Reputation: 6225
'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.
Upvotes: 1
Reputation: 129119
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.
Upvotes: 9