mapper.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:funcmap 作者: AKuederle 项目源码 文件源码
def map(self, regex):
        """Decorate a function to map it to a regex expression.

        Decorator that allows to map a Python function to a regex expression provided as argument. The regex expression
        is parsed using the 're' module (https://docs.python.org/3/library/re.html). Therefore, all regex syntax that
        this module supports is also supported by this regex matcher. To encapsulate arguments for the function in the
        regex expression use named capture groups (see examples).

        Inspired by the URL mapping of the Flask microframework (http://flask.pocoo.org/)

        Args:
            regex: An Python raw string (r'I am a raw string') that can be interpreted as regular expression

        Returns:
            func: The input function without modfication

        Example:
            The simplest case just maps a function to a name:

                >>> mapper = FuncMapper()
                >>> @mapper.map(r'a name')
                ... def my_func():
                ...    return 'I, my_func, have been called'
                >>> mapper('a name')
                'I, my_func, have been called'

            But you can also use variables by adding regex capture groups:
            (Note: Only named match groups are supported!)

                >>> mapper = FuncMapper()
                >>> @mapper.map(r'(?P<first>\d+)\+(?P<second>\d+)')
                ... def adder(first, second):
                ...    return '{} + {} = {}'.format(first, second, int(first) + int(second))
                >>> mapper('3+5')
                '3 + 5 = 8'
        """

        def wrapper(f):
            self._mapped_functions[regex] = f
            compiled_regex = re.compile(regex)
            if compiled_regex.groups > 0 and len(compiled_regex.groupindex) < compiled_regex.groups:
                raise NotSupportedError("Only named matched groups are Supported!")
            self._mapped_regex[regex] = compiled_regex
            return f

        return wrapper
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号