Python, Recursive Functions and Returns
So, I found out the other other day that if you want to have a value returned when using a recursive function you must include the return line in each instance of the return. Example:
Incorrect way:
def cleanMyString(self, url):
returnURL = ''
if ':' in str(url.encode('utf-8')):
fixMe = url.replace(':', '_')
self.clean(fixMe)
elif '$' in str(url.encode('utf-8')):
fixMe = url.replace('$', '-')
self.clean(fixMe)
else:
returnURL = url
return returnURL
The result of this method is None unless the string did not match any of the conditions to re-curse.
Correct way:
def cleanMyString(self, url):
returnURL = ''
if ':' in str(url.encode('utf-8')):
fixMe = url.replace(':', '_')
return self.clean(fixMe)
elif '$' in str(url.encode('utf-8')):
fixMe = url.replace('$', '-')
return self.clean(fixMe)
else:
returnURL = url
return returnURL
so we can see that instead of calling the function directly we need to put return in front, otherwise we get a return value of None.
Tags: Python, Recursive Functions and Returns
Trackback from your site.