Say that you have a function that should support some state and behave differently depending on this state. I know two ways to implement this when the state is fully preserved by the function:
- Using Function Attribute
- Using a mutable default
Using a slightly modified version of Felix Klings will answer another question , here is an example function that can be used in re.sub(), so only the third matching regular expression will be replaced:
Function attribute:
def replace(match):
replace.c = getattr(replace, "c", 0) + 1
return repl if replace.c == 3 else match.group(0)
Changeable default value:
def replace(match, c=[0]):
c[0] += 1
return repl if c[0] == 3 else match.group(0)
The first seems to me cleaner, but I saw the second more often. Which is preferable and why?