How to use as_string method in pytest-benchmark

Best Python code snippet using pytest-benchmark

nodes.py

Source:nodes.py Github

copy

Full Screen

...22 Module, Function or Class)23 .set_local(name, node), define an identifier <name> on the first parent frame,24 with the node defining it. This is used by the astng builder and should not25 be used from out there.26 .as_string(), returning a string representation of the code (should be27 executable).28on From and Import :29 .real_name(name),30 [1] http://docs.python.org/lib/module-compiler.ast.html31:author: Sylvain Thenault32:copyright: 2003-2007 LOGILAB S.A. (Paris, FRANCE)33:contact: http://www.logilab.fr/ -- mailto:python-projects@logilab.org34:copyright: 2003-2007 Sylvain Thenault35:contact: mailto:thenault@gmail.com36"""37# This file have been modified by Anatoly Zapadinski to meet the Clone Digger's needs38from __future__ import generators39__docformat__ = "restructuredtext en"40from compiler.ast import Assign, Add, And, AssAttr, AssList, AssName, \41 AssTuple, Assert, Assign, AugAssign, \42 Backquote, Bitand, Bitor, Bitxor, Break, CallFunc, Class, \43 Compare, Const, Continue, Dict, Discard, Div, FloorDiv, \44 Ellipsis, EmptyNode, Exec, \45 For, From, Function, Getattr, Global, \46 If, Import, Invert, Keyword, Lambda, LeftShift, \47 List, ListComp, ListCompFor, ListCompIf, Mod, Module, Mul, Name, Node, \48 Not, Or, Pass, Power, Print, Printnl, Raise, Return, RightShift, Slice, \49 Sliceobj, Stmt, Sub, Subscript, TryExcept, TryFinally, Tuple, UnaryAdd, \50 UnarySub, While, Yield51try:52 # introduced in python 2.453 from compiler.ast import GenExpr, GenExprFor, GenExprIf, GenExprInner54except:55 class GenExpr:56 """dummy GenExpr node, shouldn't be used since py < 2.4"""57 class GenExprFor: 58 """dummy GenExprFor node, shouldn't be used since py < 2.4"""59 class GenExprIf: 60 """dummy GenExprIf node, shouldn't be used since py < 2.4"""61 class GenExprInner: 62 """dummy GenExprInner node, shouldn't be used since py < 2.4"""63try:64 # introduced in python 2.465 from compiler.ast import Decorators66except:67 class Decorators:68 """dummy Decorators node, shouldn't be used since py < 2.4"""69try:70 # introduced in python 2.571 from compiler.ast import With72except:73 class With:74 """dummy With node, shouldn't be used since py < 2.5"""75from clonedigger.logilab.astng._exceptions import NotFoundError, InferenceError76from clonedigger.logilab.astng.utils import extend_class77from clonedigger.logilab.astng import InferenceContext78import re79ID_RGX = re.compile('^[a-zA-Z_][a-zA-Z_0-9]*$')80del re81INFER_NEED_NAME_STMTS = (From, Import, Global, TryExcept)82# Node ######################################################################83class NodeNG:84 """/!\ this class should not be used directly /!\ it's85 only used as a methods and attribute container, and update the86 original class from the compiler.ast module using its dictionnary87 (see below the class definition)88 """89 90 # attributes below are set by the builder module or by raw factories91 fromlineno = None92 tolineno = None93 # parent node in the tree94 parent = None95 def __str__(self):96 return '%s(%s)' % (self.__class__.__name__, getattr(self, 'name', ''))97 98 def parent_of(self, node):99 """return true if i'm a parent of the given node"""100 parent = node.parent101 while parent is not None:102 if self is parent:103 return True104 parent = parent.parent105 return False106 def is_statement(self):107 """return true if the node should be considered as statement node108 """109 if isinstance(self.parent, Stmt):110 return self111 return None112 def statement(self):113 """return the first parent node marked as statement node114 """115 if self.is_statement():116 return self117 return self.parent.statement()118 def frame(self):119 """return the first parent frame node (i.e. Module, Function or Class)120 """121 return self.parent.frame()122 def scope(self):123 """return the first node defining a new scope (i.e. Module,124 Function, Class, Lambda but also GenExpr)125 """126 return self.parent.scope()127 def root(self):128 """return the root node of the tree, (i.e. a Module)129 """130 if self.parent:131 return self.parent.root()132 return self133 def next_sibling(self):134 """return the previous sibling statement 135 """136 while not self.is_statement(): 137 self = self.parent138 index = self.parent.nodes.index(self)139 try:140 return self.parent.nodes[index+1]141 except IndexError:142 return143 def previous_sibling(self):144 """return the next sibling statement 145 """146 while not self.is_statement(): 147 self = self.parent148 index = self.parent.nodes.index(self)149 if index > 0:150 return self.parent.nodes[index-1]151 return152 def nearest(self, nodes):153 """return the node which is the nearest before this one in the154 given list of nodes155 """156 myroot = self.root()157 mylineno = self.source_line()158 nearest = None, 0159 for node in nodes:160 assert node.root() is myroot, \161 'not from the same module %s' % (self, node)162 lineno = node.source_line()163 if node.source_line() > mylineno:164 break165 if lineno > nearest[1]:166 nearest = node, lineno167 # FIXME: raise an exception if nearest is None ?168 return nearest[0]169 170 def source_line(self):171 """return the line number where the given node appears172 we need this method since not all nodes as the lineno attribute173 correctly set...174 """175 line = self.lineno176 if line is None:177 _node = self178 try:179 while line is None:180 _node = _node.getChildNodes()[0]181 line = _node.lineno182 except IndexError:183 _node = self.parent184 while _node and line is None:185 line = _node.lineno186 _node = _node.parent187 self.lineno = line188 return line189 190 def last_source_line(self):191 """return the last block line number for this node (i.e. including192 children)193 """194 try:195 return self.__dict__['_cached_last_source_line']196 except KeyError:197 line = self.source_line()198 for node in self.getChildNodes():199 line = max(line, node.last_source_line())200 self._cached_last_source_line = line201 return line202 def block_range(self, lineno):203 """handle block line numbers range for non block opening statements204 """205 return lineno, self.last_source_line()206 def set_local(self, name, stmt):207 """delegate to a scoped parent handling a locals dictionary208 """209 self.parent.set_local(name, stmt)210 def nodes_of_class(self, klass, skip_klass=None):211 """return an iterator on nodes which are instance of the given class(es)212 klass may be a class object or a tuple of class objects213 """214 if isinstance(self, klass):215 yield self216 for child_node in self.getChildNodes():217 if skip_klass is not None and isinstance(child_node, skip_klass):218 continue219 for matching in child_node.nodes_of_class(klass, skip_klass):220 yield matching221 def _infer_name(self, frame, name):222 if isinstance(self, INFER_NEED_NAME_STMTS) or (223 isinstance(self, (Function, Lambda)) and self is frame):224 return name225 return None226 def eq(self, value):227 return False228 229extend_class(Node, NodeNG)230Const.eq = lambda self, value: self.value == value231def decorators_scope(self):232 # skip the function node to go directly to the upper level scope233 return self.parent.parent.scope()234Decorators.scope = decorators_scope235# block range overrides #######################################################236def object_block_range(node, lineno):237 """handle block line numbers range for function/class statements:238 start from the "def" or "class" position whatever the given lineno239 """240 return node.source_line(), node.last_source_line()241Function.block_range = object_block_range242Class.block_range = object_block_range243Module.block_range = object_block_range244def if_block_range(node, lineno):245 """handle block line numbers range for if/elif statements246 """247 last = None248 for test, testbody in node.tests[1:]:249 if lineno == testbody.source_line():250 return lineno, lineno251 if lineno <= testbody.last_source_line():252 return lineno, testbody.last_source_line()253 if last is None:254 last = testbody.source_line() - 1255 return elsed_block_range(node, lineno, last)256If.block_range = if_block_range257def try_except_block_range(node, lineno):258 """handle block line numbers range for try/except statements259 """260 last = None261 for excls, exinst, exbody in node.handlers:262 if excls and lineno == excls.source_line():263 return lineno, lineno264 if exbody.source_line() <= lineno <= exbody.last_source_line():265 return lineno, exbody.last_source_line()266 if last is None:267 last = exbody.source_line() - 1268 return elsed_block_range(node, lineno, last)269TryExcept.block_range = try_except_block_range270def elsed_block_range(node, lineno, last=None):271 """handle block line numbers range for try/finally, for and while272 statements273 """274 if lineno == node.source_line():275 return lineno, lineno276 if node.else_:277 if lineno >= node.else_.source_line():278 return lineno, node.else_.last_source_line()279 return lineno, node.else_.source_line() - 1280 return lineno, last or node.last_source_line()281TryFinally.block_range = elsed_block_range282While.block_range = elsed_block_range283For.block_range = elsed_block_range284# From and Import #############################################################285def real_name(node, asname):286 """get name from 'as' name287 """288 for index in range(len(node.names)):289 name, _asname = node.names[index]290 if name == '*':291 return asname292 if not _asname:293 name = name.split('.', 1)[0]294 _asname = name295 if asname == _asname:296 return name297 raise NotFoundError(asname)298 299From.real_name = real_name300Import.real_name = real_name301def infer_name_module(node, name):302 context = InferenceContext(node)303 context.lookupname = name304 return node.infer(context, asname=False)305Import.infer_name_module = infer_name_module306# as_string ###################################################################307def add_as_string(node):308 """return an ast.Add node as string"""309 return '(%s) + (%s)' % (node.left.as_string(), node.right.as_string())310Add.as_string = add_as_string311def and_as_string(node):312 """return an ast.And node as string"""313 return ' and '.join(['(%s)' % n.as_string() for n in node.nodes])314And.as_string = and_as_string315 316def assattr_as_string(node):317 """return an ast.AssAttr node as string"""318 if node.flags == 'OP_DELETE':319 return 'del %s.%s' % (node.expr.as_string(), node.attrname.as_string())320 return '%s.%s' % (node.expr.as_string(), node.attrname.as_string())321AssAttr.as_string = assattr_as_string322def asslist_as_string(node):323 """return an ast.AssList node as string"""324 string = ', '.join([n.as_string() for n in node.nodes])325 return '[%s]' % string326AssList.as_string = asslist_as_string327def assname_as_string(node):328 """return an ast.AssName node as string"""329 if node.flags == 'OP_DELETE':330 return 'del %s' % node.name.as_string()331 return node.name.as_string()332AssName.as_string = assname_as_string333 334def asstuple_as_string(node):335 """return an ast.AssTuple node as string"""336 string = ', '.join([n.as_string() for n in node.nodes])337 # fix for del statement338 return string.replace(', del ', ', ')339AssTuple.as_string = asstuple_as_string340def assert_as_string(node):341 """return an ast.Assert node as string"""342 if node.fail:343 return 'assert %s, %s' % (node.test.as_string(), node.fail.as_string())344 return 'assert %s' % node.test.as_string()345Assert.as_string = assert_as_string346def assign_as_string(node):347 """return an ast.Assign node as string"""348 lhs = ' = '.join([n.as_string() for n in node.nodes])349 return '%s = %s' % (lhs, node.expr.as_string())350Assign.as_string = assign_as_string351def augassign_as_string(node):352 """return an ast.AugAssign node as string"""353 return '%s %s %s' % (node.node.as_string(), node.op.as_string(), node.expr.as_string())354AugAssign.as_string = augassign_as_string355def backquote_as_string(node):356 """return an ast.Backquote node as string"""357 return '`%s`' % node.expr.as_string()358Backquote.as_string = backquote_as_string359def bitand_as_string(node):360 """return an ast.Bitand node as string"""361 return ' & '.join(['(%s)' % n.as_string() for n in node.nodes])362Bitand.as_string = bitand_as_string363def bitor_as_string(node):364 """return an ast.Bitor node as string"""365 return ' | '.join(['(%s)' % n.as_string() for n in node.nodes])366Bitor.as_string = bitor_as_string367def bitxor_as_string(node):368 """return an ast.Bitxor node as string"""369 return ' ^ '.join(['(%s)' % n.as_string() for n in node.nodes])370Bitxor.as_string = bitxor_as_string371def break_as_string(node):372 """return an ast.Break node as string"""373 return 'break'374Break.as_string = break_as_string375def callfunc_as_string(node):376 """return an ast.CallFunc node as string"""377 expr_str = node.node.as_string()378 args = ', '.join([arg.as_string() for arg in node.args])379 if node.star_args:380 args += ', *%s' % node.star_args.as_string()381 if node.dstar_args:382 args += ', **%s' % node.dstar_args.as_string()383 return '%s(%s)' % (expr_str, args)384CallFunc.as_string = callfunc_as_string385def class_as_string(node):386 """return an ast.Class node as string"""387 bases = ', '.join([n.as_string() for n in node.bases])388 bases = bases and '(%s)' % bases or ''389 docs = node.doc and '\n """%s"""' % node.doc or ''390 return 'class %s%s:%s\n %s\n' % (node.name.as_string(), bases, docs,391 node.code.as_string())392Class.as_string = class_as_string393def compare_as_string(node):394 """return an ast.Compare node as string"""395 rhs_str = ' '.join(['%s %s' % (op.as_string(), expr.as_string())396 for op, expr in node.ops])397 return '%s %s' % (node.expr.as_string(), rhs_str)398Compare.as_string = compare_as_string399def const_as_string(node):400 """return an ast.Const node as string"""401 return node.value.as_string()402Const.as_string = const_as_string403def continue_as_string(node):404 """return an ast.Continue node as string"""405 return 'continue'406Continue.as_string = continue_as_string407def dict_as_string(node):408 """return an ast.Dict node as string"""409 return '{%s}' % ', '.join(['%s: %s' % (key.as_string(), value.as_string())410 for key, value in node.items])411Dict.as_string = dict_as_string412def discard_as_string(node):413 """return an ast.Discard node as string"""414 return node.expr.as_string()415Discard.as_string = discard_as_string416def div_as_string(node):417 """return an ast.Div node as string"""418 return '(%s) / (%s)' % (node.left.as_string(), node.right.as_string())419Div.as_string = div_as_string420def floordiv_as_string(node):421 """return an ast.Div node as string"""422 return '(%s) // (%s)' % (node.left.as_string(), node.right.as_string())423FloorDiv.as_string = floordiv_as_string424def ellipsis_as_string(node):425 """return an ast.Ellipsis node as string"""426 return '...'427Ellipsis.as_string = ellipsis_as_string428def empty_as_string(node):429 return ''430EmptyNode.as_string = empty_as_string431def exec_as_string(node):432 """return an ast.Exec node as string"""433 if node.globals:434 return 'exec %s in %s, %s' % (node.expr.as_string(),435 node.locals.as_string(),436 node.globals.as_string())437 if node.locals:438 return 'exec %s in %s' % (node.expr.as_string(),439 node.locals.as_string())440 return 'exec %s' % node.expr.as_string()441Exec.as_string = exec_as_string442def for_as_string(node):443 """return an ast.For node as string"""444 fors = 'for %s in %s:\n %s' % (node.assign.as_string(),445 node.list.as_string(),446 node.body.as_string())447 if node.else_:448 fors = '%s\nelse:\n %s' % (fors, node.else_.as_string())449 return fors450For.as_string = for_as_string451def from_as_string(node):452 """return an ast.From node as string"""453 return 'from %s import %s' % (node.modname, _import_string(node.names))454From.as_string = from_as_string455def function_as_string(node):456 """return an ast.Function node as string"""457 fargs = node.format_args()458 docs = node.doc and '\n """%s"""' % node.doc or ''459 return 'def %s(%s):%s\n %s' % (node.name, fargs, docs,460 node.code.as_string())461Function.as_string = function_as_string462def genexpr_as_string(node):463 """return an ast.GenExpr node as string"""464 return '(%s)' % node.code.as_string()465GenExpr.as_string = genexpr_as_string466def genexprinner_as_string(node):467 """return an ast.GenExpr node as string"""468 return '%s %s' % (node.expr.as_string(), ' '.join([n.as_string()469 for n in node.quals]))470GenExprInner.as_string = genexprinner_as_string471def genexprfor_as_string(node):472 """return an ast.GenExprFor node as string"""473 return 'for %s in %s %s' % (node.assign.as_string(),474 node.iter.as_string(),475 ' '.join([n.as_string() for n in node.ifs]))476GenExprFor.as_string = genexprfor_as_string477def genexprif_as_string(node):478 """return an ast.GenExprIf node as string"""479 return 'if %s' % node.test.as_string()480GenExprIf.as_string = genexprif_as_string481def getattr_as_string(node):482 """return an ast.Getattr node as string"""483 return '%s.%s' % (node.expr.as_string(), node.attrname.as_string())484Getattr.as_string = getattr_as_string485def global_as_string(node):486 """return an ast.Global node as string"""487 return 'global %s' % ', '.join([name.as_string() for name in node.names])488Global.as_string = global_as_string489def if_as_string(node):490 """return an ast.If node as string"""491 cond, body = node.tests[0]492 ifs = ['if %s:\n %s' % (cond.as_string(), body.as_string())]493 for cond, body in node.tests[1:]:494 ifs.append('elif %s:\n %s' % (cond.as_string(), body.as_string()))495 if node.else_:496 ifs.append('else:\n %s' % node.else_.as_string())497 return '\n'.join(ifs)498If.as_string = if_as_string499def import_as_string(node):500 """return an ast.Import node as string"""501 return 'import %s' % _import_string(node.names)502Import.as_string = import_as_string503def invert_as_string(node):504 """return an ast.Invert node as string"""505 return '~%s' % node.expr.as_string()506Invert.as_string = invert_as_string507def keyword_as_string(node):508 """return an ast.Keyword node as string"""509 return '%s=%s' % (node.name.as_string(), node.expr.as_string())510Keyword.as_string = keyword_as_string511def lambda_as_string(node):512 """return an ast.Lambda node as string"""513 return 'lambda %s: %s' % (node.format_args(), node.code.as_string())514Lambda.as_string = lambda_as_string515def leftshift_as_string(node):516 """return an ast.LeftShift node as string"""517 return '(%s) << (%s)' % (node.left.as_string(), node.right.as_string())518LeftShift.as_string = leftshift_as_string519def list_as_string(node):520 """return an ast.List node as string"""521 return '[%s]' % ', '.join([child.as_string() for child in node.nodes])522List.as_string = list_as_string523def listcomp_as_string(node):524 """return an ast.ListComp node as string"""525 return '[%s %s]' % (node.expr.as_string(), ' '.join([n.as_string()526 for n in node.quals]))527ListComp.as_string = listcomp_as_string528def listcompfor_as_string(node):529 """return an ast.ListCompFor node as string"""530 return 'for %s in %s %s' % (node.assign.as_string(),531 node.list.as_string(),532 ' '.join([n.as_string() for n in node.ifs]))533ListCompFor.as_string = listcompfor_as_string534def listcompif_as_string(node):535 """return an ast.ListCompIf node as string"""536 return 'if %s' % node.test.as_string()537ListCompIf.as_string = listcompif_as_string538def mod_as_string(node):539 """return an ast.Mod node as string"""540 return '(%s) %% (%s)' % (node.left.as_string(), node.right.as_string())541Mod.as_string = mod_as_string542def module_as_string(node):543 """return an ast.Module node as string"""544 docs = node.doc and '"""%s"""\n' % node.doc or ''545 return '%s%s' % (docs, node.node.as_string())546Module.as_string = module_as_string547def mul_as_string(node):548 """return an ast.Mul node as string"""549 return '(%s) * (%s)' % (node.left.as_string(), node.right.as_string())550Mul.as_string = mul_as_string551def name_as_string(node):552 """return an ast.Name node as string"""553 return node.name.as_string()554Name.as_string = name_as_string555def not_as_string(node):556 """return an ast.Not node as string"""557 return 'not %s' % node.expr.as_string()558Not.as_string = not_as_string559def or_as_string(node):560 """return an ast.Or node as string"""561 return ' or '.join(['(%s)' % n.as_string() for n in node.nodes])562Or.as_string = or_as_string563def pass_as_string(node):564 """return an ast.Pass node as string"""565 return 'pass'566Pass.as_string = pass_as_string567def power_as_string(node):568 """return an ast.Power node as string"""569 return '(%s) ** (%s)' % (node.left.as_string(), node.right.as_string())570Power.as_string = power_as_string571def print_as_string(node):572 """return an ast.Print node as string"""573 nodes = ', '.join([n.as_string() for n in node.nodes])574 if node.dest:575 return 'print >> %s, %s,' % (node.dest.as_string(), nodes)576 return 'print %s,' % nodes577Print.as_string = print_as_string578def printnl_as_string(node):579 """return an ast.Printnl node as string"""580 nodes = ', '.join([n.as_string() for n in node.nodes])581 if node.dest:582 return 'print >> %s, %s' % (node.dest.as_string(), nodes)583 return 'print %s' % nodes584Printnl.as_string = printnl_as_string585def raise_as_string(node):586 """return an ast.Raise node as string"""587 if node.expr1:588 if node.expr2:589 if node.expr3:590 return 'raise %s, %s, %s' % (node.expr1.as_string(),591 node.expr2.as_string(),592 node.expr3.as_string())593 return 'raise %s, %s' % (node.expr1.as_string(),594 node.expr2.as_string())595 return 'raise %s' % node.expr1.as_string()596 return 'raise'597Raise.as_string = raise_as_string598def return_as_string(node):599 """return an ast.Return node as string"""600 return 'return %s' % node.value.as_string()601Return.as_string = return_as_string602def rightshift_as_string(node):603 """return an ast.RightShift node as string"""604 return '(%s) >> (%s)' % (node.left.as_string(), node.right.as_string())605RightShift.as_string = rightshift_as_string606def slice_as_string(node):607 """return an ast.Slice node as string"""608 # FIXME: use flags609 lower = node.lower and node.lower.as_string() or ''610 upper = node.upper and node.upper.as_string() or ''611 return '%s[%s:%s]' % (node.expr.as_string(), lower, upper)612Slice.as_string = slice_as_string613def sliceobj_as_string(node):614 """return an ast.Sliceobj node as string"""615 return ':'.join([n.as_string() for n in node.nodes])616Sliceobj.as_string = sliceobj_as_string617def stmt_as_string(node):618 """return an ast.Stmt node as string"""619 stmts = '\n'.join([n.as_string() for n in node.nodes])620 if isinstance(node.parent, Module):621 return stmts622 return stmts.replace('\n', '\n ')623Stmt.as_string = stmt_as_string624def sub_as_string(node):625 """return an ast.Sub node as string"""626 return '(%s) - (%s)' % (node.left.as_string(), node.right.as_string())627Sub.as_string = sub_as_string628def subscript_as_string(node):629 """return an ast.Subscript node as string"""630 # FIXME: flags ?631 return '%s[%s]' % (node.expr.as_string(), ','.join([n.as_string()632 for n in node.subs]))633Subscript.as_string = subscript_as_string634def tryexcept_as_string(node):635 """return an ast.TryExcept node as string"""636 trys = ['try:\n %s' % node.body.as_string()]637 for exc_type, exc_obj, body in node.handlers:638 if exc_type:639 if exc_obj:640 excs = 'except %s, %s' % (exc_type.as_string(),641 exc_obj.as_string())642 else:643 excs = 'except %s' % exc_type.as_string()644 else:645 excs = 'except'646 trys.append('%s:\n %s' % (excs, body.as_string()))647 return '\n'.join(trys)648TryExcept.as_string = tryexcept_as_string649def tryfinally_as_string(node):650 """return an ast.TryFinally node as string"""651 return 'try:\n %s\nfinally:\n %s' % (node.body.as_string(),652 node.final.as_string())653TryFinally.as_string = tryfinally_as_string654def tuple_as_string(node):655 """return an ast.Tuple node as string"""656 return '(%s)' % ', '.join([child.as_string() for child in node.nodes])657Tuple.as_string = tuple_as_string658def unaryadd_as_string(node):659 """return an ast.UnaryAdd node as string"""660 return '+%s' % node.expr.as_string()661UnaryAdd.as_string = unaryadd_as_string662def unarysub_as_string(node):663 """return an ast.UnarySub node as string"""664 return '-%s' % node.expr.as_string()665UnarySub.as_string = unarysub_as_string666def while_as_string(node):667 """return an ast.While node as string"""668 whiles = 'while %s:\n %s' % (node.test.as_string(),669 node.body.as_string())670 if node.else_:671 whiles = '%s\nelse:\n %s' % (whiles, node.else_.as_string())672 return whiles673While.as_string = while_as_string674def with_as_string(node):675 """return an ast.With node as string"""676 withs = 'with (%s) as (%s):\n %s' % (node.expr.as_string(),677 node.vars.as_string(),678 node.body.as_string())679 return withs680With.as_string = with_as_string681def yield_as_string(node):682 """yield an ast.Yield node as string"""683 return 'yield %s' % node.value.as_string()684Yield.as_string = yield_as_string685def _import_string(names):686 """return a list of (name, asname) formatted as a string687 """688 _names = []689 for name, asname in names:690 if asname is not None:691 _names.append('%s as %s' % (name, asname))692 else:693 _names.append(name)694 return ', '.join(_names)695# to backport into compiler ###################################################...

Full Screen

Full Screen

as_string_op_test.py

Source:as_string_op_test.py Github

copy

Full Screen

...28 ]29 with self.test_session():30 for dtype in (dtypes.float32, dtypes.float64):31 input_ = array_ops.placeholder(dtype)32 output = string_ops.as_string(input_, shortest=True)33 result = output.eval(feed_dict={input_: float_inputs_})34 s = lambda strs: [x.decode("ascii") for x in strs]35 self.assertAllEqual(s(result), ["%g" % x for x in float_inputs_])36 output = string_ops.as_string(input_, scientific=True)37 result = output.eval(feed_dict={input_: float_inputs_})38 self.assertAllEqual(s(result), ["%e" % x for x in float_inputs_])39 output = string_ops.as_string(input_)40 result = output.eval(feed_dict={input_: float_inputs_})41 self.assertAllEqual(s(result), ["%f" % x for x in float_inputs_])42 output = string_ops.as_string(input_, width=3)43 result = output.eval(feed_dict={input_: float_inputs_})44 self.assertAllEqual(s(result), ["%3f" % x for x in float_inputs_])45 output = string_ops.as_string(input_, width=3, fill="0")46 result = output.eval(feed_dict={input_: float_inputs_})47 self.assertAllEqual(s(result), ["%03f" % x for x in float_inputs_])48 output = string_ops.as_string(input_, width=3, fill="0", shortest=True)49 result = output.eval(feed_dict={input_: float_inputs_})50 self.assertAllEqual(s(result), ["%03g" % x for x in float_inputs_])51 output = string_ops.as_string(input_, precision=10, width=3)52 result = output.eval(feed_dict={input_: float_inputs_})53 self.assertAllEqual(s(result), ["%03.10f" % x for x in float_inputs_])54 output = string_ops.as_string(55 input_, precision=10, width=3, fill="0", shortest=True)56 result = output.eval(feed_dict={input_: float_inputs_})57 self.assertAllEqual(s(result), ["%03.10g" % x for x in float_inputs_])58 with self.assertRaisesOpError("Cannot select both"):59 output = string_ops.as_string(input_, scientific=True, shortest=True)60 output.eval(feed_dict={input_: float_inputs_})61 with self.assertRaisesOpError("Fill string must be one or fewer"):62 output = string_ops.as_string(input_, fill="ab")63 output.eval(feed_dict={input_: float_inputs_})64 def testInt(self):65 # Cannot use values outside -128..127 for test, because we're also66 # testing int867 int_inputs_ = [0, -1, 1, -128, 127, -101, 101, -0]68 s = lambda strs: [x.decode("ascii") for x in strs]69 with self.test_session():70 for dtype in (dtypes.int32, dtypes.int64, dtypes.int8):71 input_ = array_ops.placeholder(dtype)72 output = string_ops.as_string(input_)73 result = output.eval(feed_dict={input_: int_inputs_})74 self.assertAllEqual(s(result), ["%d" % x for x in int_inputs_])75 output = string_ops.as_string(input_, width=3)76 result = output.eval(feed_dict={input_: int_inputs_})77 self.assertAllEqual(s(result), ["%3d" % x for x in int_inputs_])78 output = string_ops.as_string(input_, width=3, fill="0")79 result = output.eval(feed_dict={input_: int_inputs_})80 self.assertAllEqual(s(result), ["%03d" % x for x in int_inputs_])81 with self.assertRaisesOpError("scientific and shortest"):82 output = string_ops.as_string(input_, scientific=True)83 output.eval(feed_dict={input_: int_inputs_})84 with self.assertRaisesOpError("scientific and shortest"):85 output = string_ops.as_string(input_, shortest=True)86 output.eval(feed_dict={input_: int_inputs_})87 with self.assertRaisesOpError("precision not supported"):88 output = string_ops.as_string(input_, precision=0)89 output.eval(feed_dict={input_: int_inputs_})90 def testLargeInt(self):91 # Cannot use values outside -128..127 for test, because we're also92 # testing int893 s = lambda strs: [x.decode("ascii") for x in strs]94 with self.test_session():95 input_ = array_ops.placeholder(dtypes.int32)96 int_inputs_ = [np.iinfo(np.int32).min, np.iinfo(np.int32).max]97 output = string_ops.as_string(input_)98 result = output.eval(feed_dict={input_: int_inputs_})99 self.assertAllEqual(s(result), ["%d" % x for x in int_inputs_])100 input_ = array_ops.placeholder(dtypes.int64)101 int_inputs_ = [np.iinfo(np.int64).min, np.iinfo(np.int64).max]102 output = string_ops.as_string(input_)103 result = output.eval(feed_dict={input_: int_inputs_})104 self.assertAllEqual(s(result), ["%d" % x for x in int_inputs_])105 def testBool(self):106 bool_inputs_ = [False, True]107 s = lambda strs: [x.decode("ascii") for x in strs]108 with self.test_session():109 for dtype in (dtypes.bool,):110 input_ = array_ops.placeholder(dtype)111 output = string_ops.as_string(input_)112 result = output.eval(feed_dict={input_: bool_inputs_})113 self.assertAllEqual(s(result), ["false", "true"])114 def testComplex(self):115 float_inputs_ = [116 0, 1, -1, 0.5, 0.25, 0.125, complex("INF"), complex("NAN"),117 complex("-INF")118 ]119 complex_inputs_ = [(x + (x + 1) * 1j) for x in float_inputs_]120 with self.test_session():121 for dtype in (dtypes.complex64,):122 input_ = array_ops.placeholder(dtype)123 def clean_nans(s_l):124 return [s.decode("ascii").replace("-nan", "nan") for s in s_l]125 output = string_ops.as_string(input_, shortest=True)126 result = output.eval(feed_dict={input_: complex_inputs_})127 self.assertAllEqual(128 clean_nans(result),129 ["(%g,%g)" % (x.real, x.imag) for x in complex_inputs_])130 output = string_ops.as_string(input_, scientific=True)131 result = output.eval(feed_dict={input_: complex_inputs_})132 self.assertAllEqual(133 clean_nans(result),134 ["(%e,%e)" % (x.real, x.imag) for x in complex_inputs_])135 output = string_ops.as_string(input_)136 result = output.eval(feed_dict={input_: complex_inputs_})137 self.assertAllEqual(138 clean_nans(result),139 ["(%f,%f)" % (x.real, x.imag) for x in complex_inputs_])140 output = string_ops.as_string(input_, width=3)141 result = output.eval(feed_dict={input_: complex_inputs_})142 self.assertAllEqual(143 clean_nans(result),144 ["(%03f,%03f)" % (x.real, x.imag) for x in complex_inputs_])145 output = string_ops.as_string(input_, width=3, fill="0", shortest=True)146 result = output.eval(feed_dict={input_: complex_inputs_})147 self.assertAllEqual(148 clean_nans(result),149 ["(%03g,%03g)" % (x.real, x.imag) for x in complex_inputs_])150 output = string_ops.as_string(input_, precision=10, width=3)151 result = output.eval(feed_dict={input_: complex_inputs_})152 self.assertAllEqual(153 clean_nans(result),154 ["(%03.10f,%03.10f)" % (x.real, x.imag) for x in complex_inputs_])155 output = string_ops.as_string(156 input_, precision=10, width=3, fill="0", shortest=True)157 result = output.eval(feed_dict={input_: complex_inputs_})158 self.assertAllEqual(159 clean_nans(result),160 ["(%03.10g,%03.10g)" % (x.real, x.imag) for x in complex_inputs_])161 with self.assertRaisesOpError("Cannot select both"):162 output = string_ops.as_string(input_, scientific=True, shortest=True)163 output.eval(feed_dict={input_: complex_inputs_})164if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-benchmark automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful