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

Python templates.replace函数代码示例

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

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



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

示例1: visit_Assign

  def visit_Assign(self, node):
    if not isinstance(node.value, gast.ListComp):
      return self.generic_visit(node)
    if len(node.targets) > 1:
      raise NotImplementedError('multiple assignments')

    target, = node.targets
    list_comp_node = node.value

    template = """
      target = []
    """
    initialization = templates.replace(template, target=target)

    template = """
      target.append(elt)
    """
    body = templates.replace(template, target=target, elt=list_comp_node.elt)

    for gen in reversed(list_comp_node.generators):
      for gen_if in reversed(gen.ifs):
        template = """
          if test:
            body
        """
        body = templates.replace(template, test=gen_if, body=body)
      template = """
        for target in iter_:
          body
      """
      body = templates.replace(
          template, iter_=gen.iter, target=gen.target, body=body)

    return initialization + body
开发者ID:Brandon1016,项目名称:tensorflow,代码行数:34,代码来源:list_comprehensions.py


示例2: replace_as_expression_restrictions

 def replace_as_expression_restrictions(self):
   template = """
     foo(a)
     bar(b)
   """
   with self.assertRaises(ValueError):
     templates.replace_as_expression(template)
   with self.assertRaises(ValueError):
     templates.replace('')
   with self.assertRaises(ValueError):
     templates.replace('a = b')
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:11,代码来源:templates_test.py


示例3: test_replace_attribute

  def test_replace_attribute(self):
    template = """
      def test_fn(a):
        return a.foo
    """

    node = templates.replace(template, foo='b')[0]
    result, _ = compiler.ast_to_object(node)
    mod = imp.new_module('test')
    mod.b = 3
    self.assertEquals(3, result.test_fn(mod))

    with self.assertRaises(ValueError):
      templates.replace(template, foo=1)
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:14,代码来源:templates_test.py


示例4: visit_With

  def visit_With(self, node):
    # Depth-first traversal of syntax
    node = self.generic_visit(node)

    # If the with statement returns, lift the return
    if isinstance(node.body[-1], gast.Return):
      node.body[-1] = templates.replace(
          'a = b', a=self.common_return_name, b=node.body[-1].value)[0]
      return_node = templates.replace('return a', a=self.common_return_name)[0]
      node = self.generic_visit(node)
      self.changes_made = True
      return [node, return_node]
    else:
      return node
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:14,代码来源:return_statements.py


示例5: test_replace_call_keyword

  def test_replace_call_keyword(self):
    template = """
      def test_fn():
        def f(a, d, f):
          return a + d + f
        return f(1, kws=None)
    """

    source = parser.parse_expression('f(d=3, f=5)')
    node = templates.replace(template, kws=source.keywords)[0]
    result, _ = compiler.ast_to_object(node)
    self.assertEquals(9, result.test_fn())

    with self.assertRaises(ValueError):
      templates.replace(template, kws=[])
      templates.replace(template, kws=1)
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:16,代码来源:templates_test.py


示例6: visit_Assert

  def visit_Assert(self, node):
    self.generic_visit(node)

    # Note: The lone tf.Assert call will be wrapped with control_dependencies
    # by side_effect_guards.
    template = """
      tf.Assert(test, (msg,))
    """

    if node.msg is None:
      return templates.replace(
          template, test=node.test, msg=gast.Str('Assertion error'))
    elif isinstance(node.msg, gast.Str):
      return templates.replace(template, test=node.test, msg=node.msg)
    else:
      raise NotImplementedError('can only convert string messages for now.')
开发者ID:Brandon1016,项目名称:tensorflow,代码行数:16,代码来源:asserts.py


示例7: _rename_compilable_function

  def _rename_compilable_function(self, node):
    assert anno.hasanno(node.func, 'live_val')
    assert anno.hasanno(node.func, 'fqn')
    target_entity = anno.getanno(node.func, 'live_val')
    target_fqn = anno.getanno(node.func, 'fqn')

    if not self._should_compile(node, target_fqn):
      return node

    if anno.hasanno(node, 'is_constructor'):
      new_name = self.ctx.namer.compiled_class_name(
          target_fqn, live_entity=target_entity)
      do_rename = True
    else:
      if anno.hasanno(node.func, 'parent_type'):
        owner_type = anno.getanno(node.func, 'parent_type')
      else:
        # Fallback - not reliable.
        owner_type = inspect_utils.getmethodclass(target_entity)
      new_name, do_rename = self.ctx.namer.compiled_function_name(
          target_fqn, live_entity=target_entity, owner_type=owner_type)

    if do_rename:
      if target_entity is not None:
        if tf_inspect.ismethod(target_entity):
          # The renaming process will transform it into a regular function.
          # TODO(mdan): Is this complete? How does it work with nested members?
          node.args = [node.func.value] + node.args
      node.func = templates.replace('func_name', func_name=new_name)[0]
    return node
开发者ID:ZhangXinNan,项目名称:tensorflow,代码行数:30,代码来源:call_trees.py


示例8: visit_For

  def visit_For(self, node):
    scope = anno.getanno(node, NodeAnno.BODY_SCOPE)
    break_var = self.context.namer.new_symbol('break__', scope.referenced)

    node.target = self.visit(node.target)
    node.iter = self.visit(node.iter)
    node.body, break_used = self._track_body(node.body, break_var)
    # A break in the else clause applies to the containing scope.
    node.orelse = self.visit_block(node.orelse)

    if break_used:
      node.orelse = self._guard_if_present(node.orelse, break_var)
      template = """
        var_name = False
        for_stmt
      """
      # Python's else clause only triggers if the loop exited cleanly (e.g.
      # break did not trigger).
      node = templates.replace(
          template,
          var_name=break_var,
          for_stmt=node)
      extra_test = templates.replace_as_expression(
          'not var_name', var_name=break_var)
      anno.setanno(node[1], 'extra_test', extra_test)

    return node
开发者ID:Jackiefan,项目名称:tensorflow,代码行数:27,代码来源:break_statements.py


示例9: _insert_dynamic_conversion

 def _insert_dynamic_conversion(self, node):
   """Inlines a dynamic conversion for a dynamic function."""
   # TODO(mdan): Pass information on the statically compiled functions.
   # Having access to the statically compiled functions can help avoid
   # unnecessary compilation.
   # For example, this would lead to function `a` being compiled twice:
   #
   #   def a():
   #     v = b
   #     b()
   #   def b():
   #     a()
   #
   # This is really a problem with recursive calls, which currently can
   # only be gated by a static condition, and should be rare.
   # TODO(mdan): It probably makes sense to use dynamic conversion every time.
   # Before we could convert all the time though, we'd need a reasonable
   # caching mechanism.
   template = """
     ag__.converted_call(func, True, False, False, {}, args)
   """
   call_expr = templates.replace(template, func=node.func, args=node.args)
   new_call = call_expr[0].value
   # TODO(mdan): Improve the template mechanism to better support this.
   new_call.keywords = node.keywords
   return new_call
开发者ID:ZhangXinNan,项目名称:tensorflow,代码行数:26,代码来源:call_trees.py


示例10: visit_While

  def visit_While(self, node):
    scope = anno.getanno(node, NodeAnno.BODY_SCOPE)
    break_var = self.ctx.namer.new_symbol('break_', scope.referenced)

    node.test = self.visit(node.test)
    node.body, break_used = self._track_body(node.body, break_var)
    # A break in the else clause applies to the containing scope.
    node.orelse = self.visit_block(node.orelse)

    if break_used:
      # Python's else clause only triggers if the loop exited cleanly (e.g.
      # break did not trigger).
      guarded_orelse = self._guard_if_present(node.orelse, break_var)

      template = """
        var_name = False
        while test and not var_name:
          body
        else:
          orelse
      """
      node = templates.replace(
          template,
          var_name=break_var,
          test=node.test,
          body=node.body,
          orelse=guarded_orelse)

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


示例11: visit_Continue

 def visit_Continue(self, node):
   self.set_local(CONTINUE_USED, True)
   template = """
     var_name = True
   """
   return templates.replace(
       template, var_name=self.get_local(CONTROL_VAR_NAME))
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:7,代码来源:continue_statements.py


示例12: visit_Break

 def visit_Break(self, node):
   self.break_uses[-1][0] = True
   template = """
     var_name = True
     continue
   """
   return templates.replace(template, var_name=self.break_uses[-1][1])
开发者ID:tejas-kale,项目名称:tensorflow,代码行数:7,代码来源:break_statements.py


示例13: _create_break_trigger

 def _create_break_trigger(self):
   template = """
     var_name = True
   """
   block = templates.replace(template, var_name=self.break_uses[-1][1])
   block.append(gast.Continue())
   return block
开发者ID:bikong2,项目名称:tensorflow,代码行数:7,代码来源:break_statements.py


示例14: _generate_pop_operation

  def _generate_pop_operation(self, original_call_node, pop_var_name):
    assert isinstance(original_call_node.func, gast.Attribute)

    if original_call_node.args:
      pop_element = original_call_node.args[0]
    else:
      pop_element = parser.parse_expression('None')
    # The call will be something like "target.pop()", and the dtype is hooked to
    # target, hence the func.value.
    dtype = anno.getanno(
        original_call_node.func.value,
        'element_type',
        default=templates.replace_as_expression('None'))
    shape = anno.getanno(
        original_call_node.func.value,
        'element_shape',
        default=templates.replace_as_expression('None'))

    template = """
      target, pop_var_name = ag__.list_pop(
          target, element,
          opts=ag__.ListPopOpts(element_dtype=dtype, element_shape=shape))
    """
    return templates.replace(
        template,
        target=original_call_node.func.value,
        pop_var_name=pop_var_name,
        element=pop_element,
        dtype=dtype,
        shape=shape)
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:30,代码来源:lists.py


示例15: _create_cond_expr

 def _create_cond_expr(self, results, test, body_name, orelse_name):
   if results is not None:
     template = """
       results = ag__.utils.run_cond(test, body_name, orelse_name)
     """
     return templates.replace(
         template,
         test=test,
         results=results,
         body_name=body_name,
         orelse_name=orelse_name)
   else:
     template = """
       ag__.utils.run_cond(test, body_name, orelse_name)
     """
     return templates.replace(
         template, test=test, body_name=body_name, orelse_name=orelse_name)
开发者ID:didukhle,项目名称:tensorflow,代码行数:17,代码来源:control_flow.py


示例16: visit_For

  def visit_For(self, node):
    self.generic_visit(node)

    self._validate_no_live_vars_created(node)

    body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE)
    body_closure = body_scope.modified - body_scope.created
    all_referenced = body_scope.referenced

    state = list(body_closure)

    state_ssf = [
        self.ctx.namer.new_symbol(s.ssf(), all_referenced) for s in state
    ]
    ssf_map = {
        name: ssf
        for name, ssf in zip(state, state_ssf)
        if str(name) != ssf
    }

    if len(state) == 1:
      state = state[0]
      state_ssf = state_ssf[0]
      state_ast_tuple = state
    else:
      state_ast_tuple = gast.Tuple([n.ast() for n in state], None)

    node_body = ast_util.rename_symbols(node.body, ssf_map)
    if anno.hasanno(node, 'extra_test'):
      extra_test = anno.getanno(node, 'extra_test')
      extra_test = ast_util.rename_symbols(extra_test, ssf_map)
    else:
      extra_test = parser.parse_expression('True')

    template = """
      def extra_test_name(state_ssf):
        return extra_test_expr
      def body_name(loop_vars, state_ssf):
        # Workaround for PEP-3113
        iterate = loop_vars
        body
        return state_ssf,
      state_ast_tuple = ag__.for_stmt(
          iter_, extra_test_name, body_name, (state,))
    """
    node = templates.replace(
        template,
        state=state,
        state_ssf=state_ssf,
        state_ast_tuple=state_ast_tuple,
        iter_=node.iter,
        iterate=node.target,
        extra_test_name=self.ctx.namer.new_symbol('extra_test', all_referenced),
        extra_test_expr=extra_test,
        body_name=self.ctx.namer.new_symbol('loop_body', all_referenced),
        body=node_body)

    return node
开发者ID:clsung,项目名称:tensorflow,代码行数:58,代码来源:control_flow.py


示例17: _process_single_assignment

  def _process_single_assignment(self, target, value):
    if not isinstance(target, gast.Subscript):
      return None

    template = """
      target = ag__.set_item(target, key, item)
    """
    return templates.replace(
        template, target=target.value, key=target.slice, item=value)
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:9,代码来源:slices.py


示例18: replace_as_expression

  def replace_as_expression(self):
    template = """
      foo(a)
    """

    node = templates.replace(template, foo='bar', a='baz')
    self.assertTrue(node is gast.Call)
    self.assertEqual(node.func.id, 'bar')
    self.assertEqual(node.func.args[0].id, 'baz')
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:9,代码来源:templates_test.py


示例19: visit_Break

 def visit_Break(self, node):
   self.set_local(BREAK_USED, True)
   var_name = self.get_local(CONTROL_VAR_NAME)
   # TODO(mdan): This will fail when expanded inside a top-level else block.
   template = """
     var_name = True
     continue
   """
   return templates.replace(template, var_name=var_name)
开发者ID:BhaskarNallani,项目名称:tensorflow,代码行数:9,代码来源:break_statements.py


示例20: visit_Break

 def visit_Break(self, node):
   self.state[_Break].used = True
   var_name = self.state[_Break].control_var_name
   # TODO(mdan): This will fail when expanded inside a top-level else block.
   template = """
     var_name = True
     continue
   """
   return templates.replace(template, var_name=var_name)
开发者ID:Brandon1016,项目名称:tensorflow,代码行数:9,代码来源:break_statements.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python model_ops.tree_ensemble_variable函数代码示例发布时间:2022-05-27
下一篇:
Python parser.parse_entity函数代码示例发布时间: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