Last active
January 15, 2018 10:30
-
-
Save headsrooms/98794aae5cc65cbb8c8169a1574d97f7 to your computer and use it in GitHub Desktop.
Function calling counter extracted from https://github.com/hchasestevens/hchasestevens.github.io/blob/master/notebooks/the-decorators-they-wont-tell-you-about.ipynb?utm_source=hackernewsletter&utm_medium=email&utm_term=code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FunctionHolder(object): | |
| def __init__(self, function): | |
| self.func = function | |
| self.called_count = 0 | |
| def __call__(self, *args, **kwargs): | |
| try: | |
| return self.func(*args, **kwargs) | |
| finally: | |
| self.called_count += 1 | |
| def held(function): | |
| return FunctionHolder(function) | |
| @held | |
| def i_am_counted(): | |
| pass | |
| i_am_counted() | |
| i_am_counted() | |
| i_am_counted() | |
| i_am_counted.called_count | |
| @FunctionHolder | |
| def i_am_also_counted(val): | |
| print(val) | |
| i_am_also_counted('a') | |
| i_am_also_counted('b') | |
| i_am_also_counted.called_count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment