[Python-ideas] Decorators for variables
Matthias welp
boekewurm at gmail.com
Fri Apr 1 13:14:41 EDT 2016
> An example of the transformation would help here
An example, that detects cycles in a graph, and doesn't do an update if
the graph has cycles.
class prevent_cycles(property):
"""
This uses nodes that point to only one other node: if there is a
cycle
in the current subgraph, it will detect that within O(n)
"""
def __init__(self, value):
super().__init__()
self._value = None
self.__set__(value)
def getter(self):
return self._value
def setter(self, value):
if not turtle_and_hare(value):
self._value = value
else:
raise Exception("cycle detected, shutting down")
def deleter(self):
del self._value
def turtle_and_hare(self, other):
"""
Generic turtle and hare implementation. true if cycle, false if
not.
Returns True if cyclic from this point, false if it is not.
"""
turtle = other
hare = other
fieldname = self.__name__
# this assuming that properties have access to their name, but that
# would also be the same as a function.
while True:
if hare is None:
return False
hare = getattr(hare, fieldname)
if hare is None:
return False
if hare is turtle:
return True
hare = getattr(hare, fieldname)
turtle = getattr(turtle, fieldname)
if hare is turtle:
return True
class A(object):
def __init__(self, parent):
@prevent_cycles
self.parent = parent
This would prevent cycles from being created in this object A, and would
make
some highly reusable code. The same can be done for @not_none, etc, to
prevent
some states which may be unwanted.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160401/d36df48d/attachment.html>
More information about the Python-ideas
mailing list