Use this object when you need to evaluate an expression and to capture the value for some later use. This is particularly useful in conditional expressions, as shown below.
>>> import re >>> regexp = re.compile(r"^Hello (\w+)!$")>>> good_match = capture() >>> if good_match(regexp.match("Hello World!")) is not None: ... name = good_match.group(1) ... print name World>>> if good_match(regexp.match("Hello World !!!")) is not None: ... name = good_match.group(1) ... print name
Bases: object
A proxy object for capturing value of the most recent expression with which an instance is called. The call itself sets the object to the expression’s value and returns this value. Subsequent attribute and method lookups get passed on to the value of the expression. Calling the object with no arguments retrieves the last value it was set with. Note that Python built-in operations, e.g. len(), do not get proxied.
>>> m = capture()
>>> m() is None
True
>>> m(list(xrange(5)))
[0, 1, 2, 3, 4]
>>> m.append('a')
>>> m()
[0, 1, 2, 3, 4, 'a']
>>> m.pop()
'a'
>>> m()
[0, 1, 2, 3, 4]
>>> m(set())
set([])
>>> m.add('b')
>>> m()
set(['b'])
>>> len(m)
Traceback (most recent call last):
...
TypeError: object of type 'capture' has no len()