I have a question regarding globals() in python
My sample code
b=9 def a1(): 'kkk' a1() print globals()
I got output b as global
Since b is global, I am expecting I can modify it anywhere
So I modified my code to
b=9 def a1(): 'kkk' b=100 a1() print globals()
still my globals() says b as 100. Why b inside the function is taken as local value while my globals() says its global?
Note: If I add keyword global b inside the function, it get convert to global.
My question is why b was not getting modified inside the function while globals() declare b as global ?
inside a function, unless you use the keyword global, it is not global variable that is modified. instead,a local variable is created and is destroyed as soon as it is out of scope
Refer Python docs for more information. Copying the text in case URL doesn’t work
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
As your code
b is a local variable in a1(), to use global variable, you should first say that to python and then use it, as follows:
b=9 def a1(): 'kkk' global b b=100 a1() print globals()