A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2009-December/094442.html below:

[Python-Dev] recursive closures - reference cycle

[Python-Dev] recursive closures - reference cycle [Python-Dev] recursive closures - reference cycleAntoine Pitrou solipsis at pitrou.net
Tue Dec 8 15:55:06 CET 2009
Kristján Valur Jónsson <kristjan <at> ccpgames.com> writes:
> 
> The problem with this is that once you have called
> factorial() once, you end up with a recursive cycle.

You don't need a closure to exhibit a reference cycle. A global function is 
enough:

>>> def helper(n):
...  if n:
...   return n*helper(n-1)
...  else:
...   return 1
... 
>>> helper.func_globals['helper'] is helper
True


If you really want to avoid this you can prevent the function from depending
on its outside environment:

>>> from functools import partial
>>> def helper2(rec, n):
...  if n:
...   return n*rec(rec, n-1)
...  else:
...   return 1
... 
>>> factorial = partial(helper2, helper2)
>>> "helper2" in factorial.func.func_globals
True
>>> del helper2
>>> "helper2" in factorial.func.func_globals
False
>>> factorial(3)
6


Regards

Antoine.


More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4