Traverses the AST and returns the corresponding CFG

    :param ast_func: The AST representation of function
    :type ast_func: ast.Function

    :returns: The CFG representation of the function
    :rtype: cfg.Function
422776
def get_cfg(ast_func):
    
    cfg_func = cfg.Function()
    for ast_var in ast_func.input_variable_list:
        cfg_var = cfg_func.get_variable(ast_var.name)
        cfg_func.add_input_variable(cfg_var)
    for ast_var in ast_func.output_variable_list:
        cfg_var = cfg_func.get_variable(ast_var.name)
        cfg_func.add_output_variable(cfg_var)
    bb_start  = cfg.BasicBlock()
    cfg_func.add_basic_block(bb_start)
    for stmt in ast_func.body:
        bb_temp = bb_start
        bb_temp = process_cfg(stmt, bb_temp, cfg_func)
    cfg_func.clean_up()
    cfg_func.add_summary(ast_func.summary)
    return cfg_func
759206
def _function_signature(func):
    
    if sys.version_info.major > 2:
        # Python 3 already implements this functionality
        return func.__name__ + str(inspect.signature(func))

    # In Python 2 we have to do it manually, unfortunately
    spec = inspect.getargspec(func)
    posargs = spec.args
    defaults = spec.defaults if spec.defaults is not None else []
    varargs = spec.varargs
    kwargs = spec.keywords
    deflen = 0 if defaults is None else len(defaults)
    nodeflen = 0 if posargs is None else len(posargs) - deflen

    args = ['{}'.format(arg) for arg in posargs[:nodeflen]]
    args.extend('{}={}'.format(arg, dval)
                for arg, dval in zip(posargs[nodeflen:], defaults))
    if varargs:
        args.append('*{}'.format(varargs))
    if kwargs:
        args.append('**{}'.format(kwargs))

    argstr = ', '.join(args)

    return '{}({})'.format(func.__name__, argstr)
1105606
def get_signature(func):
    
    code = func.__code__

    # Names of regular parameters
    parameters = tuple(code.co_varnames[:code.co_argcount])

    # Flags
    has_varargs = bool(code.co_flags & inspect.CO_VARARGS)
    has_varkw = bool(code.co_flags & inspect.CO_VARKEYWORDS)
    has_kwonly = bool(code.co_kwonlyargcount)

    # A mapping of parameter names to default values
    default_values = func.__defaults__ or ()
    defaults = dict(zip(parameters[-len(default_values):], default_values))

    # Type annotations for all parameters
    type_hints = typing.get_type_hints(func) if typing else func.__annotations__
    types = tuple(normalize_type(type_hints.get(param, AnyType)) for param in parameters)

    # Type annotations for required parameters
    required = types[:-len(defaults)] if defaults else types

    # Complexity
    complexity = tuple(map(type_complexity, types)) if typing else None

    return Signature(parameters, types, complexity, defaults, required,
                     has_varargs, has_varkw, has_kwonly)
81649
def _getFuncArgs(func):
  
  """
  code = func.func_code
  Defaults = func.func_defaults

  nargs = code.co_argcount
  ArgNames = code.co_varnames[:nargs]

  Args = OrderedDict()
  argCount = len(ArgNames)
  defCount = len(Defaults) if Defaults else 0
  diff = argCount - defCount

  for i in range(0, diff):
    Args[ArgNames[i]] = {}

  for i in range(diff, argCount):
    Args[ArgNames[i]] = {'default': Defaults[i - diff]}

  return Args
292471
def _generate_signature_for_function(self, func):
    """"""
    args_list = []
    argspec = inspect.getargspec(func)
    first_arg_with_default = (
        len(argspec.args or []) - len(argspec.defaults or []))
    for arg in argspec.args[:first_arg_with_default]:
      if arg == "self":
        # Python documentation typically skips `self` when printing method
        # signatures.
        continue
      args_list.append(arg)

    # TODO(mrry): This is a workaround for documenting signature of
    # functions that have the @contextlib.contextmanager decorator.
    # We should do something better.
    if argspec.varargs == "args" and argspec.keywords == "kwds":
      original_func = func.__closure__[0].cell_contents
      return self._generate_signature_for_function(original_func)

    if argspec.defaults:
      for arg, default in zip(
          argspec.args[first_arg_with_default:], argspec.defaults):
        if callable(default):
          args_list.append("%s=%s" % (arg, default.__name__))
        else:
          args_list.append("%s=%r" % (arg, default))
    if argspec.varargs:
      args_list.append("*" + argspec.varargs)
    if argspec.keywords:
      args_list.append("**" + argspec.keywords)
    return "(" + ", ".join(args_list) + ")"
1185018
async def traverse(self, func):
        

        # this allows the reference to be stolen
        async_executor = self

        if inspect.isasyncgenfunction(func):
            async for result in func(*async_executor.args):
                yield result
        else:
            yield await func(*async_executor.args)
1240031
def compile_func(arg_names, statements, name='_the_func', debug=False):
    
    func_def = ast.FunctionDef(
        name=name,
        args=ast.arguments(
            args=[ast.arg(arg=n, annotation=None) for n in arg_names],
            kwonlyargs=[],
            kw_defaults=[],
            defaults=[ex_literal(None) for _ in arg_names],
        ),
        body=statements,
        decorator_list=[],
    )

    mod = ast.Module([func_def])
    ast.fix_missing_locations(mod)

    prog = compile(mod, '<generated>', 'exec')

    # Debug: show bytecode.
    if debug:
        dis.dis(prog)
        for const in prog.co_consts:
            if isinstance(const, types.CodeType):
                dis.dis(const)

    the_locals = {}
    exec(prog, {}, the_locals)
    return the_locals[name]
542615
def copy_func(f, name=None, sinceversion=None, doc=None):
    
    # See
    # http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python
    fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__, f.__defaults__,
                            f.__closure__)
    # in case f was given attrs (note this dict is a shallow copy):
    fn.__dict__.update(f.__dict__)
    if doc is not None:
        fn.__doc__ = doc
    if sinceversion is not None:
        fn = since(sinceversion)(fn)
    return fn
919202
def decorator(caller, func=None):
    
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
577000
def get_func_args(func):
    
    if isinstance(func, functools.partial):
        return _signature(func.func)
    if inspect.isfunction(func) or inspect.ismethod(func):
        return _signature(func)
    # Callable class
    return _signature(func.__call__)
127326
def get_func_task_path(func):
    
    module_path = inspect.getmodule(func).__name__
    task_path = '{module_path}.{func_name}'.format(
                                        module_path=module_path,
                                        func_name=func.__name__
                                    )
    return task_path
163216
def ex_call(func, args):
    
    if isinstance(func, str):
        func = ex_rvalue(func)

    args = list(args)
    for i in range(len(args)):
        if not isinstance(args[i], ast.expr):
            args[i] = ex_literal(args[i])

    if sys.version_info[:2] < (3, 5):
        return ast.Call(func, args, [], None, None)
    else:
        return ast.Call(func, args, [])
844242
def get_function_help(function: str, bel_spec: BELSpec):
    

    function_long = bel_spec["functions"]["to_long"].get(function)
    function_help = []

    if function_long:
        for signature in bel_spec["functions"]["signatures"][function_long]["signatures"]:
            function_help.append(
                {
                    "function_summary": signature["argument_summary"],
                    "argument_help": signature["argument_help_listing"],
                    "description": bel_spec["functions"]["info"][function_long]["description"],
                }
            )

    return function_help
37678
def parse_annotation_function(code, func_name):
    
    expr = parse_annotation(code)
    call = expr.value
    assert type(call) is ast.Call, 'Annotation is not a function call'

    assert type(call.func) is ast.Attribute, 'Unexpected annotation function'
    assert type(call.func.value) is ast.Name, 'Invalid annotation function name'
    assert call.func.value.id == 'nni', 'Annotation is not a NNI function'
    assert call.func.attr == func_name, 'internal error #2'

    assert len(call.keywords) == 1, 'Annotation function contains more than one keyword argument'
    assert call.keywords[0].arg == 'name', 'Annotation keyword argument is not "name"'
    name = call.keywords[0].value

    return name, call
1307679
def custom_function(func, input_files, output_file):
    
    from .modules import utils

    return {
        'dependencies_fn': utils.no_dependencies,
        'compiler_fn': func,
        'input': input_files,
        'output': output_file,
        'kwargs': {},
    }
1233961
def serialize_func_name(func):
    
    if func.__module__ == '__main__':
        raise ValueError('Functions from the __main__ module cannot be '
                         'processed by workers.')
    try:
        # This will only work on Python 3.3 or above, but it will allow us to use static/classmethods
        func_name = func.__qualname__
    except AttributeError:
        func_name = func.__name__
    return ':'.join([func.__module__, func_name])
1004567
def trace(f):
    
    @functools.wraps(f)
    def decorator(*args, **kwargs):
        print 'Calling ' + f.func_name + ' in ' + str(args[0])
        return f(*args, **kwargs)
    return decorator