• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python six.get_function_globals函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.get_function_globals函数的典型用法代码示例。如果您正苦于以下问题:Python get_function_globals函数的具体用法?Python get_function_globals怎么用?Python get_function_globals使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_function_globals函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _update_function

def _update_function(oldfunc, newfunc):
    """Update a function object."""
    if _closure_changed(six.get_function_closure(oldfunc),
                        six.get_function_closure(newfunc)):
        raise ClosureChanged()
    setattr(oldfunc, six._func_code, six.get_function_code(newfunc))
    setattr(oldfunc, six._func_defaults, six.get_function_defaults(newfunc))
    _update_scope(six.get_function_globals(oldfunc),
                  six.get_function_globals(newfunc))
    # XXX What else?
    return oldfunc
开发者ID:plone,项目名称:plone.reload,代码行数:11,代码来源:xreload.py


示例2: class_to_graph

def class_to_graph(c, conversion_map, param_value_hints):
  """Specialization of `object_to_graph` for classes."""
  converted_members = {}
  members = tf_inspect.getmembers(c, predicate=tf_inspect.ismethod)
  if not members:
    raise ValueError('Cannot convert %s: it has no member methods.')

  if 'self' in param_value_hints:
    raise ValueError('Hints may not be provided for reserved name "self".')
  param_value_hints['self'] = (c.__name__, c)

  class_globals = None
  for _, m in members:
    node, _ = function_to_graph(m, conversion_map, param_value_hints, c)
    # TODO(mdan): Do not assume all members have the same view of globals.
    if class_globals is None:
      class_globals = six.get_function_globals(m)
    converted_members[m] = node
  namer = conversion_map.new_namer(class_globals)
  class_name = namer.compiled_class_name(c.__name__, c)
  node = gast.ClassDef(
      class_name,
      bases=[],
      keywords=[],
      body=converted_members.values(),
      decorator_list=[])

  return node, class_name
开发者ID:andrewharp,项目名称:tensorflow,代码行数:28,代码来源:conversion.py


示例3: class_to_graph

def class_to_graph(c, conversion_map):
  """Specialization of `entity_to_graph` for classes."""
  converted_members = {}
  members = tf_inspect.getmembers(c, predicate=tf_inspect.ismethod)
  if not members:
    raise ValueError('Cannot convert %s: it has no member methods.')

  class_globals = None
  for _, m in members:
    node, _ = function_to_graph(
        m,
        conversion_map=conversion_map,
        arg_values={},
        arg_types={'self': (c.__name__, c)},
        owner_type=c)
    # TODO(mdan): Do not assume all members have the same view of globals.
    if class_globals is None:
      class_globals = six.get_function_globals(m)
    converted_members[m] = node
  namer = conversion_map.new_namer(class_globals)
  class_name = namer.compiled_class_name(c.__name__, c)
  node = gast.ClassDef(
      class_name,
      bases=[],
      keywords=[],
      body=converted_members.values(),
      decorator_list=[])

  return node, class_name
开发者ID:craffel,项目名称:tensorflow,代码行数:29,代码来源:conversion.py


示例4: function_to_graph

def function_to_graph(f, conversion_map, arg_values, arg_types,
                      owner_type=None):
  """Specialization of `entity_to_graph` for callable functions."""
  node = parser.parse_object(f).body[0]
  namespace = six.get_function_globals(f)

  # This is needed for non-global functions.
  closure = six.get_function_closure(f)
  if closure:
    for e in closure:
      if callable(e.cell_contents):
        fn = e.cell_contents
        namespace[fn.__name__] = fn

  namer = conversion_map.new_namer(namespace)
  ctx = context.EntityContext(
      namer=namer,
      source_code=tf_inspect.getsource(f),
      source_file=tf_inspect.getfile(f),
      namespace=namespace,
      arg_values=arg_values,
      arg_types=arg_types)
  node = node_to_graph(node, ctx, conversion_map.nocompile_decorators)

  # Simulate a rename to ensure the top level is in the name map. This is needed
  # for top level functions, and it also helps the consistency verification made
  # by update_name_map.
  if owner_type is not None:
    new_name = namer.compiled_function_name(f.__name__, f, owner_type)
  else:
    new_name = namer.compiled_function_name(f.__name__, f)
  node.name = new_name
  conversion_map.update_name_map(namer)
  return node, conversion_map.name_map[f]
开发者ID:craffel,项目名称:tensorflow,代码行数:34,代码来源:conversion.py


示例5: to_graph

def to_graph(f, arg_value_hints=None):
  """Compile a Python function into equivalent TensorFlow code.

  Args:
    f: A Python function with arbitrary arguments and return values.
    arg_value_hints: A dict mapping parameter names to objects that can hint
        at the type of those parameters.

  Returns:
    A function with a signature identical to `f`, but which when executed it
  creates TF a graph that has the same functionality as the original function.
  """
  conversion_map = conversion.ConversionMap()
  _, name = conversion.object_to_graph(f, conversion_map, arg_value_hints)

  module = gast.Module([])
  for import_line in config.COMPILED_IMPORT_STATEMENTS:
    module.body.append(parser.parse_str(import_line))
  for dep in conversion_map.dependency_cache.values():
    module.body.append(dep)
  compiled_node = compiler.ast_to_object(module)

  # The compiled code should see everything the entry function saw.
  # TODO(mdan): This might not work well if the call tree spans modules?
  compiled_node.__dict__.update(six.get_function_globals(f))

  compiled_fn = getattr(compiled_node, name)
  return compiled_fn
开发者ID:Lin-jipeng,项目名称:tensorflow,代码行数:28,代码来源:api.py


示例6: parse_args

def parse_args(args, path, query, specials):
    def one_or_many(fn_, dict_, key):
        result = [fn_(value) for value in dict_[key]]
        return result[0] if len(result) == 1 else result

    kwargs = {}
    for arg, parse_fn in six.iteritems(args):
        if arg in specials:
            kwargs[arg] = specials[arg]()
        elif parse_fn is None:
            kwargs[arg] = one_or_many(lambda x: x, query, arg)
        elif isinstance(parse_fn, tuple):
            kwargs[arg] = parse_fn[DEFAULT] if arg not in query else one_or_many(parse_fn[CALLABLE], query, arg)
        elif isalambda(parse_fn):
            _code = six.get_function_code(parse_fn)
            closures = six.get_function_closure(parse_fn)
            if closures:
                assert len(closures) <= 1
                fn = closures[0].cell_contents
            else:
                fn = eval(".".join(_code.co_names), six.get_function_globals(parse_fn))
            kwargs[arg] = fn(**parse_args(get_function_args(parse_fn), path, query, specials))
        else:
            kwargs[arg] = one_or_many(parse_fn, query, arg)
    return kwargs
开发者ID:petr-s,项目名称:cleaREST,代码行数:25,代码来源:core.py


示例7: function_to_graph

def function_to_graph(f, conversion_map, param_value_hints):
  """Specialization of `object_to_graph` for callable functions."""
  node = parser.parse_object(f).body[0]
  node_globals = six.get_function_globals(f)

  # This is needed for non-global functions.
  closure = six.get_function_closure(f)
  if closure:
    for e in closure:
      if callable(e.cell_contents):
        fn = e.cell_contents
        node_globals[fn.__name__] = fn

  namer = conversion_map.new_namer(node_globals)
  node = node_to_graph(node, namer, node_globals, param_value_hints)

  # Simulate a rename to ensure the top level is in the name map. This is needed
  # for top level functions, and it also helps the consistency verification made
  # by update_name_map.
  namer.compiled_function_name(f.__name__, f)

  conversion_map.add_to_cache(f, node)
  conversion_map.update_name_map(namer)

  # Recursively convert any remaining dependencies.
  for obj in conversion_map.name_map.keys():
    if obj not in conversion_map.dependency_cache:
      object_to_graph(obj, conversion_map, None)
  return node, conversion_map.name_map[f]
开发者ID:Lin-jipeng,项目名称:tensorflow,代码行数:29,代码来源:conversion.py


示例8: _new_func_from_source

def _new_func_from_source(source, func):
    """
    Create new function defined in source but maintain context from func

    @param func: The function whose global + local context we will use
    @param source: Python source code containing def statement
    """
    src_str = ''.join(source)
    frames = inspect.getouterframes(inspect.currentframe())
    calling_frame = frames[2][0]

    context = {}
    # My initial instict was: exec src_str in func.func_globals.items(), calling_frame.f_locals
    # however this seems to break the function closure so caveat here is that we create a new
    # function with the locals merged into the globals.
    #
    # Possible consequences I can think of:
    #   - If a global exists that already has the same name as the local, it will be overwritten in
    #     in the context of this function. This shouldnt matter though as the global should have already
    #     been hidden by the new name?
    #
    # This functionality should be considered experimental as no idea what other consequences there
    # could be.
    #
    # relevant: http://stackoverflow.com/questions/2749655/why-are-closures-broken-within-exec
    globals = six.get_function_globals(func)
    locals = calling_frame.f_locals
    combined = globals.copy()
    combined.update(locals)
    Logger.debug('New src_str:\n %s' % src_str)
    six.exec_(src_str, combined, context)
    new_func = context[func.__name__]
    return new_func
开发者ID:CyberLight,项目名称:silk,代码行数:33,代码来源:dynamic.py


示例9: to_graph

def to_graph(o, arg_value_hints=None):
  """Compile a Python entity into equivalent TensorFlow code.

  Currently supported entities:
    * functions
    * classes

  Classes are handled by converting all their methods into a new class.

  Args:
    o: A Python function or class.
    arg_value_hints: A dict mapping parameter names to objects that can hint
        at the type of those parameters.

  Returns:
    A function with a signature identical to `o`, but which when executed it
  creates TF a graph that has the same functionality as the original entity.
  """
  conversion_map = conversion.ConversionMap()
  _, name = conversion.object_to_graph(o, conversion_map, arg_value_hints)

  module = gast.Module([])
  for import_line in config.COMPILED_IMPORT_STATEMENTS:
    module.body.append(parser.parse_str(import_line))
  for dep in conversion_map.dependency_cache.values():
    module.body.append(dep)
  compiled_node = compiler.ast_to_object(module)

  # The compiled code should see everything the entry function saw.
  # TODO(mdan): This might not work well if the call tree spans modules?
  if tf_inspect.isfunction(o):
    compiled_node.__dict__.update(six.get_function_globals(o))

  compiled_fn = getattr(compiled_node, name)
  return compiled_fn
开发者ID:andrewharp,项目名称:tensorflow,代码行数:35,代码来源:api.py


示例10: construct_new_test_function

def construct_new_test_function(original_func, name, build_params):
    """Builds a new test function based on parameterized data.

    :param original_func: The original test function that is used as a template
    :param name: The fullname of the new test function
    :param build_params: A dictionary or list containing args or kwargs
        for the new test
    :return: A new function object
    """
    new_func = types.FunctionType(
        six.get_function_code(original_func),
        six.get_function_globals(original_func),
        name=name,
        argdefs=six.get_function_defaults(original_func)
    )

    # Support either an arg list or kwarg dict for our data
    build_args = build_params if isinstance(build_params, list) else []
    build_kwargs = build_params if isinstance(build_params, dict) else {}

    # Build a test wrapper to execute with our kwargs
    def test_wrapper(func, test_args, test_kwargs):
        @functools.wraps(func)
        def wrapper(self):
            return func(self, *test_args, **test_kwargs)
        return wrapper

    return test_wrapper(new_func, build_args, build_kwargs)
开发者ID:openstack,项目名称:python-barbicanclient,代码行数:28,代码来源:utils.py


示例11: function_to_graph

def function_to_graph(f, conversion_map, param_value_hints, owner_type=None):
  """Specialization of `object_to_graph` for callable functions."""
  node = parser.parse_object(f).body[0]
  node_globals = six.get_function_globals(f)

  # This is needed for non-global functions.
  closure = six.get_function_closure(f)
  if closure:
    for e in closure:
      if callable(e.cell_contents):
        fn = e.cell_contents
        node_globals[fn.__name__] = fn

  namer = conversion_map.new_namer(node_globals)
  node = node_to_graph(node, namer, node_globals, param_value_hints)

  # Simulate a rename to ensure the top level is in the name map. This is needed
  # for top level functions, and it also helps the consistency verification made
  # by update_name_map.
  if owner_type is not None:
    new_name = namer.compiled_function_name(f.__name__, f, owner_type)
  else:
    new_name = namer.compiled_function_name(f.__name__, f)
  node.name = new_name
  conversion_map.update_name_map(namer)
  return node, conversion_map.name_map[f]
开发者ID:andrewharp,项目名称:tensorflow,代码行数:26,代码来源:conversion.py


示例12: _build_new_function

def _build_new_function(func, name):
    code = six.get_function_code(func)
    func_globals = six.get_function_globals(func)
    func_defaults = six.get_function_defaults(func)
    func_closure = six.get_function_closure(func)
    return types.FunctionType(code, func_globals,
                              name, func_defaults,
                              func_closure)
开发者ID:stefan-caraiman,项目名称:cloudbase-init-ci,代码行数:8,代码来源:base.py


示例13: fix_js_args

def fix_js_args(func):
    '''Use this function when unsure whether func takes this and arguments as its last 2 args.
       It will append 2 args if it does not.'''
    fcode = six.get_function_code(func)
    fargs = fcode.co_varnames[fcode.co_argcount-2:fcode.co_argcount]
    if fargs==('this', 'arguments') or fargs==('arguments', 'var'):
        return func
    code = append_arguments(six.get_function_code(func), ('this','arguments'))

    return types.FunctionType(code, six.get_function_globals(func), func.__name__, closure=six.get_function_closure(func))
开发者ID:2mny,项目名称:mylar,代码行数:10,代码来源:injector.py


示例14: DataDrivenFixture

def DataDrivenFixture(cls):
    """Generates new unittest test methods from methods defined in the
    decorated class"""

    if not issubclass(cls, TestCase):
        raise DataDrivenFixtureError

    test_case_attrs = dir(cls)
    for attr_name in test_case_attrs:
        if attr_name.startswith(DATA_DRIVEN_TEST_PREFIX) is False:
            # Not a data driven test, skip it
            continue

        original_test = getattr(cls, attr_name, None).__func__
        test_data = getattr(original_test, DATA_DRIVEN_TEST_ATTR, None)

        if test_data is None:
            # no data was provided to the datasource decorator or this is not a
            # data driven test, skip it.
            continue

        for dataset in test_data:
            # Name the new test based on original and dataset names
            base_test_name = str(original_test.__name__)[int(len(DATA_DRIVEN_TEST_PREFIX)) :]
            new_test_name = "test_{0}_{1}".format(base_test_name, dataset.name)

            # Create a new test from the old test
            new_test = FunctionType(
                six.get_function_code(original_test), six.get_function_globals(original_test), name=new_test_name
            )

            # Copy over any other attributes the original test had (mainly to
            # support test tag decorator)
            for attr in list(set(dir(original_test)) - set(dir(new_test))):
                setattr(new_test, attr, getattr(original_test, attr))

            # Change the new test's default keyword values to the appropriate
            # new data as defined by the datasource decorator
            args, _, _, defaults = inspect.getargspec(original_test)

            # Self doesn't have a default, so we need to remove it
            args.remove("self")

            # Make sure we take into account required arguments
            kwargs = dict(zip_longest(args[::-1], list(defaults or ())[::-1], fillvalue=None))

            kwargs.update(dataset.data)

            # Make sure the updated values are in the correct order
            new_default_values = [kwargs[arg] for arg in args]
            setattr(new_test, "func_defaults", tuple(new_default_values))

            # Add the new test to the decorated TestCase
            setattr(cls, new_test_name, new_test)
    return cls
开发者ID:izrik,项目名称:opencafe,代码行数:55,代码来源:decorators.py


示例15: to_graph

def to_graph(e,
             recursive=True,
             verbose=False,
             arg_values=None,
             arg_types=None,
             partial_types=None):
  """Compile a Python entity into equivalent TensorFlow code.

  Currently supported entities:
    * functions
    * classes

  Classes are handled by converting all their methods into a new class.

  Args:
    e: A Python entity.
    recursive: Whether to recusrively convert any functions that the decorator
        function may call.
    verbose: Whether to output the compiled code in the logs.
    arg_values: A dict containing value hints for symbols like function
        parameters.
    arg_types: A dict containing type hints for symbols like function
        parameters.
    partial_types: A set of types (e.g. classes) that will not be converted
        entirely. Calls to member functions for these types will be renamed
        independently.

  Returns:
    A function with a signature identical to `o`, but which when executed it
  creates TF a graph that has the same functionality as the original entity.
  """
  conversion_map = conversion.ConversionMap(
      recursive=recursive,
      nocompile_decorators=(convert, graph_ready, convert_inline),
      partial_types=partial_types,
      api_module=tf_inspect.getmodule(to_graph))
  _, name = conversion.entity_to_graph(e, conversion_map, arg_values, arg_types)

  module = gast.Module([])
  for import_line in config.COMPILED_IMPORT_STATEMENTS:
    module.body.append(parser.parse_str(import_line))
  for dep in conversion_map.dependency_cache.values():
    module.body.append(dep)
  compiled_node, compiled_src = compiler.ast_to_object(module)

  # The compiled code should see everything the entry function saw.
  # TODO(mdan): This might not work well if the call tree spans modules?
  if tf_inspect.isfunction(e):
    compiled_node.__dict__.update(six.get_function_globals(e))
  compiled_fn = getattr(compiled_node, name)

  if verbose:
    logging.info('Compiled output of %s:\n\n%s\n', e, compiled_src)

  return compiled_fn
开发者ID:keithc61,项目名称:tensorflow,代码行数:55,代码来源:api.py


示例16: test_getnamespace_hermetic

  def test_getnamespace_hermetic(self):

    # Intentionally hiding the global function to make sure we don't overwrite
    # it in the global namespace.
    free_function = object()  # pylint:disable=redefined-outer-name

    def test_fn():
      return free_function

    ns = inspect_utils.getnamespace(test_fn)
    globs = six.get_function_globals(test_fn)
    self.assertTrue(ns['free_function'] is free_function)
    self.assertFalse(globs['free_function'] is free_function)
开发者ID:AnishShah,项目名称:tensorflow,代码行数:13,代码来源:inspect_utils_test.py


示例17: copy_func

def copy_func(f, name=None):
    """Create a copy of a function.

    Parameters
    ----------
    f : function
        Function to copy.
    name : str, optional
        Name of new function.

    """
    return types.FunctionType(six.get_function_code(f),
                              six.get_function_globals(f), name or f.__name__,
                              six.get_function_defaults(f), six.get_function_closure(f))
开发者ID:ClinicalGraphics,项目名称:scikit-image,代码行数:14,代码来源:utils.py


示例18: __init__

 def __init__(self, func, fallback=None, autojit_kw=None):
    self.func = func
    # This covers a Python 2/3 change not covered by six
    try:
        self.func_name = func.__name__
    except AttributeError:
        self.func_name = func.func_name
    module_name = inspect.getmoduleinfo(
        six.get_function_globals(func)['__file__']).name
    module_name = '.'.join(['trackpy', module_name])
    self.module_name = module_name
    self.autojit_kw = autojit_kw
    if fallback is not None:
        self.ordinary = fallback
    else:
        self.ordinary = func
开发者ID:abhilashksh,项目名称:trackpy,代码行数:16,代码来源:try_numba.py


示例19: function_to_graph

def function_to_graph(f, conversion_map, arg_values, arg_types,
                      owner_type=None):
  """Specialization of `entity_to_graph` for callable functions."""
  node, source = parser.parse_entity(f)
  node = node.body[0]
  namespace = six.get_function_globals(f)

  # This is needed for non-global functions.
  closure = six.get_function_closure(f)
  if closure:
    for e in closure:
      if callable(e.cell_contents):
        fn = e.cell_contents
        namespace[fn.__name__] = fn

  # Manually add the utils namespace which may be used from generated code.
  if 'py2tf_util' not in namespace:
    namespace['py2tf_utils'] = utils
  elif namespace['py2tf_utils'] != utils:
    raise ValueError(
        'The module name py2tf_utils is reserved and may not be used.')

  namer = conversion_map.new_namer(namespace)
  ctx = context.EntityContext(
      namer=namer,
      source_code=source,
      source_file='<fragment>',
      namespace=namespace,
      arg_values=arg_values,
      arg_types=arg_types,
      recursive=conversion_map.recursive)
  node = node_to_graph(node, ctx, conversion_map.nocompile_decorators)

  # TODO(mdan): This somewhat duplicates the call rename logic in call_treest.py
  new_name, did_rename = namer.compiled_function_name(f.__name__, f, owner_type)
  if not did_rename:
    new_name = f.__name__
    if node.name != f.__name__:
      raise NotImplementedError('Strange corner case. Send us offending code!')

  node.name = new_name
  conversion_map.update_name_map(namer)
  return node, new_name
开发者ID:dananjayamahesh,项目名称:tensorflow,代码行数:43,代码来源:conversion.py


示例20: save_function

def save_function(pickler, obj):
    if not _locate_function(obj, pickler):
        log.info("F1: %s" % obj)
        globs = get_function_globals(obj)
        mod_name = obj.__module__

        pickler.save_reduce(_create_function, (get_function_code(obj),
                                               {},
                                               obj.__name__,
                                               get_function_defaults(obj),
                                               get_function_closure(obj),
                                               obj.__dict__,
                                               mod_name), obj=obj, func_globals=globs)

        log.info("# F1 %s" % obj)
    else:
        log.info("F2: %s" % obj)
        StockPickler.save_global(pickler, obj)
        log.info("# F2 %s" % obj)
    return
开发者ID:wxiang7,项目名称:dill,代码行数:20,代码来源:dill.py



注:本文中的six.get_function_globals函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.get_method_function函数代码示例发布时间:2022-05-27
下一篇:
Python six.get_function_defaults函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap