[Python-3000] A new member for contextlib?
Zaur Shibzoukhov
szport at gmail.com
Fri Apr 4 09:49:30 CEST 2008
I suggest a context manager for property defining/redefining. There is a
prototype and illustrative example:
--------------------------------------------------------------------------------------------------------------
import sys
null = object()
_property = property
class property(_property):
#
def __init__(self, *args, **kw):
_property.__init__(self, *args, **kw)
self.__enter__ = self.__enter
self.__exit__ = self.__exit
#
@classmethod
def __enter__(self):
return null
#
@classmethod
def __exit__(self, type, value, tb):
if tb is None:
frame = sys._getframe(1)
self.__exitHandler(self, frame.f_locals)
#
def __enter(self):
return null
#
def __exit(self, type, value, tb):
if tb is None:
frame = sys._getframe(1)
self.__exitHandler(self, frame.f_locals)
#
@staticmethod
def __exitHandler(self, _locals):
propName = "_"
PropName = str(id(self))
for key, value in _locals.items():
if value is null:
propName = key
PropName = key.capitalize()
break
if type(self) == type(property):
getFunc = _locals.pop('get', None)
setFunc = _locals.pop('set', None)
delFunc = _locals.pop('delete', None)
doc = _locals.pop('doc', None)
else:
getFunc = _locals.pop('get', None) or self.fget
setFunc = _locals.pop('set', None) or self.fset
delFunc = _locals.pop('delete', None) or self.fdel
doc = _locals.pop('doc', None) or self.__doc__
if getFunc:
funcName = "_get"+PropName
getFunc.__name__ = funcName
_locals[funcName] = getFunc
if setFunc:
funcName = "_set"+PropName
setFunc.__name__ = funcName
_locals[funcName] = setFunc
if delFunc:
funcName = "_del"+PropName
delFunc.__name__ = funcName
_locals[funcName] = delFunc
prop = property(getFunc, setFunc, delFunc)
prop.__doc__ = doc
_locals[propName] = prop
-----------------------------------------------------------------------------------------------------------
def testPropertyMaker():
class AAA:
_v = 1
with property as v:
doc = "Example of making property with *with* statement"
def get(self):
return self._v
def set(self, v):
self._v = v
class BBB(AAA):
with AAA.v as v:
doc = "Example of modified property"
def get(self):
return [self._v]
a=AAA()
a.v = 10
print(a.v)
print(AAA.v.__doc__)
b=BBB()
b.v = 100
print(b.v)
print(BBB.v.__doc__)
This code is also in attachment.
Is it suitable for contextlib.py?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20080404/61e5bb44/attachment.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: withProperty.py
Type: text/x-python
Size: 2725 bytes
Desc: not available
Url : http://mail.python.org/pipermail/python-3000/attachments/20080404/61e5bb44/attachment.py
More information about the Python-3000
mailing list