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,

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you may have meant "Yes, it is already a global." rather than "No."
@ninjagecko: I'll just get rid of the yes/no at the beginning.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.