![]() |
Recursion, with "some_dict={}" function parameter. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Recursion, with "some_dict={}" function parameter. (/thread-20244.html) |
Recursion, with "some_dict={}" function parameter. - MvGulik - Aug-02-2019 I'm not getting some python(3.5.2) behaviour. I got a function def get_links_titles( links_list, titles_dict={}, r=0 ): . (Key-part: titles_dict={} )In it I recall(recursion) it with titles_del = get_links_titles( case_dict['redirlinks'], {}, r=r+1 ) it works as intended. The recursive case start with an empty titles_dict case.But when I don't use the , {} part, and use titles_del = get_links_titles( case_dict['redirlinks'], r=r+1 ) The titles_dict in the recursion case is not empty, but contains the data titles_dict had before the recursive call. (???).Ergo: What Python behaviour rule(s) I'm I missing to make sense of that last case. --- Mmm, seems that titles_dict={} as function parameter is not a good idea based on some similar down the line unsuspected hiccup.So ditched it in the def-part and moved it inside the function. (not needed in def + wip function. re-investigate later.) RE: Recursion, with "some_dict={}" function parameter. - fishhook - Aug-02-2019 Dictionaries are objects that are always passed as links to the original. Never do the following: def get_links_titles( links_list, titles_dict={}, r=0 ): passin this case, you will have only one object titles_dict through all of the function calls. Do like this: def get_links_titles(links_list, titles_dict=None, r=0): titles_dict = titles_dict or {} RE: Recursion, with "some_dict={}" function parameter. - ThomasL - Aug-02-2019 The same is with lists as default arguments https://nikos7am.com/posts/mutable-default-arguments/ RE: Recursion, with "some_dict={}" function parameter. - MvGulik - Aug-02-2019 Aha. Its starting to make more sense to me now. Definitely a subject I need to explore some more (todo). Additional Link definitely going to help with that. (I think I used this ones to my benefit, but without actually realising why or how it worked) Thanks for putting me on the right track. :-) |