+ 2
Python refferncing globals from sallow and deep recurise funtion calls:?
Hi Everyone, I have observed some interesting behavior in python. If you have a non-recursive function, you use variables in the calling frame without needing a global declaration in your called function. if your function is recursive, then you need a a global declaration in the called function to reference variables in the top level calling frame. When exactly does the global declaration become necessary???
12 Respuestas
+ 7
Ruba Kh global is not required always! 🙌
x = [1]
def func():
x.append(1)
func()
func()
print(x)
Output: [1,1,1]
+ 3
Ruba, but that doesn't need to have a global, it can be re-written
def returnx(x):
x+=1
return x
print(returnx(1))
Write your programs with your functions taking inputs from arguments and with your functions returning value rather than setting globals. Avoiding globals is easy once you write your functions as functions rather than named chunks of code.
+ 3
Steven M Thankss 🙌
Really helpful for me as well
+ 3
Steven M, thanks for the pointer to the python patterns book.
+ 2
Steven M, here my code example. i use the global like a class variable.
https://code.sololearn.com/c9xEpKW588s0/
+ 2
Rick, thanks for sharing the code. I am curious, why can't the "mcnt" variable be returned and passed into other functions?
+ 2
I know it probably sounds really nerdy, but I like design patterns, below is a great read on why global variables, in any language, should be avoided. However, if you have no other choice but to use globals, you need to perform a global cleanup by setting them to None.
I also included a book I am reading, Python 3 Patterns, Recipes and Idioms, I am about halfway through it, I highly recommend it. The book talks about things like this, best practices, etc.
https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
https://python-3-patterns-idioms-test.readthedocs.io/en/latest/
+ 1
It doesn't seem to hurt to always have a global statement for the global variables referenced by any function...
+ 1
Generally speaking, global variables are typically bad practice and should be avoided. Do you have an example that you can share?
+ 1
Steven M
Yeah I know that it is not a good practice I am just giving an example that you need a way of accessing the global variables in a function
+ 1
Namit Jain
Yeah you are right thanks for the note
0
I think sometimes global is necessary even without a recursion,
For example
x=1
def returnx():
global x
x+=1
returnx()
print(x)
If you don't use global keyword it will result in an error