recursive function: use a global or pass a parameter?

Tim jtim.arnold at gmail.com
Fri Jan 16 13:48:41 EST 2015


On Friday, January 16, 2015 at 1:34:51 PM UTC-5, Peter Otten wrote:
>> Tim wrote:
>>> Globals are generally bad as they make code non-reentrant; when two calls of 
> the function run simultaneously the data will be messed up.
>> I recommend that you use a generator:
>> >>> def walk(obj):
> ... if not hasattr(obj, "keys"):
> ... return
> ... if "things" in obj:
> ... yield obj["things"]
> ... for v in obj.values():
> ... yield from walk(v)
> ... 
> >>> d = {'things':1, 'two':{'things':2}}
> >>> set(walk(d))
> {1, 2}
>> In Python before 3.3 you have to replace
>> yield from walk(v)
>> with a loop:
>> for t in walk(v):
> yield t

Ah, a generator, I wouldn't have seen the problem in this way, but with your example, it looks so natural.
thanks,
--Tim


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /