Python ast.Ellipsis() Examples
The following are 23
code examples of ast.Ellipsis().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ast
, or try the search function
.
Example #1
Source File: type_comment.py From cotk with Apache License 2.0 | 6 votes |
def update_annotations_using_type_comments(app: Sphinx, obj: Any, bound_method: bool) -> None: """Update annotations info of *obj* using type_comments.""" try: function = get_type_comment(obj) if function and hasattr(function, 'argtypes'): if function.argtypes != [ast.Ellipsis]: # type: ignore sig = inspect.signature(obj, bound_method) for i, param in enumerate(sig.parameters.values()): if param.name not in obj.__annotations__: annotation = ast_unparse(function.argtypes[i]) # type: ignore obj.__annotations__[param.name] = annotation if 'return' not in obj.__annotations__: obj.__annotations__['return'] = ast_unparse(function.returns) # type: ignore except NotImplementedError as exc: # failed to ast.unparse() logger.warning("Failed to parse type_comment for %r: %s", obj, exc)
Example #2
Source File: checker.py From pyflakes with MIT License | 6 votes |
def _handle_type_comments(self, node): for (lineno, col_offset), comment in self._type_comments.get(node, ()): comment = comment.split(':', 1)[1].strip() func_match = TYPE_FUNC_RE.match(comment) if func_match: parts = ( func_match.group(1).replace('*', ''), func_match.group(2).strip(), ) else: parts = (comment,) for part in parts: if PY2: part = part.replace('...', 'Ellipsis') self.deferFunction(functools.partial( self.handleStringAnnotation, part, DummyNode(lineno, col_offset), lineno, col_offset, messages.CommentAnnotationSyntaxError, ))
Example #3
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 6 votes |
def visit_Index(self, node): new_value = self._visit(node.value) if isinstance(new_value, ast.Ellipsis): new_node = new_value elif isinstance(new_value, ast.Tuple): if any(isinstance(elt, ast.Ellipsis) for elt in new_value.elts): new_elts = [elt if isinstance(elt, (ast.Ellipsis, ast.Slice)) else ast.Index(elt) for elt in new_value.elts] new_node = ast.ExtSlice(new_elts) else: new_node = ast.Index(new_value) else: new_node = ast.Index(new_value) ast.copy_location(new_node, node) return new_node
Example #4
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_Ellipsis(self, node): new_node = gast.Constant( Ellipsis, None, ) gast.copy_location(new_node, node) new_node.end_lineno = new_node.end_col_offset = None return new_node
Example #5
Source File: onelinerizer.py From onelinerizer with MIT License | 5 votes |
def slice_repr(self, slice): if type(slice) is ast.Ellipsis: return T('Ellipsis') elif type(slice) is ast.Slice: return T('slice({}, {}, {})').format( 'None' if slice.lower is None else self.visit(slice.lower), 'None' if slice.upper is None else self.visit(slice.upper), 'None' if slice.step is None else self.visit(slice.step)) elif type(slice) is ast.ExtSlice: return T('({})').format(T(', ').join(map(self.slice_repr, slice.dims)) + ','*(len(slice.dims) == 1)) elif type(slice) is ast.Index: return self.visit(slice.value) else: raise NotImplementedError('Case not caught: %s' % str(type(slice)))
Example #6
Source File: test_size.py From vulture with MIT License | 5 votes |
def test_size_ellipsis(): example = """ class Foo: bar[1:2, ...] """ if sys.version_info < (3, 0): check_size(example, 2) else: # ast.Ellipsis is a subclass of ast.expr in Python 3. check_size(example, 3)
Example #7
Source File: commonast.py From pscript with BSD 2-Clause "Simplified" License | 5 votes |
def _convert_index_like(self, n): c = self._convert if isinstance(n, (ast.Slice, ast.Index, ast.ExtSlice, ast.Ellipsis)): return c(n) # Python < 3.8 (and also 3.8 on Windows?) elif isinstance(n, ast.Num): return Index(c(n)) else: assert isinstance(n, ast.Tuple) dims = [self._convert_index_like(x) for x in n.elts] return ExtSlice(dims)
Example #8
Source File: commonast.py From pscript with BSD 2-Clause "Simplified" License | 5 votes |
def _convert_Ellipsis(self, n): if pyversion < (3, ): return Index(Ellipsis()) # Ellipses must be wrapped in an index return Ellipsis()
Example #9
Source File: commonast.py From pscript with BSD 2-Clause "Simplified" License | 5 votes |
def _convert_Constant(self, n): val = n.value if val is None or val is True or val is False: return NameConstant(val) if isinstance(val, (int, float, complex)): return Num(val) if isinstance(val, str): return Str(val) if isinstance(val, bytes): return Bytes(val) if val is _Ellipsis: return Ellipsis() raise RuntimeError('Cannot convert %s constants.' % type(val).__name__)
Example #10
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_subscript_1(p): '''subscript : DOT DOT DOT''' # 1 2 3 p[0] = ast.Ellipsis(rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #11
Source File: ast3.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_Constant(self, node): if node.value is None: new_node = ast.NameConstant(node.value) elif node.value is Ellipsis: new_node = ast.Ellipsis() elif isinstance(node.value, bool): new_node = ast.NameConstant(node.value) elif isinstance(node.value, (int, float, complex)): new_node = ast.Num(node.value) elif isinstance(node.value, str): new_node = ast.Str(node.value) else: new_node = ast.Bytes(node.value) ast.copy_location(new_node, node) return new_node
Example #12
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_Constant(self, node): if isinstance(node.value, (bool, int, long, float, complex)): new_node = ast.Num(node.value) elif node.value is Ellipsis: new_node = ast.Ellipsis() else: new_node = ast.Str(node.value) ast.copy_location(new_node, node) return new_node
Example #13
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_ExtSlice(self, node): has_ellipsis = any(isinstance(d, ast.Ellipsis) for d in node.dims) has_slice = any(isinstance(d, ast.Slice) for d in node.dims) new_dims = self._visit(node.dims) if has_ellipsis and not has_slice: new_dims = [nd.value if isinstance(nd, gast.Index) else nd for nd in new_dims] new_node = gast.Index(gast.Tuple(new_dims, gast.Load())) else: new_node = gast.ExtSlice(new_dims) gast.copy_location(new_node, node) new_node.end_lineno = new_node.end_col_offset = None return new_node
Example #14
Source File: helper.py From YAPyPy with MIT License | 5 votes |
def atom_rewrite(loc, name, token, value, number, strs, namedc, ellipsis, dict, is_dict, is_gen, is_list, comp, yield_expr): if name: if not token: return ast.Name(name.value, ast.Load(), **loc @ name) return ex_ast.AssignExpr( ast.Name(name.value, ast.Store(), **loc @ name), value=value, **loc @ token) if number: return ast.Num(eval(number.value), **loc @ number) if strs: return str_maker(*strs) if ellipsis: return ast.Ellipsis() if namedc: return ast.NameConstant(eval(namedc.value), **loc @ namedc) if is_dict: return dict or ex_ast.ExDict([], [], ast.Load(), **loc @ is_dict) if is_gen: if yield_expr: return yield_expr return comp(is_tuple=True) if comp else ast.Tuple([], ast.Load(), **loc @ is_gen) if is_list: return comp(is_list=True) if comp else ast.List([], ast.Load(), **loc @ is_list) raise TypeError
Example #15
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_Subscript(self, node): new_slice = self._visit(node.slice) if isinstance(node.slice, ast.Ellipsis): new_slice = gast.Index(new_slice) new_node = gast.Subscript( self._visit(node.value), new_slice, self._visit(node.ctx), ) gast.copy_location(new_node, node) new_node.end_lineno = new_node.end_col_offset = None return new_node
Example #16
Source File: checker.py From pyflakes with MIT License | 5 votes |
def _is_singleton(node): # type: (ast.AST) -> bool return ( isinstance(node, ast.Name) and node.id in {'True', 'False', 'Ellipsis', 'None'} )
Example #17
Source File: checker.py From pyflakes with MIT License | 5 votes |
def _is_singleton(node): # type: (ast.AST) -> bool return isinstance(node, (ast.NameConstant, ast.Ellipsis))
Example #18
Source File: checker.py From pyflakes with MIT License | 5 votes |
def _is_singleton(node): # type: (ast.AST) -> bool return ( isinstance(node, ast.Constant) and isinstance(node.value, (bool, type(Ellipsis), type(None))) )
Example #19
Source File: overloading.py From overloading.py with MIT License | 5 votes |
def is_void(func): """ Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be used to introduce an overloaded function without actually registering an implementation. """ try: source = dedent(inspect.getsource(func)) except (OSError, IOError): return False fdef = next(ast.iter_child_nodes(ast.parse(source))) return ( type(fdef) is ast.FunctionDef and len(fdef.body) == 1 and type(fdef.body[0]) is ast.Expr and type(fdef.body[0].value) in {ast.Str, ast.Ellipsis})
Example #20
Source File: dead.py From dead with MIT License | 5 votes |
def _is_stub_function(self, node: ast.FunctionDef) -> bool: for stmt in node.body: if ( isinstance(stmt, ast.Expr) and isinstance(stmt.value, (ast.Str, ast.Ellipsis)) ): continue # docstring or ... elif isinstance(stmt, ast.Pass): continue # pass elif ( isinstance(stmt, ast.Raise) and stmt.cause is None and ( ( isinstance(stmt.exc, ast.Name) and stmt.exc.id in STUB_EXCEPTIONS ) or ( isinstance(stmt.exc, ast.Call) and isinstance(stmt.exc.func, ast.Name) and stmt.exc.func.id in STUB_EXCEPTIONS ) ) ): continue # raise NotImplementedError else: return False else: return True
Example #21
Source File: pyupgrade.py From pyupgrade with MIT License | 5 votes |
def _unparse(node: ast.expr) -> str: if isinstance(node, ast.Name): return node.id elif isinstance(node, ast.Attribute): return ''.join((_unparse(node.value), '.', node.attr)) elif isinstance(node, ast.Call): return '{}()'.format(_unparse(node.func)) elif isinstance(node, ast.Subscript): if sys.version_info >= (3, 9): # pragma: no cover (py39+) # https://github.com/python/typeshed/pull/3950 node_slice: ast.expr = node.slice # type: ignore elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39) node_slice = node.slice.value else: raise AssertionError(f'expected Slice: {ast.dump(node)}') if isinstance(node_slice, ast.Tuple): if len(node_slice.elts) == 1: slice_s = f'{_unparse(node_slice.elts[0])},' else: slice_s = ', '.join(_unparse(elt) for elt in node_slice.elts) else: slice_s = _unparse(node_slice) return '{}[{}]'.format(_unparse(node.value), slice_s) elif isinstance(node, ast.Str): return repr(node.s) elif isinstance(node, ast.Ellipsis): return '...' elif isinstance(node, ast.List): return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts)) elif isinstance(node, ast.NameConstant): return repr(node.value) else: raise NotImplementedError(ast.dump(node))
Example #22
Source File: test_context.py From bandit with Apache License 2.0 | 4 votes |
def test__get_literal_value(self): new_context = context.Context() value = ast.Num(42) expected = value.n self.assertEqual(expected, new_context._get_literal_value(value)) value = ast.Str('spam') expected = value.s self.assertEqual(expected, new_context._get_literal_value(value)) value = ast.List([ast.Str('spam'), ast.Num(42)], ast.Load()) expected = [ast.Str('spam').s, ast.Num(42).n] self.assertListEqual(expected, new_context._get_literal_value(value)) value = ast.Tuple([ast.Str('spam'), ast.Num(42)], ast.Load()) expected = (ast.Str('spam').s, ast.Num(42).n) self.assertTupleEqual(expected, new_context._get_literal_value(value)) value = ast.Set([ast.Str('spam'), ast.Num(42)]) expected = set([ast.Str('spam').s, ast.Num(42).n]) self.assertSetEqual(expected, new_context._get_literal_value(value)) value = ast.Dict(['spam', 'eggs'], [42, 'foo']) expected = dict(spam=42, eggs='foo') self.assertDictEqual(expected, new_context._get_literal_value(value)) value = ast.Ellipsis() self.assertIsNone(new_context._get_literal_value(value)) value = ast.Name('spam', ast.Load()) expected = value.id self.assertEqual(expected, new_context._get_literal_value(value)) if six.PY3: value = ast.NameConstant(True) expected = str(value.value) self.assertEqual(expected, new_context._get_literal_value(value)) if six.PY3: value = ast.Bytes(b'spam') expected = value.s self.assertEqual(expected, new_context._get_literal_value(value)) self.assertIsNone(new_context._get_literal_value(None))
Example #23
Source File: context.py From bandit with Apache License 2.0 | 4 votes |
def _get_literal_value(self, literal): '''Utility function to turn AST literals into native Python types :param literal: The AST literal to convert :return: The value of the AST literal ''' if isinstance(literal, ast.Num): literal_value = literal.n elif isinstance(literal, ast.Str): literal_value = literal.s elif isinstance(literal, ast.List): return_list = list() for li in literal.elts: return_list.append(self._get_literal_value(li)) literal_value = return_list elif isinstance(literal, ast.Tuple): return_tuple = tuple() for ti in literal.elts: return_tuple = return_tuple + (self._get_literal_value(ti),) literal_value = return_tuple elif isinstance(literal, ast.Set): return_set = set() for si in literal.elts: return_set.add(self._get_literal_value(si)) literal_value = return_set elif isinstance(literal, ast.Dict): literal_value = dict(zip(literal.keys, literal.values)) elif isinstance(literal, ast.Ellipsis): # what do we want to do with this? literal_value = None elif isinstance(literal, ast.Name): literal_value = literal.id # NOTE(sigmavirus24): NameConstants are only part of the AST in Python # 3. NameConstants tend to refer to things like True and False. This # prevents them from being re-assigned in Python 3. elif six.PY3 and isinstance(literal, ast.NameConstant): literal_value = str(literal.value) # NOTE(sigmavirus24): Bytes are only part of the AST in Python 3 elif six.PY3 and isinstance(literal, ast.Bytes): literal_value = literal.s else: literal_value = None return literal_value