2 This is the syntax tree for Python 3 syntaxes. The classes represent
3 syntax elements like functions and imports.
5 All of the nodes can be traced back to the `Python grammar file
6 <https://docs.python.org/3/reference/grammar.html>`_. If you want to know how
7 a tree is structured, just analyse that file (for each Python version it's a
10 There's a lot of logic here that makes it easier for Jedi (and other libraries)
11 to deal with a Python syntax tree.
13 By using :py:meth:`parso.tree.NodeOrLeaf.get_code` on a module, you can get
14 back the 1-to-1 representation of the input given to the parser. This is
15 important if you want to refactor a parser tree.
17 >>> from parso import parse
18 >>> parser = parse('import os')
19 >>> module = parser.get_root_node()
23 Any subclasses of :class:`Scope`, including :class:`Module` has an attribute
24 :attr:`iter_imports <Scope.iter_imports>`:
26 >>> list(module.iter_imports())
27 [<ImportName: import os@1,0>]
29 Changes to the Python Grammar
30 -----------------------------
32 A few things have changed when looking at Python grammar files:
34 - :class:`Param` does not exist in Python grammar files. It is essentially a
35 part of a ``parameters`` node. |parso| splits it up to make it easier to
36 analyse parameters. However this just makes it easier to deal with the syntax
37 tree, it doesn't actually change the valid syntax.
38 - A few nodes like `lambdef` and `lambdef_nocond` have been merged in the
39 syntax tree to make it easier to do deal with them.
47 from collections
.abc
import Mapping
49 from collections
import Mapping
50 from typing
import Tuple
52 from parso
.tree
import Node
, BaseNode
, Leaf
, ErrorNode
, ErrorLeaf
, search_ancestor
# noqa
53 from parso
.python
.prefix
import split_prefix
54 from parso
.utils
import split_lines
56 _FLOW_CONTAINERS
= set(['if_stmt', 'while_stmt', 'for_stmt', 'try_stmt',
57 'with_stmt', 'async_stmt', 'suite'])
58 _RETURN_STMT_CONTAINERS
= set(['suite', 'simple_stmt']) | _FLOW_CONTAINERS
60 _FUNC_CONTAINERS
= set(
61 ['suite', 'simple_stmt', 'decorated', 'async_funcdef']
64 _GET_DEFINITION_TYPES
= set([
65 'expr_stmt', 'sync_comp_for', 'with_stmt', 'for_stmt', 'import_name',
66 'import_from', 'param', 'del_stmt', 'namedexpr_test',
68 _IMPORTS
= set(['import_name', 'import_from'])
74 def get_doc_node(self
):
76 Returns the string leaf of a docstring. e.g. ``r'''foo'''``.
78 if self
.type == 'file_input':
79 node
= self
.children
[0]
80 elif self
.type in ('funcdef', 'classdef'):
81 node
= self
.children
[self
.children
.index(':') + 1]
82 if node
.type == 'suite': # Normally a suite
83 node
= node
.children
[1] # -> NEWLINE stmt
85 simple_stmt
= self
.parent
86 c
= simple_stmt
.parent
.children
87 index
= c
.index(simple_stmt
)
92 if node
.type == 'simple_stmt':
93 node
= node
.children
[0]
94 if node
.type == 'string':
101 Some Python specific utilities.
105 def get_name_of_position(self
, position
):
107 Given a (line, column) tuple, returns a :py:class:`Name` or ``None`` if
108 there is no name at that position.
110 for c
in self
.children
:
111 if isinstance(c
, Leaf
):
112 if c
.type == 'name' and c
.start_pos
<= position
<= c
.end_pos
:
115 result
= c
.get_name_of_position(position
)
116 if result
is not None:
121 class PythonLeaf(PythonMixin
, Leaf
):
124 def _split_prefix(self
):
125 return split_prefix(self
, self
.get_start_pos_of_prefix())
127 def get_start_pos_of_prefix(self
):
129 Basically calls :py:meth:`parso.tree.NodeOrLeaf.get_start_pos_of_prefix`.
131 # TODO it is really ugly that we have to override it. Maybe change
132 # indent error leafs somehow? No idea how, though.
133 previous_leaf
= self
.get_previous_leaf()
134 if previous_leaf
is not None and previous_leaf
.type == 'error_leaf' \
135 and previous_leaf
.token_type
in ('INDENT', 'DEDENT', 'ERROR_DEDENT'):
136 previous_leaf
= previous_leaf
.get_previous_leaf()
138 if previous_leaf
is None: # It's the first leaf.
139 lines
= split_lines(self
.prefix
)
140 # + 1 is needed because split_lines always returns at least [''].
141 return self
.line
- len(lines
) + 1, 0 # It's the first leaf.
142 return previous_leaf
.end_pos
145 class _LeafWithoutNewlines(PythonLeaf
):
147 Simply here to optimize performance.
152 def end_pos(self
) -> Tuple
[int, int]:
153 return self
.line
, self
.column
+ len(self
.value
)
156 # Python base classes
157 class PythonBaseNode(PythonMixin
, BaseNode
):
161 class PythonNode(PythonMixin
, Node
):
165 class PythonErrorNode(PythonMixin
, ErrorNode
):
169 class PythonErrorLeaf(ErrorLeaf
, PythonLeaf
):
173 class EndMarker(_LeafWithoutNewlines
):
178 return "<%s: prefix=%s end_pos=%s>" % (
179 type(self
).__name
__, repr(self
.prefix
), self
.end_pos
183 class Newline(PythonLeaf
):
184 """Contains NEWLINE and ENDMARKER tokens."""
189 return "<%s: %s>" % (type(self
).__name
__, repr(self
.value
))
192 class Name(_LeafWithoutNewlines
):
194 A string. Sometimes it is important to know if the string belongs to a name
201 return "<%s: %s@%s,%s>" % (type(self
).__name
__, self
.value
,
202 self
.line
, self
.column
)
204 def is_definition(self
, include_setitem
=False):
206 Returns True if the name is being defined.
208 return self
.get_definition(include_setitem
=include_setitem
) is not None
210 def get_definition(self
, import_name_always
=False, include_setitem
=False):
212 Returns None if there's no definition for a name.
214 :param import_name_always: Specifies if an import name is always a
215 definition. Normally foo in `from foo import bar` is not a
221 if type_
in ('funcdef', 'classdef'):
222 if self
== node
.name
:
226 if type_
== 'except_clause':
227 if self
.get_previous_sibling() == 'as':
228 return node
.parent
# The try_stmt.
231 while node
is not None:
232 if node
.type == 'suite':
234 if node
.type in _GET_DEFINITION_TYPES
:
235 if self
in node
.get_defined_names(include_setitem
):
237 if import_name_always
and node
.type in _IMPORTS
:
244 class Literal(PythonLeaf
):
248 class Number(Literal
):
253 class String(Literal
):
258 def string_prefix(self
):
259 return re
.match(r
'\w*(?=[\'"])', self.value).group(0)
261 def _get_payload(self):
263 r'''('{3}|"{3}|
'|")(.*)$''',
267 return match.group(2)[:-len(match.group(1))]
270 class FStringString(PythonLeaf):
272 f-strings contain f-string expressions and normal python strings. These are
273 the string parts of f-strings.
275 type = 'fstring_string
'
279 class FStringStart(PythonLeaf):
281 f-strings contain f-string expressions and normal python strings. These are
282 the string parts of f-strings.
284 type = 'fstring_start
'
288 class FStringEnd(PythonLeaf):
290 f-strings contain f-string expressions and normal python strings. These are
291 the string parts of f-strings.
297 class _StringComparisonMixin:
298 def __eq__(self, other):
300 Make comparisons with strings easy.
301 Improves the readability of the parser.
303 if isinstance(other, str):
304 return self.value == other
309 return hash(self.value)
312 class Operator(_LeafWithoutNewlines, _StringComparisonMixin):
317 class Keyword(_LeafWithoutNewlines, _StringComparisonMixin):
322 class Scope(PythonBaseNode, DocstringMixin):
324 Super class for the parser tree, which represents the state of a python
326 A Scope is either a function, class or lambda.
330 def __init__(self, children):
331 super().__init__(children)
333 def iter_funcdefs(self):
335 Returns a generator of `funcdef` nodes.
337 return self._search_in_scope('funcdef
')
339 def iter_classdefs(self):
341 Returns a generator of `classdef` nodes.
343 return self._search_in_scope('classdef
')
345 def iter_imports(self):
347 Returns a generator of `import_name` and `import_from` nodes.
349 return self._search_in_scope('import_name
', 'import_from
')
351 def _search_in_scope(self, *names):
353 for element in children:
354 if element.type in names:
356 if element.type in _FUNC_CONTAINERS:
357 yield from scan(element.children)
359 return scan(self.children)
363 Returns the part that is executed by the function.
365 return self.children[-1]
369 name = self.name.value
370 except AttributeError:
373 return "<%s: %s@%s-%s>" % (type(self).__name__, name,
374 self.start_pos[0], self.end_pos[0])
379 The top scope, which is always a module.
380 Depending on the underlying parser this may be a full module or just a part
383 __slots__ = ('_used_names
',)
386 def __init__(self, children):
387 super().__init__(children)
388 self._used_names = None
390 def _iter_future_import_names(self):
392 :return: A list of future import names.
395 # In Python it's
not allowed to use future imports after the first
396 # actual (non-future) statement. However this is not a linter here,
397 # just return all future imports. If people want to scan for issues
398 # they should use the API.
399 for imp
in self
.iter_imports():
400 if imp
.type == 'import_from' and imp
.level
== 0:
401 for path
in imp
.get_paths():
402 names
= [name
.value
for name
in path
]
403 if len(names
) == 2 and names
[0] == '__future__':
406 def get_used_names(self
):
408 Returns all the :class:`Name` leafs that exist in this module. This
409 includes both definitions and references of names.
411 if self
._used
_names
is None:
412 # Don't directly use self._used_names to eliminate a lookup.
417 children
= node
.children
418 except AttributeError:
419 if node
.type == 'name':
420 arr
= dct
.setdefault(node
.value
, [])
423 for child
in children
:
427 self
._used
_names
= UsedNamesMapping(dct
)
428 return self
._used
_names
431 class Decorator(PythonBaseNode
):
436 class ClassOrFunc(Scope
):
442 Returns the `Name` leaf that defines the function or class name.
444 return self
.children
[1]
446 def get_decorators(self
):
448 :rtype: list of :class:`Decorator`
450 decorated
= self
.parent
451 if decorated
.type == 'async_funcdef':
452 decorated
= decorated
.parent
454 if decorated
.type == 'decorated':
455 if decorated
.children
[0].type == 'decorators':
456 return decorated
.children
[0].children
458 return decorated
.children
[:1]
463 class Class(ClassOrFunc
):
465 Used to store the parsed contents of a python class.
470 def __init__(self
, children
):
471 super().__init
__(children
)
473 def get_super_arglist(self
):
475 Returns the `arglist` node that defines the super classes. It returns
476 None if there are no arguments.
478 if self
.children
[2] != '(': # Has no parentheses
481 if self
.children
[3] == ')': # Empty parentheses
484 return self
.children
[3]
487 def _create_params(parent
, argslist_list
):
489 `argslist_list` is a list that can contain an argslist as a first item, but
490 most not. It's basically the items between the parameter brackets (which is
492 This function modifies the parser structure. It generates `Param` objects
493 from the normal ast. Those param objects do not exist in a normal ast, but
494 make the evaluation of the ast tree so much easier.
495 You could also say that this function replaces the argslist node with a
496 list of Param objects.
499 first
= argslist_list
[0]
503 if first
.type in ('name', 'fpdef'):
504 return [Param([first
], parent
)]
507 else: # argslist is a `typedargslist` or a `varargslist`.
508 if first
.type == 'tfpdef':
511 children
= first
.children
514 # Start with offset 1, because the end is higher.
515 for end
, child
in enumerate(children
+ [None], 1):
516 if child
is None or child
== ',':
517 param_children
= children
[start
:end
]
518 if param_children
: # Could as well be comma and then end.
519 if param_children
[0] == '*' \
520 and (len(param_children
) == 1
521 or param_children
[1] == ',') \
522 or param_children
[0] == '/':
523 for p
in param_children
:
525 new_children
+= param_children
527 new_children
.append(Param(param_children
, parent
))
532 class Function(ClassOrFunc
):
534 Used to store the parsed contents of a python function.
540 2. parameter list (including open-paren and close-paren <Operator>s)
541 3. or 5. <Operator: :>
542 4. or 6. Node() representing function body
543 3. -> (if annotation is also present)
544 4. annotation (if present)
548 def __init__(self
, children
):
549 super().__init
__(children
)
550 parameters
= self
.children
[2] # After `def foo`
551 parameters_children
= parameters
.children
[1:-1]
552 # If input parameters list already has Param objects, keep it as is;
553 # otherwise, convert it to a list of Param objects.
554 if not any(isinstance(child
, Param
) for child
in parameters_children
):
555 parameters
.children
[1:-1] = _create_params(parameters
, parameters_children
)
557 def _get_param_nodes(self
):
558 return self
.children
[2].children
560 def get_params(self
):
562 Returns a list of `Param()`.
564 return [p
for p
in self
._get
_param
_nodes
() if p
.type == 'param']
568 return self
.children
[1] # First token after `def`
570 def iter_yield_exprs(self
):
572 Returns a generator of `yield_expr`.
575 for element
in children
:
576 if element
.type in ('classdef', 'funcdef', 'lambdef'):
580 nested_children
= element
.children
581 except AttributeError:
582 if element
.value
== 'yield':
583 if element
.parent
.type == 'yield_expr':
588 yield from scan(nested_children
)
590 return scan(self
.children
)
592 def iter_return_stmts(self
):
594 Returns a generator of `return_stmt`.
597 for element
in children
:
598 if element
.type == 'return_stmt' \
599 or element
.type == 'keyword' and element
.value
== 'return':
601 if element
.type in _RETURN_STMT_CONTAINERS
:
602 yield from scan(element
.children
)
604 return scan(self
.children
)
606 def iter_raise_stmts(self
):
608 Returns a generator of `raise_stmt`. Includes raise statements inside try-except blocks
611 for element
in children
:
612 if element
.type == 'raise_stmt' \
613 or element
.type == 'keyword' and element
.value
== 'raise':
615 if element
.type in _RETURN_STMT_CONTAINERS
:
616 yield from scan(element
.children
)
618 return scan(self
.children
)
620 def is_generator(self
):
622 :return bool: Checks if a function is a generator or not.
624 return next(self
.iter_yield_exprs(), None) is not None
627 def annotation(self
):
629 Returns the test node after `->` or `None` if there is no annotation.
632 if self
.children
[3] == "->":
633 return self
.children
[4]
634 assert self
.children
[3] == ":"
640 class Lambda(Function
):
642 Lambdas are basically trimmed functions, so give it the same interface.
647 *. <Param x> for each argument x
649 -1. Node() representing body
654 def __init__(self
, children
):
655 # We don't want to call the Function constructor, call its parent.
656 super(Function
, self
).__init
__(children
)
657 # Everything between `lambda` and the `:` operator is a parameter.
658 parameters_children
= self
.children
[1:-2]
659 # If input children list already has Param objects, keep it as is;
660 # otherwise, convert it to a list of Param objects.
661 if not any(isinstance(child
, Param
) for child
in parameters_children
):
662 self
.children
[1:-2] = _create_params(self
, parameters_children
)
667 Raises an AttributeError. Lambdas don't have a defined name.
669 raise AttributeError("lambda is not named.")
671 def _get_param_nodes(self
):
672 return self
.children
[1:-2]
675 def annotation(self
):
677 Returns `None`, lambdas don't have annotations.
682 return "<%s@%s>" % (self
.__class
__.__name
__, self
.start_pos
)
685 class Flow(PythonBaseNode
):
693 def get_test_nodes(self
):
695 E.g. returns all the `test` nodes that are named as x, below:
702 for i
, c
in enumerate(self
.children
):
703 if c
in ('elif', 'if'):
704 yield self
.children
[i
+ 1]
706 def get_corresponding_test_node(self
, node
):
708 Searches for the branch in which the node is and returns the
709 corresponding test node (see function above). However if the node is in
710 the test node itself and not in the suite return None.
712 start_pos
= node
.start_pos
713 for check_node
in reversed(list(self
.get_test_nodes())):
714 if check_node
.start_pos
< start_pos
:
715 if start_pos
< check_node
.end_pos
:
717 # In this case the node is within the check_node itself,
722 def is_node_after_else(self
, node
):
724 Checks if a node is defined after `else`.
726 for c
in self
.children
:
728 if node
.start_pos
> c
.start_pos
:
734 class WhileStmt(Flow
):
743 def get_testlist(self
):
745 Returns the input node ``y`` from: ``for x in y:``.
747 return self
.children
[3]
749 def get_defined_names(self
, include_setitem
=False):
750 return _defined_names(self
.children
[1], include_setitem
)
757 def get_except_clause_tests(self
):
759 Returns the ``test`` nodes found in ``except_clause`` nodes.
760 Returns ``[None]`` for except clauses without an exception given.
762 for node
in self
.children
:
763 if node
.type == 'except_clause':
764 yield node
.children
[1]
765 elif node
== 'except':
769 class WithStmt(Flow
):
773 def get_defined_names(self
, include_setitem
=False):
775 Returns the a list of `Name` that the with statement defines. The
776 defined names are set after `as`.
779 for with_item
in self
.children
[1:-2:2]:
780 # Check with items for 'as' names.
781 if with_item
.type == 'with_item':
782 names
+= _defined_names(with_item
.children
[2], include_setitem
)
785 def get_test_node_from_name(self
, name
):
786 node
= name
.search_ancestor("with_item")
788 raise ValueError('The name is not actually part of a with statement.')
789 return node
.children
[0]
792 class Import(PythonBaseNode
):
795 def get_path_for_name(self
, name
):
797 The path is the list of names that leads to the searched name.
799 :return list of Name:
802 # The name may be an alias. If it is, just map it back to the name.
803 name
= self
._aliases
()[name
]
807 for path
in self
.get_paths():
809 return path
[:path
.index(name
) + 1]
810 raise ValueError('Name should be defined in the import itself')
813 return False # By default, sub classes may overwrite this behavior
815 def is_star_import(self
):
816 return self
.children
[-1] == '*'
819 class ImportFrom(Import
):
823 def get_defined_names(self
, include_setitem
=False):
825 Returns the a list of `Name` that the import defines. The
826 defined names are set after `import` or in case an alias - `as` - is
827 present that name is returned.
829 return [alias
or name
for name
, alias
in self
._as
_name
_tuples
()]
832 """Mapping from alias to its corresponding name."""
833 return dict((alias
, name
) for name
, alias
in self
._as
_name
_tuples
()
834 if alias
is not None)
836 def get_from_names(self
):
837 for n
in self
.children
[1:]:
838 if n
not in ('.', '...'):
840 if n
.type == 'dotted_name': # from x.y import
841 return n
.children
[::2]
842 elif n
== 'import': # from . import
844 else: # from x import
849 """The level parameter of ``__import__``."""
851 for n
in self
.children
[1:]:
852 if n
in ('.', '...'):
853 level
+= len(n
.value
)
858 def _as_name_tuples(self
):
859 last
= self
.children
[-1]
861 last
= self
.children
[-2]
863 return # No names defined directly.
865 if last
.type == 'import_as_names':
866 as_names
= last
.children
[::2]
869 for as_name
in as_names
:
870 if as_name
.type == 'name':
873 yield as_name
.children
[::2] # yields x, y -> ``x as y``
877 The import paths defined in an import statement. Typically an array
878 like this: ``[<Name: datetime>, <Name: date>]``.
880 :return list of list of Name:
882 dotted
= self
.get_from_names()
884 if self
.children
[-1] == '*':
886 return [dotted
+ [name
] for name
, alias
in self
._as
_name
_tuples
()]
889 class ImportName(Import
):
890 """For ``import_name`` nodes. Covers normal imports without ``from``."""
894 def get_defined_names(self
, include_setitem
=False):
896 Returns the a list of `Name` that the import defines. The defined names
897 is always the first name after `import` or in case an alias - `as` - is
898 present that name is returned.
900 return [alias
or path
[0] for path
, alias
in self
._dotted
_as
_names
()]
904 """The level parameter of ``__import__``."""
905 return 0 # Obviously 0 for imports without from.
908 return [path
for path
, alias
in self
._dotted
_as
_names
()]
910 def _dotted_as_names(self
):
911 """Generator of (list(path), alias) where alias may be None."""
912 dotted_as_names
= self
.children
[1]
913 if dotted_as_names
.type == 'dotted_as_names':
914 as_names
= dotted_as_names
.children
[::2]
916 as_names
= [dotted_as_names
]
918 for as_name
in as_names
:
919 if as_name
.type == 'dotted_as_name':
920 alias
= as_name
.children
[2]
921 as_name
= as_name
.children
[0]
924 if as_name
.type == 'name':
925 yield [as_name
], alias
928 yield as_name
.children
[::2], alias
932 This checks for the special case of nested imports, without aliases and
937 return bool([1 for path
, alias
in self
._dotted
_as
_names
()
938 if alias
is None and len(path
) > 1])
942 :return list of Name: Returns all the alias
944 return dict((alias
, path
[-1]) for path
, alias
in self
._dotted
_as
_names
()
945 if alias
is not None)
948 class KeywordStatement(PythonBaseNode
):
950 For the following statements: `assert`, `del`, `global`, `nonlocal`,
951 `raise`, `return`, `yield`.
953 `pass`, `continue` and `break` are not in there, because they are just
954 simple keywords and the parser reduces it to a keyword.
961 Keyword statements start with the keyword and end with `_stmt`. You can
962 crosscheck this with the Python grammar.
964 return '%s_stmt' % self
.keyword
968 return self
.children
[0].value
970 def get_defined_names(self
, include_setitem
=False):
971 keyword
= self
.keyword
973 return _defined_names(self
.children
[1], include_setitem
)
974 if keyword
in ('global', 'nonlocal'):
975 return self
.children
[1::2]
979 class AssertStmt(KeywordStatement
):
984 return self
.children
[1]
987 class GlobalStmt(KeywordStatement
):
990 def get_global_names(self
):
991 return self
.children
[1::2]
994 class ReturnStmt(KeywordStatement
):
998 class YieldExpr(PythonBaseNode
):
1003 def _defined_names(current
, include_setitem
):
1005 A helper function to find the defined names in statements, for loops and
1006 list comprehensions.
1009 if current
.type in ('testlist_star_expr', 'testlist_comp', 'exprlist', 'testlist'):
1010 for child
in current
.children
[::2]:
1011 names
+= _defined_names(child
, include_setitem
)
1012 elif current
.type in ('atom', 'star_expr'):
1013 names
+= _defined_names(current
.children
[1], include_setitem
)
1014 elif current
.type in ('power', 'atom_expr'):
1015 if current
.children
[-2] != '**': # Just if there's no operation
1016 trailer
= current
.children
[-1]
1017 if trailer
.children
[0] == '.':
1018 names
.append(trailer
.children
[1])
1019 elif trailer
.children
[0] == '[' and include_setitem
:
1020 for node
in current
.children
[-2::-1]:
1021 if node
.type == 'trailer':
1022 names
.append(node
.children
[1])
1024 if node
.type == 'name':
1028 names
.append(current
)
1032 class ExprStmt(PythonBaseNode
, DocstringMixin
):
1036 def get_defined_names(self
, include_setitem
=False):
1038 Returns a list of `Name` defined before the `=` sign.
1041 if self
.children
[1].type == 'annassign':
1042 names
= _defined_names(self
.children
[0], include_setitem
)
1045 for i
in range(0, len(self
.children
) - 2, 2)
1046 if '=' in self
.children
[i
+ 1].value
1047 for name
in _defined_names(self
.children
[i
], include_setitem
)
1051 """Returns the right-hand-side of the equals."""
1052 node
= self
.children
[-1]
1053 if node
.type == 'annassign':
1054 if len(node
.children
) == 4:
1055 node
= node
.children
[3]
1057 node
= node
.children
[1]
1060 def yield_operators(self
):
1062 Returns a generator of `+=`, `=`, etc. or None if there is no operation.
1064 first
= self
.children
[1]
1065 if first
.type == 'annassign':
1066 if len(first
.children
) <= 2:
1067 return # No operator is available, it's just PEP 484.
1069 first
= first
.children
[2]
1072 yield from self
.children
[3::2]
1075 class NamedExpr(PythonBaseNode
):
1076 type = 'namedexpr_test'
1078 def get_defined_names(self
, include_setitem
=False):
1079 return _defined_names(self
.children
[0], include_setitem
)
1082 class Param(PythonBaseNode
):
1084 It's a helper class that makes business logic with params much easier. The
1085 Python grammar defines no ``param`` node. It defines it in a different way
1086 that is not really suited to working with parameters.
1090 def __init__(self
, children
, parent
=None):
1091 super().__init
__(children
)
1092 self
.parent
= parent
1095 def star_count(self
):
1097 Is `0` in case of `foo`, `1` in case of `*foo` or `2` in case of
1100 first
= self
.children
[0]
1101 if first
in ('*', '**'):
1102 return len(first
.value
)
1108 The default is the test node that appears after the `=`. Is `None` in
1109 case no default is present.
1111 has_comma
= self
.children
[-1] == ','
1113 if self
.children
[-2 - int(has_comma
)] == '=':
1114 return self
.children
[-1 - int(has_comma
)]
1119 def annotation(self
):
1121 The default is the test node that appears after `:`. Is `None` in case
1122 no annotation is present.
1124 tfpdef
= self
._tfpdef
()
1125 if tfpdef
.type == 'tfpdef':
1126 assert tfpdef
.children
[1] == ":"
1127 assert len(tfpdef
.children
) == 3
1128 annotation
= tfpdef
.children
[2]
1135 tfpdef: see e.g. grammar36.txt.
1137 offset
= int(self
.children
[0] in ('*', '**'))
1138 return self
.children
[offset
]
1143 The `Name` leaf of the param.
1145 if self
._tfpdef
().type == 'tfpdef':
1146 return self
._tfpdef
().children
[0]
1148 return self
._tfpdef
()
1150 def get_defined_names(self
, include_setitem
=False):
1154 def position_index(self
):
1156 Property for the positional index of a paramter.
1158 index
= self
.parent
.children
.index(self
)
1160 keyword_only_index
= self
.parent
.children
.index('*')
1161 if index
> keyword_only_index
:
1167 keyword_only_index
= self
.parent
.children
.index('/')
1168 if index
> keyword_only_index
:
1175 def get_parent_function(self
):
1177 Returns the function/lambda of a parameter.
1179 return self
.search_ancestor('funcdef', 'lambdef')
1181 def get_code(self
, include_prefix
=True, include_comma
=True):
1183 Like all the other get_code functions, but includes the param
1186 :param include_comma bool: If enabled includes the comma in the string output.
1189 return super().get_code(include_prefix
)
1191 children
= self
.children
1192 if children
[-1] == ',':
1193 children
= children
[:-1]
1194 return self
._get
_code
_for
_children
(
1196 include_prefix
=include_prefix
1200 default
= '' if self
.default
is None else '=%s' % self
.default
.get_code()
1201 return '<%s: %s>' % (type(self
).__name
__, str(self
._tfpdef
()) + default
)
1204 class SyncCompFor(PythonBaseNode
):
1205 type = 'sync_comp_for'
1208 def get_defined_names(self
, include_setitem
=False):
1210 Returns the a list of `Name` that the comprehension defines.
1213 return _defined_names(self
.children
[1], include_setitem
)
1216 # This is simply here so an older Jedi version can work with this new parso
1217 # version. Can be deleted in the next release.
1218 CompFor
= SyncCompFor
1221 class UsedNamesMapping(Mapping
):
1223 This class exists for the sole purpose of creating an immutable dict.
1225 def __init__(self
, dct
):
1228 def __getitem__(self
, key
):
1229 return self
._dict
[key
]
1232 return len(self
._dict
)
1235 return iter(self
._dict
)
1240 def __eq__(self
, other
):
1241 # Comparing these dicts does not make sense.
1242 return self
is other