globals() scope inside a function

Question:

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 ?

Asked By: syam

||

Answers:

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

Answered By: Max

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.

Answered By: anuragal

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()
Answered By: Serjik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.