recursive function: use a global or pass a parameter?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jan 17 05:15:47 EST 2015


Tim wrote:

> I have this type of situation and wonder if I should use a global variable
> outside the recursive function instead of passing the updated parameter
> through.

To a first approximation, the answer to:

"I have a X, should I use a global variable or a parameter?"

is *always* "use a parameter", no matter what X is.

To a second and third approximation, the answer is still "use a parameter".

Good reasons for using global variables are few and far between. Just about
the only good reason for using global variables that I can think of is if
you have one or more settings/preference that get set once at the start of
the program and then apply to the entire program.

Actually, there is one other reason... if your program is a simple script
written in imperative style:

name = "steve"
print "Hello", name
do_this()
do_that()
do_something_else()
print "Good bye", name


sort of thing.



-- 
Steven




More information about the Python-list mailing list