Skip to content

Instantly share code, notes, and snippets.

@mscook
Created September 4, 2014 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mscook/af090514de45d05b5a44 to your computer and use it in GitHub Desktop.
Save mscook/af090514de45d05b5a44 to your computer and use it in GitHub Desktop.
counter decorator
print 80*"="+"\nThe 'counter' decorator\n"+80*"="
def scount(wrapped):
def inner(*args, **kwargs):
inner.counter +=1
return wrapped(*args, **kwargs)
inner.counter = 0
return inner
@scount
def scount_me():
pass
for i in range(4):
scount_me()
print "SCount called %i times" % (scount_me.counter)
@GrahamDumpleton
Copy link

import wrapt

def wscount(wrapped):
    @wrapt.decorator
    def wrapper(wrapped, instance, args, kwargs):
        wrapped.counter +=1
        return wrapped(*args, **kwargs)
    wrapped.counter = 0
    return wrapper(wrapped)

@wscount
def wscount_me():
    pass

for i in range(10):
    wscount_me()
print "WSCount called %i times" % (wscount_me.counter)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment