def function()

in src/composer/composer.py [0:0]


def function(fun):
    ''' function combinator: stringify def/lambda code '''
    if getattr(fun, '__name__', '') == '<lambda>':
        exc = str(base64.b64encode(marshal.dumps(fun.__code__)), 'ASCII')
    elif callable(fun):
        try:
            exc = inspect.getsource(fun)
        except OSError:
            raise ComposerError('Invalid argument', fun)
    else:
        exc = fun

    if isinstance(exc, str):
        if exc.startswith('def'):
            # standardize function name
            pattern = re.compile(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(')
            match = pattern.match(exc)
            functionName = match.group(1)

            exc = { 'kind': 'python:3', 'code': exc, 'functionName': functionName }
        else: # lambda
            exc = { 'kind': 'python:3+lambda', 'code': exc }

    if not isinstance(exc, dict) or exc is None:
        raise ComposerError('Invalid argument "function" in "function" combinator', fun)

    return Composition({'type':'function', 'function':{ 'exec': exc }, '.combinator': lambda: combinators['function'] })