Created
February 26, 2015 02:57
-
-
Save djm/e991e3147b8a6b811d60 to your computer and use it in GitHub Desktop.
Prefer closures over classes keeping state
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
| # Bad | |
| class Join(object): | |
| """ | |
| >>> join_by_commas = Join(',') | |
| >>> join_by_commas(['o', 'm', 'g']) | |
| 'o,m,g' | |
| """ | |
| def __init__(self, separator=u' '): | |
| self.separator = separator | |
| def __call__(self, values): | |
| return self.separator.join(values) | |
| # Good | |
| def join(separator=u' '): | |
| """ | |
| >>> join_by_commas = join(',') | |
| >>> join_by_commas(['f', 't', 'w']) | |
| 'f,t,w' | |
| """ | |
| def inner_join(values): | |
| return separator.join(values) | |
| return inner_join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment