Ulli Horlacher wrote: > Steven D'Aprano <st...@pearwood.info> wrote: > >> A better and more general test is: >> >> if hasattr(a, 'x'): print('attribute of a') > > Fine! > > I have now: > > def a(x=None): > if not hasattr(a,'x'): a.x = 0 > a.x += 1 > print('%d:' % a.x,x) > > This simply counts the calls of a() > > But, when I rename the function I have to rename the attribute also. > Is it possible to refer the attribute automatically to its function? > Something like: > > def a(x=None): > if not hasattr(_function_,'x'): _function_.x = 0 > _function_.x += 1 > print('%d:' % _function_.x,x)
Not directly, but there are workarounds: def with_function(f): return functools.partial(f, f) @with_function def foo(self, x=None): if not hasattr(self, "x"): self.x = 0 self.x += 1 print("{} called {} times".format(self.__name__, self.x)) -- https://mail.python.org/mailman/listinfo/python-list