File: patch.py

package info (click to toggle)
codespeak-lib 0.9.1-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,212 kB
  • ctags: 5,409
  • sloc: python: 33,390; ansic: 961; xml: 582; makefile: 90
file content (26 lines) | stat: -rw-r--r-- 868 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

patched = {}

def patch(namespace, name, value):
    """ rebind the 'name' on the 'namespace'  to the 'value',
        possibly and remember the original value. Multiple
        invocations to the same namespace/name pair will
        remember a list of old values.
    """
    nref = (namespace, name)
    orig = getattr(namespace, name)
    patched.setdefault(nref, []).append(orig)
    setattr(namespace, name, value)
    return orig

def revert(namespace, name):
    """ revert to the orginal value the last patch modified.
        Raise ValueError if no such original value exists.
    """
    nref = (namespace, name)
    if nref not in patched or not patched[nref]:
        raise ValueError, "No original value stored for %s.%s" % nref
    current = getattr(namespace, name)
    orig = patched[nref].pop()
    setattr(namespace, name, orig)
    return current