blob: 0819d5b97cbb0ce9e998a71ccc5d8cbb9de320ee [file] [log] [blame]
Matthew Treinish0db53772013-07-26 10:39:35 -04001# Copyright 2011 OpenStack Foundation.
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
Matthew Treinishffa94d62013-09-11 18:09:17 +000016"""Local storage of variables using weak references"""
Matthew Treinish0db53772013-07-26 10:39:35 -040017
Matthew Treinishffa94d62013-09-11 18:09:17 +000018import threading
Matthew Treinish0db53772013-07-26 10:39:35 -040019import weakref
20
Matthew Treinish0db53772013-07-26 10:39:35 -040021
Matthew Treinishffa94d62013-09-11 18:09:17 +000022class WeakLocal(threading.local):
Matthew Treinish0db53772013-07-26 10:39:35 -040023 def __getattribute__(self, attr):
Matthew Treinishffa94d62013-09-11 18:09:17 +000024 rval = super(WeakLocal, self).__getattribute__(attr)
Matthew Treinish0db53772013-07-26 10:39:35 -040025 if rval:
26 # NOTE(mikal): this bit is confusing. What is stored is a weak
27 # reference, not the value itself. We therefore need to lookup
28 # the weak reference and return the inner value here.
29 rval = rval()
30 return rval
31
32 def __setattr__(self, attr, value):
33 value = weakref.ref(value)
Matthew Treinishffa94d62013-09-11 18:09:17 +000034 return super(WeakLocal, self).__setattr__(attr, value)
Matthew Treinish0db53772013-07-26 10:39:35 -040035
36
37# NOTE(mikal): the name "store" should be deprecated in the future
38store = WeakLocal()
39
40# A "weak" store uses weak references and allows an object to fall out of scope
41# when it falls out of scope in the code that uses the thread local storage. A
42# "strong" store will hold a reference to the object so that it never falls out
43# of scope.
44weak_store = WeakLocal()
Matthew Treinishffa94d62013-09-11 18:09:17 +000045strong_store = threading.local()