-
Notifications
You must be signed in to change notification settings - Fork 461
Make Locale objects immutable and cache them #305
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
08b5113
65575c5
07b824f
0278582
33a9057
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # TODO: This can't live in .util until the circular import of | ||
| # core -> util -> localtime -> win32 -> core is resolved. | ||
|
|
||
|
|
||
| class Memoized(type): | ||
| """ | ||
| Metaclass for memoization based on __init__ args/kwargs. | ||
| """ | ||
|
|
||
| def __new__(mcs, name, bases, dict): | ||
| if "_cache" not in dict: | ||
| dict["_cache"] = {} | ||
| if "_cache_lock" not in dict: | ||
| dict["_cache_lock"] = None | ||
| return type.__new__(mcs, name, bases, dict) | ||
|
|
||
| def __memoized_init__(cls, *args, **kwargs): | ||
| lock = cls._cache_lock | ||
| if hasattr(cls, "_get_memo_key"): | ||
| key = cls._get_memo_key(args, kwargs) | ||
| else: | ||
| key = (args or None, frozenset(kwargs.items()) or None) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe memoization could provide both a metaclass and a base class (using the metaclass), the latter providing a default |
||
|
|
||
| try: | ||
| return cls._cache[key] | ||
| except KeyError: | ||
| try: | ||
| if lock: | ||
| lock.acquire() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't that be outside the |
||
| inst = cls._cache[key] = type.__call__(cls, *args, **kwargs) | ||
| return inst | ||
| finally: | ||
| if lock: | ||
| lock.release() | ||
|
|
||
| __call__ = __memoized_init__ # This aliasing makes tracebacks more understandable. | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should probably document that it assumes the constructor&initializer are pure since the cache-fetch is not locked, you could have two identical memoized instances being constructed.