class StatefulReplace(object):

    def __init__(self, initial_c=0):
        self.c = initial_c

def __call__(self, match):
    self.c += 1
return repl if self.c == 3 else match.group(0)
Python - Function attributes or mutable default values