Variable in enclosed local scope vs variable in global scope - Python -
hi guys can't figure out why when find_average()
called, total = 20
in global scope being used find_total()
function, instead of total = 10
in enclosing scope? in advance insights , help!
total = 20 def find_total(l): return total def find_length(l): length = len(l) return length def find_average(l): total = 10 return find_total(l) / find_length(l) average = find_average(example_list)
each function has own scope. starts @ functions local, inner scope, goes outwards through enclosing functions until reaches global (module) scope. sequence depends on scope function defined in. stack (calling sequence) not used variable lookup.
in example, each function has inner scope followed outer scope. find_total
, that's <module>.find_total.<locals>
, <module>
. so, whenever find_total
run, total
in local scope, failing, , in global scope. there, total == 20
.
the scope inside find_average
exclusive find_average
. neither global scope, find_total
or find_length
can access it. if want pass inside find_average
find_total
, should via parameter.
alternatively, if find_total
can defined inside find_average
. way, find_total
resolves names searching sequence <module>.find_average.<locals>.find_total.<locals> -> <module>.find_average.<locals> -> <module>
.
total = 20 def find_length(l): length = len(l) return length def find_average(l): total = 10 def find_total(l): return total return find_total(l) / find_length(l) average = find_average(example_list)
this make find_total
inaccessible outside find_average
!
Comments
Post a Comment