~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lazy_regex.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-05 14:12:23 UTC
  • mto: This revision was merged to the branch mainline in revision 6348.
  • Revision ID: jelmer@samba.org-20111205141223-8qxae4h37satlzgq
Move more functionality to vf_search.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Lazily compiled regex objects.
18
18
 
19
 
This module defines a class which creates proxy objects for regex compilation.
20
 
This allows overriding re.compile() to return lazily compiled objects.
 
19
This module defines a class which creates proxy objects for regex
 
20
compilation.  This allows overriding re.compile() to return lazily compiled
 
21
objects.  
 
22
 
 
23
We do this rather than just providing a new interface so that it will also
 
24
be used by existing Python modules that create regexs.
21
25
"""
22
26
 
23
27
import re
24
28
 
 
29
from bzrlib import errors
 
30
 
25
31
 
26
32
class LazyRegex(object):
27
33
    """A proxy around a real regex, which won't be compiled until accessed."""
42
48
    def __init__(self, args=(), kwargs={}):
43
49
        """Create a new proxy object, passing in the args to pass to re.compile
44
50
 
45
 
        :param args: The *args to pass to re.compile
46
 
        :param kwargs: The **kwargs to pass to re.compile
 
51
        :param args: The `*args` to pass to re.compile
 
52
        :param kwargs: The `**kwargs` to pass to re.compile
47
53
        """
48
54
        self._real_regex = None
49
55
        self._regex_args = args
58
64
 
59
65
    def _real_re_compile(self, *args, **kwargs):
60
66
        """Thunk over to the original re.compile"""
61
 
        return _real_re_compile(*args, **kwargs)
 
67
        try:
 
68
            return _real_re_compile(*args, **kwargs)
 
69
        except re.error, e:
 
70
            # raise InvalidPattern instead of re.error as this gives a
 
71
            # cleaner message to the user.
 
72
            raise errors.InvalidPattern('"' + args[0] + '" ' +str(e))
 
73
 
 
74
    def __getstate__(self):
 
75
        """Return the state to use when pickling."""
 
76
        return {
 
77
            "args": self._regex_args,
 
78
            "kwargs": self._regex_kwargs,
 
79
            }
 
80
 
 
81
    def __setstate__(self, dict):
 
82
        """Restore from a pickled state."""
 
83
        self._real_regex = None
 
84
        setattr(self, "_regex_args", dict["args"])
 
85
        setattr(self, "_regex_kwargs", dict["kwargs"])
62
86
 
63
87
    def __getattr__(self, attr):
64
88
        """Return a member from the proxied regex object.