summaryrefslogtreecommitdiff
path: root/astroid
diff options
context:
space:
mode:
authorCeridwen <ceridwenv@gmail.com>2016-03-02 10:47:46 -0500
committerCeridwen <ceridwenv@gmail.com>2016-03-02 10:47:46 -0500
commit229e5c448bc94b27fd47923a6e4093f5f6135853 (patch)
tree61322b1c369cc1b54444f77155bf7d1157ba2ae7 /astroid
parent51bd977f064520f5efe2795e484d2c0728128e08 (diff)
downloadastroid-git-229e5c448bc94b27fd47923a6e4093f5f6135853.tar.gz
Replace None with Empty in the ASTs and refactor the zipper tests to work with this
Diffstat (limited to 'astroid')
-rw-r--r--astroid/__init__.py3
-rw-r--r--astroid/brain/brain_builtin_inference.py2
-rw-r--r--astroid/inference.py2
-rw-r--r--astroid/raw_building.py2
-rw-r--r--astroid/tests/unittest_builder.py2
-rw-r--r--astroid/tests/unittest_inference.py2
-rw-r--r--astroid/tests/unittest_python3.py2
-rw-r--r--astroid/tests/unittest_zipper.py77
-rw-r--r--astroid/tree/base.py2
-rw-r--r--astroid/tree/node_classes.py248
-rw-r--r--astroid/tree/rebuilder.py62
-rw-r--r--astroid/tree/scoped_nodes.py50
-rw-r--r--astroid/tree/zipper.py6
13 files changed, 236 insertions, 224 deletions
diff --git a/astroid/__init__.py b/astroid/__init__.py
index efae8eca..3132300f 100644
--- a/astroid/__init__.py
+++ b/astroid/__init__.py
@@ -82,6 +82,9 @@ from astroid.interpreter.lookup import builtin_lookup
from astroid.builder import parse
from astroid.util import Uninferable, YES
+# ???
+from astroid.tree import zipper
+
# transform utilities (filters and decorator)
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index a3c95370..e8b43fd5 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -504,7 +504,7 @@ def infer_slice(node, context=None):
if len(args) < 3:
# Make sure we have 3 arguments.
- args.extend([None] * (3 - len(args)))
+ args.extend([nodes.Empty] * (3 - len(args)))
slice_node = nodes.Slice(lineno=node.lineno,
col_offset=node.col_offset,
diff --git a/astroid/inference.py b/astroid/inference.py
index e4074bc1..bc5f0469 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -212,7 +212,7 @@ def _slice_value(index, context=None):
if isinstance(index, treeabc.Const):
if isinstance(index.value, (int, type(None))):
return index.value
- elif index is None:
+ elif isinstance(index, treeabc.Empty):
return None
else:
# Try to infer what the index actually is.
diff --git a/astroid/raw_building.py b/astroid/raw_building.py
index bccd83da..b11cef18 100644
--- a/astroid/raw_building.py
+++ b/astroid/raw_building.py
@@ -371,7 +371,7 @@ def ast_from_function(func, built_objects, module, name=None, parent=None):
vararg = _extract_vararg(python_vararg, args_node)
kwarg = _extract_vararg(python_kwarg, args_node)
- returns = None
+ returns = node_classes.Empty
if signature.return_annotation is not _Parameter.empty:
returns = _ast_from_object(signature.return_annotation,
built_objects,
diff --git a/astroid/tests/unittest_builder.py b/astroid/tests/unittest_builder.py
index 813c2e3d..e9008e51 100644
--- a/astroid/tests/unittest_builder.py
+++ b/astroid/tests/unittest_builder.py
@@ -597,7 +597,7 @@ class BuilderTest(unittest.TestCase):
none, nothing, chain = [ret.value for ret in astroid.body[0].body]
self.assertIsInstance(none, nodes.Const)
self.assertIsNone(none.value)
- self.assertIsNone(nothing)
+ self.assertIs(nothing, nodes.Empty)
self.assertIsInstance(chain, nodes.Const)
self.assertEqual(chain.value, 'None')
diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py
index 328b813b..24be70a6 100644
--- a/astroid/tests/unittest_inference.py
+++ b/astroid/tests/unittest_inference.py
@@ -2924,7 +2924,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.Slice)
self.assertEqual(inferred.lower.value, 1)
- self.assertIsNone(inferred.upper)
+ self.assertIs(inferred.upper, nodes.Empty)
def test_instance_slicing_fails(self):
ast_nodes = test_utils.extract_node('''
diff --git a/astroid/tests/unittest_python3.py b/astroid/tests/unittest_python3.py
index 3cd7b1f5..a2fc9c8a 100644
--- a/astroid/tests/unittest_python3.py
+++ b/astroid/tests/unittest_python3.py
@@ -213,7 +213,7 @@ class Python3TC(unittest.TestCase):
self.assertEqual(func.args.args[0].annotation.name, 'int')
self.assertIsInstance(func.args.args[1].annotation, Name)
self.assertEqual(func.args.args[1].annotation.name, 'str')
- self.assertIsNone(func.returns)
+ self.assertIs(func.returns, nodes.Empty)
@require_version('3.0')
def test_annotation_as_string(self):
diff --git a/astroid/tests/unittest_zipper.py b/astroid/tests/unittest_zipper.py
index 578146be..19926110 100644
--- a/astroid/tests/unittest_zipper.py
+++ b/astroid/tests/unittest_zipper.py
@@ -8,35 +8,55 @@ import hypothesis
from hypothesis import strategies
import astroid
+from astroid.tree import base
from astroid.tree import zipper
# This screens out the empty init files.
astroid_file = strategies.sampled_from(os.path.join(p, n) for p, _, ns in os.walk('astroid/') for n in ns if n.endswith('.py') and '__init__.py' not in n)
-MapNode = collections.namedtuple('MapNode', 'children parent moves')
+class ASTMap(dict):
+ def __repr__(self):
+ return repr(self[1])
+
+class AssignLabels(object):
+ Node = collections.namedtuple('Node', 'node children parent')
+ def __init__(self):
+ self.label = 1
+ def __call__(self, labels, node, parent_label=0):
+ label = self.label
+ self.label += 1
+ children = tuple(self(labels, c, label) for c in node)
+ labels[label] = self.Node(node, children, parent_label)
+ return label
+
+Node = collections.namedtuple('Node', 'node children parent edges')
+Edge = collections.namedtuple('Edge', 'label move')
def ast_from_file_name(name):
with open(name, 'r') as source_file:
- print(name)
+ # print(name)
root = astroid.parse(source_file.read())
- to_visit = [(root, None)]
- ast = {}
+ ast = ASTMap()
+ AssignLabels()(ast, root)
+ to_visit = [1]
while to_visit:
- node, parent = to_visit.pop()
- children = tuple(iter(node)) if node else ()
- to_visit.extend((c, node) for c in children)
- moves = []
+ label = to_visit.pop()
+ children = ast[label].children
+ parent = ast[label].parent
+ to_visit.extend(c for c in reversed(children))
+ edges = []
if children:
- moves.append(zipper.Zipper.down)
+ edges.append(Edge(children[0], zipper.Zipper.down))
if parent:
- moves.append(zipper.Zipper.up)
- index = ast[id(parent)].children.index(node)
+ edges.append(Edge(parent, zipper.Zipper.up))
+ siblings = ast[parent].children
+ index = siblings.index(label)
if index > 0:
- moves.append(zipper.Zipper.left)
- if index < len(ast[id(parent)].children) - 1:
- moves.append(zipper.Zipper.right)
- ast[id(node)] = MapNode(children, parent, tuple(moves))
+ edges.append(Edge(siblings[index - 1], zipper.Zipper.left))
+ if index < len(siblings) - 1:
+ edges.append(Edge(siblings[index + 1], zipper.Zipper.right))
+ ast[label] = Node(ast[label].node, children, parent, tuple(edges))
return ast, root
ast_strategy = strategies.builds(ast_from_file_name, astroid_file)
@@ -48,23 +68,18 @@ class TestZipper(unittest.TestCase):
@hypothesis.given(ast_strategy, strategies.integers(min_value=0, max_value=100), strategies.choices())
def test(self, ast_root, length, choice):
ast, root = ast_root
- old_position = zipper.Zipper(root)
+ hypothesis.note(str(root))
+ old_label = 1
+ old_zipper = zipper.Zipper(root)
for _ in range(length):
- move = choice(ast[id(old_position.__wrapped__)].moves)
- new_position = move(old_position)
- if move is zipper.Zipper.down:
- assert(new_position.__wrapped__ is next(iter(old_position)))
- if move is zipper.Zipper.up:
- assert(new_position.__wrapped__ is ast[id(old_position.__wrapped__)].parent)
- if move is zipper.Zipper.left or move is zipper.Zipper.right:
- parent = ast[id(old_position.__wrapped__)].parent
- siblings = ast[id(parent)].children
- index = siblings.index(old_position.__wrapped__)
- if move is zipper.Zipper.left:
- assert(new_position.__wrapped__ is siblings[index - 1])
- if move is zipper.Zipper.right:
- assert(new_position.__wrapped__ is siblings[index + 1])
- old_position = new_position
+ new_label, move = choice(ast[old_label].edges)
+ new_zipper = move(old_zipper)
+ hypothesis.note(new_zipper)
+ assert(isinstance(new_zipper.__wrapped__,
+ (base.NodeNG, collections.Sequence)))
+ assert(new_zipper.__wrapped__ is ast[new_label].node)
+ old_zipper = new_zipper
+ old_label = new_label
if __name__ == '__main__':
unittest.main()
diff --git a/astroid/tree/base.py b/astroid/tree/base.py
index dc5119e1..ff8f2a30 100644
--- a/astroid/tree/base.py
+++ b/astroid/tree/base.py
@@ -397,7 +397,7 @@ class NodeNG(object):
def _repr_node(node, result, done, cur_indent='', depth=1):
"""Outputs a strings representation of an astroid node."""
if node in done:
- result.append(indent + '<Recursion on %s with id=%s' %
+ result.append('<Recursion on %s with id=%s' %
(type(node).__name__, id(node)))
return False
else:
diff --git a/astroid/tree/node_classes.py b/astroid/tree/node_classes.py
index 7189b068..5f4df46e 100644
--- a/astroid/tree/node_classes.py
+++ b/astroid/tree/node_classes.py
@@ -109,6 +109,23 @@ class BaseAssignName(base.LookupMixIn, base.ParentAssignTypeMixin,
infer_lhs = inference.infer_name
+
+@object.__new__
+@util.register_implementation(treeabc.Empty)
+class Empty(base.NodeNG):
+ """Empty nodes represents the lack of something
+
+ For instance, they can be used to represent missing annotations
+ or defaults for arguments or anything where None is a valid
+ value.
+ """
+
+ def __bool__(self):
+ return False
+
+ __nonzero__ = __bool__
+
+
@util.register_implementation(treeabc.AssignName)
class AssignName(BaseAssignName):
"""class representing an AssignName node"""
@@ -283,13 +300,13 @@ class AssignAttr(base.ParentAssignTypeMixin,
"""class representing an AssignAttr node"""
_astroid_fields = ('expr',)
_other_fields = ('attrname',)
- expr = None
+ expr = Empty
def __init__(self, attrname=None, lineno=None, col_offset=None, parent=None):
self.attrname = attrname
super(AssignAttr, self).__init__(lineno, col_offset, parent)
- def postinit(self, expr=None):
+ def postinit(self, expr=Empty):
self.expr = expr
infer_lhs = inference.infer_attribute
@@ -299,10 +316,10 @@ class AssignAttr(base.ParentAssignTypeMixin,
class Assert(Statement):
"""class representing an Assert node"""
_astroid_fields = ('test', 'fail',)
- test = None
- fail = None
+ test = Empty
+ fail = Empty
- def postinit(self, test=None, fail=None):
+ def postinit(self, test=Empty, fail=Empty):
self.fail = fail
self.test = test
@@ -311,10 +328,10 @@ class Assert(Statement):
class Assign(base.AssignTypeMixin, AssignedStmtsMixin, Statement):
"""class representing an Assign node"""
_astroid_fields = ('targets', 'value',)
- targets = None
- value = None
+ targets = Empty
+ value = Empty
- def postinit(self, targets=None, value=None):
+ def postinit(self, targets=Empty, value=Empty):
self.targets = targets
self.value = value
@@ -324,14 +341,14 @@ class AugAssign(base.AssignTypeMixin, AssignedStmtsMixin, Statement):
"""class representing an AugAssign node"""
_astroid_fields = ('target', 'value')
_other_fields = ('op',)
- target = None
- value = None
+ target = Empty
+ value = Empty
def __init__(self, op=None, lineno=None, col_offset=None, parent=None):
self.op = op
super(AugAssign, self).__init__(lineno, col_offset, parent)
- def postinit(self, target=None, value=None):
+ def postinit(self, target=Empty, value=Empty):
self.target = target
self.value = value
@@ -357,9 +374,9 @@ class AugAssign(base.AssignTypeMixin, AssignedStmtsMixin, Statement):
class Repr(base.NodeNG):
"""class representing a Repr node"""
_astroid_fields = ('value',)
- value = None
+ value = Empty
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -368,14 +385,14 @@ class BinOp(base.NodeNG):
"""class representing a BinOp node"""
_astroid_fields = ('left', 'right')
_other_fields = ('op',)
- left = None
- right = None
+ left = Empty
+ right = Empty
def __init__(self, op=None, lineno=None, col_offset=None, parent=None):
self.op = op
super(BinOp, self).__init__(lineno, col_offset, parent)
- def postinit(self, left=None, right=None):
+ def postinit(self, left=Empty, right=Empty):
self.left = left
self.right = right
@@ -402,13 +419,13 @@ class BoolOp(base.NodeNG):
"""class representing a BoolOp node"""
_astroid_fields = ('values',)
_other_fields = ('op',)
- values = None
+ values = Empty
def __init__(self, op=None, lineno=None, col_offset=None, parent=None):
self.op = op
super(BoolOp, self).__init__(lineno, col_offset, parent)
- def postinit(self, values=None):
+ def postinit(self, values=Empty):
self.values = values
@@ -421,11 +438,11 @@ class Break(Statement):
class Call(base.NodeNG):
"""class representing a Call node"""
_astroid_fields = ('func', 'args', 'keywords')
- func = None
- args = None
- keywords = None
+ func = Empty
+ args = Empty
+ keywords = Empty
- def postinit(self, func=None, args=None, keywords=None):
+ def postinit(self, func=Empty, args=Empty, keywords=Empty):
self.func = func
self.args = args
self.keywords = keywords
@@ -438,7 +455,7 @@ class Call(base.NodeNG):
@property
def kwargs(self):
keywords = self.keywords or []
- return [keyword for keyword in keywords if keyword.arg is None]
+ return [keyword for keyword in keywords if keyword.arg is Empty]
@util.register_implementation(treeabc.Compare)
@@ -446,14 +463,15 @@ class Compare(base.NodeNG):
"""class representing a Compare node"""
_astroid_fields = ('left', 'comparators')
_other_fields = ('ops',)
- left = None
+ left = Empty
+ comparators = Empty
def __init__(self, ops, lineno=None, col_offset=None, parent=None):
self.comparators = []
self.ops = ops
super(Compare, self).__init__(lineno, col_offset, parent)
- def postinit(self, left=None, comparators=None):
+ def postinit(self, left=Empty, comparators=Empty):
self.left = left
self.comparators = comparators
@@ -472,14 +490,14 @@ class Compare(base.NodeNG):
class Comprehension(AssignedStmtsMixin, base.NodeNG):
"""class representing a Comprehension node"""
_astroid_fields = ('target', 'iter', 'ifs')
- target = None
- iter = None
- ifs = None
+ target = Empty
+ iter = Empty
+ ifs = Empty
def __init__(self, parent=None):
self.parent = parent
- def postinit(self, target=None, iter=None, ifs=None):
+ def postinit(self, target=Empty, iter=Empty, ifs=Empty):
self.target = target
self.iter = iter
self.ifs = ifs
@@ -580,7 +598,7 @@ class Continue(Statement):
class Decorators(base.NodeNG):
"""class representing a Decorators node"""
_astroid_fields = ('nodes',)
- nodes = None
+ nodes = Empty
def postinit(self, nodes):
self.nodes = nodes
@@ -591,13 +609,13 @@ class DelAttr(base.ParentAssignTypeMixin, base.NodeNG):
"""class representing a DelAttr node"""
_astroid_fields = ('expr',)
_other_fields = ('attrname',)
- expr = None
+ expr = Empty
def __init__(self, attrname=None, lineno=None, col_offset=None, parent=None):
self.attrname = attrname
super(DelAttr, self).__init__(lineno, col_offset, parent)
- def postinit(self, expr=None):
+ def postinit(self, expr=Empty):
self.expr = expr
@@ -605,9 +623,9 @@ class DelAttr(base.ParentAssignTypeMixin, base.NodeNG):
class Delete(base.AssignTypeMixin, Statement):
"""class representing a Delete node"""
_astroid_fields = ('targets',)
- targets = None
+ targets = Empty
- def postinit(self, targets=None):
+ def postinit(self, targets=Empty):
self.targets = targets
@@ -680,9 +698,9 @@ class Dict(base.NodeNG, objects.BaseInstance):
class Expr(Statement):
"""class representing a Expr node"""
_astroid_fields = ('value',)
- value = None
+ value = Empty
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -716,11 +734,11 @@ class InterpreterObject(base.NodeNG):
class ExceptHandler(base.AssignTypeMixin, AssignedStmtsMixin, Statement):
"""class representing an ExceptHandler node"""
_astroid_fields = ('type', 'name', 'body',)
- type = None
- name = None
- body = None
+ type = Empty
+ name = Empty
+ body = Empty
- def postinit(self, type=None, name=None, body=None):
+ def postinit(self, type=Empty, name=Empty, body=Empty):
self.type = type
self.name = name
self.body = body
@@ -746,11 +764,11 @@ class ExceptHandler(base.AssignTypeMixin, AssignedStmtsMixin, Statement):
class Exec(Statement):
"""class representing an Exec node"""
_astroid_fields = ('expr', 'globals', 'locals')
- expr = None
- globals = None
- locals = None
+ expr = Empty
+ globals = Empty
+ locals = Empty
- def postinit(self, expr=None, globals=None, locals=None):
+ def postinit(self, expr=Empty, globals=Empty, locals=Empty):
self.expr = expr
self.globals = globals
self.locals = locals
@@ -760,9 +778,9 @@ class Exec(Statement):
class ExtSlice(base.NodeNG):
"""class representing an ExtSlice node"""
_astroid_fields = ('dims',)
- dims = None
+ dims = Empty
- def postinit(self, dims=None):
+ def postinit(self, dims=Empty):
self.dims = dims
@@ -771,12 +789,12 @@ class For(base.BlockRangeMixIn, base.AssignTypeMixin,
AssignedStmtsMixin, Statement):
"""class representing a For node"""
_astroid_fields = ('target', 'iter', 'body', 'orelse',)
- target = None
- iter = None
- body = None
- orelse = None
+ target = Empty
+ iter = Empty
+ body = Empty
+ orelse = Empty
- def postinit(self, target=None, iter=None, body=None, orelse=None):
+ def postinit(self, target=Empty, iter=Empty, body=Empty, orelse=Empty):
self.target = target
self.iter = iter
self.body = body
@@ -798,9 +816,9 @@ class Await(base.NodeNG):
"""Await node for the `await` keyword."""
_astroid_fields = ('value', )
- value = None
+ value = Empty
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -825,13 +843,13 @@ class Attribute(base.NodeNG):
"""class representing a Attribute node"""
_astroid_fields = ('expr',)
_other_fields = ('attrname',)
- expr = None
+ expr = Empty
def __init__(self, attrname=None, lineno=None, col_offset=None, parent=None):
self.attrname = attrname
super(Attribute, self).__init__(lineno, col_offset, parent)
- def postinit(self, expr=None):
+ def postinit(self, expr=Empty):
self.expr = expr
@@ -852,11 +870,11 @@ class Global(Statement):
class If(base.BlockRangeMixIn, Statement):
"""class representing an If node"""
_astroid_fields = ('test', 'body', 'orelse')
- test = None
- body = None
- orelse = None
+ test = Empty
+ body = Empty
+ orelse = Empty
- def postinit(self, test=None, body=None, orelse=None):
+ def postinit(self, test=Empty, body=Empty, orelse=Empty):
self.test = test
self.body = body
self.orelse = orelse
@@ -879,11 +897,11 @@ class If(base.BlockRangeMixIn, Statement):
class IfExp(base.NodeNG):
"""class representing an IfExp node"""
_astroid_fields = ('test', 'body', 'orelse')
- test = None
- body = None
- orelse = None
+ test = Empty
+ body = Empty
+ orelse = Empty
- def postinit(self, test=None, body=None, orelse=None):
+ def postinit(self, test=Empty, body=Empty, orelse=Empty):
self.test = test
self.body = body
self.orelse = orelse
@@ -911,9 +929,9 @@ class Import(base.FilterStmtsMixin, Statement):
class Index(base.NodeNG):
"""class representing an Index node"""
_astroid_fields = ('value',)
- value = None
+ value = Empty
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -922,13 +940,13 @@ class Keyword(base.NodeNG):
"""class representing a Keyword node"""
_astroid_fields = ('value',)
_other_fields = ('arg',)
- value = None
+ value = Empty
def __init__(self, arg=None, lineno=None, col_offset=None, parent=None):
self.arg = arg
super(Keyword, self).__init__(lineno, col_offset, parent)
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -977,14 +995,14 @@ class Pass(Statement):
class Print(Statement):
"""class representing a Print node"""
_astroid_fields = ('dest', 'values',)
- dest = None
- values = None
+ dest = Empty
+ values = Empty
def __init__(self, nl=None, lineno=None, col_offset=None, parent=None):
self.nl = nl
super(Print, self).__init__(lineno, col_offset, parent)
- def postinit(self, dest=None, values=None):
+ def postinit(self, dest=Empty, values=Empty):
self.dest = dest
self.values = values
@@ -992,22 +1010,22 @@ class Print(Statement):
@util.register_implementation(treeabc.Raise)
class Raise(Statement):
"""class representing a Raise node"""
- exc = None
+ exc = Empty
if six.PY2:
_astroid_fields = ('exc', 'inst', 'tback')
- inst = None
- tback = None
+ inst = Empty
+ tback = Empty
- def postinit(self, exc=None, inst=None, tback=None):
+ def postinit(self, exc=Empty, inst=Empty, tback=Empty):
self.exc = exc
self.inst = inst
self.tback = tback
else:
_astroid_fields = ('exc', 'cause')
- exc = None
- cause = None
+ exc = Empty
+ cause = Empty
- def postinit(self, exc=None, cause=None):
+ def postinit(self, exc=Empty, cause=Empty):
self.exc = exc
self.cause = cause
@@ -1023,9 +1041,9 @@ class Raise(Statement):
class Return(Statement):
"""class representing a Return node"""
_astroid_fields = ('value',)
- value = None
+ value = Empty
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -1047,11 +1065,11 @@ class Set(base.BaseContainer, objects.BaseInstance):
class Slice(base.NodeNG):
"""class representing a Slice node"""
_astroid_fields = ('lower', 'upper', 'step')
- lower = None
- upper = None
- step = None
+ lower = Empty
+ upper = Empty
+ step = Empty
- def postinit(self, lower=None, upper=None, step=None):
+ def postinit(self, lower=Empty, upper=Empty, step=Empty):
self.lower = lower
self.upper = upper
self.step = step
@@ -1090,14 +1108,14 @@ class Starred(base.ParentAssignTypeMixin, AssignedStmtsMixin, base.NodeNG):
"""class representing a Starred node"""
_astroid_fields = ('value',)
_other_fields = ('ctx', )
- value = None
+ value = Empty
def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None):
self.ctx = ctx
super(Starred, self).__init__(lineno=lineno,
col_offset=col_offset, parent=parent)
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -1106,15 +1124,15 @@ class Subscript(base.NodeNG):
"""class representing a Subscript node"""
_astroid_fields = ('value', 'slice')
_other_fields = ('ctx', )
- value = None
- slice = None
+ value = Empty
+ slice = Empty
def __init__(self, ctx=None, lineno=None, col_offset=None, parent=None):
self.ctx = ctx
super(Subscript, self).__init__(lineno=lineno,
col_offset=col_offset, parent=parent)
- def postinit(self, value=None, slice=None):
+ def postinit(self, value=Empty, slice=Empty):
self.value = value
self.slice = slice
@@ -1125,11 +1143,11 @@ class Subscript(base.NodeNG):
class TryExcept(base.BlockRangeMixIn, Statement):
"""class representing a TryExcept node"""
_astroid_fields = ('body', 'handlers', 'orelse',)
- body = None
- handlers = None
- orelse = None
+ body = Empty
+ handlers = Empty
+ orelse = Empty
- def postinit(self, body=None, handlers=None, orelse=None):
+ def postinit(self, body=Empty, handlers=Empty, orelse=Empty):
self.body = body
self.handlers = handlers
self.orelse = orelse
@@ -1154,10 +1172,10 @@ class TryExcept(base.BlockRangeMixIn, Statement):
class TryFinally(base.BlockRangeMixIn, Statement):
"""class representing a TryFinally node"""
_astroid_fields = ('body', 'finalbody',)
- body = None
- finalbody = None
+ body = Empty
+ finalbody = Empty
- def postinit(self, body=None, finalbody=None):
+ def postinit(self, body=Empty, finalbody=Empty):
self.body = body
self.finalbody = finalbody
@@ -1200,13 +1218,13 @@ class UnaryOp(base.NodeNG):
"""class representing an UnaryOp node"""
_astroid_fields = ('operand',)
_other_fields = ('op',)
- operand = None
+ operand = Empty
def __init__(self, op=None, lineno=None, col_offset=None, parent=None):
self.op = op
super(UnaryOp, self).__init__(lineno, col_offset, parent)
- def postinit(self, operand=None):
+ def postinit(self, operand=Empty):
self.operand = operand
def _infer_unaryop(self, context=None):
@@ -1231,11 +1249,11 @@ class UnaryOp(base.NodeNG):
class While(base.BlockRangeMixIn, Statement):
"""class representing a While node"""
_astroid_fields = ('test', 'body', 'orelse',)
- test = None
- body = None
- orelse = None
+ test = Empty
+ body = Empty
+ orelse = Empty
- def postinit(self, test=None, body=None, orelse=None):
+ def postinit(self, test=Empty, body=Empty, orelse=Empty):
self.test = test
self.body = body
self.orelse = orelse
@@ -1260,7 +1278,7 @@ class With(base.BlockRangeMixIn, base.AssignTypeMixin,
self.body = []
super(With, self).__init__(lineno, col_offset, parent)
- def postinit(self, items=None, body=None):
+ def postinit(self, items=Empty, body=Empty):
self.items = items
self.body = body
@@ -1272,10 +1290,10 @@ class With(base.BlockRangeMixIn, base.AssignTypeMixin,
@util.register_implementation(treeabc.WithItem)
class WithItem(base.ParentAssignTypeMixin, AssignedStmtsMixin, base.NodeNG):
_astroid_fields = ('context_expr', 'optional_vars')
- context_expr = None
- optional_vars = None
+ context_expr = Empty
+ optional_vars = Empty
- def postinit(self, context_expr=None, optional_vars=None):
+ def postinit(self, context_expr=Empty, optional_vars=Empty):
self.context_expr = context_expr
self.optional_vars = optional_vars
@@ -1289,9 +1307,9 @@ class AsyncWith(With):
class Yield(base.NodeNG):
"""class representing a Yield node"""
_astroid_fields = ('value',)
- value = None
+ value = Empty
- def postinit(self, value=None):
+ def postinit(self, value=Empty):
self.value = value
@@ -1305,22 +1323,6 @@ class DictUnpack(base.NodeNG):
"""Represents the unpacking of dicts into dicts using PEP 448."""
-@object.__new__
-@util.register_implementation(treeabc.Empty)
-class Empty(base.NodeNG):
- """Empty nodes represents the lack of something
-
- For instance, they can be used to represent missing annotations
- or defaults for arguments or anything where None is a valid
- value.
- """
-
- def __bool__(self):
- return False
-
- __nonzero__ = __bool__
-
-
# Register additional inference dispatched functions. We do
# this here, since we need to pass this module as an argument
# to these functions, in order to avoid circular dependencies
diff --git a/astroid/tree/rebuilder.py b/astroid/tree/rebuilder.py
index 074aea1e..28de10b2 100644
--- a/astroid/tree/rebuilder.py
+++ b/astroid/tree/rebuilder.py
@@ -97,8 +97,7 @@ def _get_doc(node):
except IndexError:
return node, None
-def _visit_or_none(node, attr, visitor, parent, visit='visit',
- **kws):
+def _visit_or_empty(node, attr, visitor, parent, visit='visit', **kws):
"""If the given node has an attribute, visits the attribute, and
otherwise returns None.
@@ -107,7 +106,7 @@ def _visit_or_none(node, attr, visitor, parent, visit='visit',
if value:
return getattr(visitor, visit)(value, parent, **kws)
else:
- return None
+ return nodes.Empty
def _get_context(node):
@@ -152,7 +151,7 @@ class ParameterVisitor(object):
col_offset=getattr(param_node, 'col_offset', None),
parent=parent)
annotation = nodes.Empty
- param_annotation = getattr(param_node, 'annotation', None)
+ param_annotation = getattr(param_node, 'annotation', nodes.Empty)
if param_annotation:
annotation = self._visitor.visit(param_annotation, param)
@@ -210,10 +209,10 @@ class TreeRebuilder(object):
# Get the annotation of the variadic node.
annotation = nodes.Empty
default = nodes.Empty
- variadic_annotation = getattr(variadic, 'annotation', None)
+ variadic_annotation = getattr(variadic, 'annotation', nodes.Empty)
if variadic_annotation is None:
# Support for Python 3.3.
- variadic_annotation = getattr(node, field_name + 'annotation', None)
+ variadic_annotation = getattr(node, field_name + 'annotation', nodes.Empty)
if variadic_annotation:
annotation = self.visit(variadic_annotation, param)
@@ -255,7 +254,7 @@ class TreeRebuilder(object):
if node.msg:
msg = self.visit(node.msg, newnode)
else:
- msg = None
+ msg = nodes.Empty
newnode.postinit(self.visit(node.test, newnode), msg)
return newnode
@@ -312,8 +311,8 @@ class TreeRebuilder(object):
def visit_call(self, node, parent):
"""visit a CallFunc node by returning a fresh instance of it"""
newnode = nodes.Call(node.lineno, node.col_offset, parent)
- starargs = _visit_or_none(node, 'starargs', self, newnode)
- kwargs = _visit_or_none(node, 'kwargs', self, newnode)
+ starargs = _visit_or_empty(node, 'starargs', self, newnode)
+ kwargs = _visit_or_empty(node, 'kwargs', self, newnode)
args = [self.visit(child, newnode)
for child in node.args]
@@ -321,7 +320,7 @@ class TreeRebuilder(object):
keywords = [self.visit(child, newnode)
for child in node.keywords]
else:
- keywords = None
+ keywords = ()
if starargs:
new_starargs = nodes.Starred(col_offset=starargs.col_offset,
lineno=starargs.lineno,
@@ -356,7 +355,7 @@ class TreeRebuilder(object):
if node.decorator_list:
decorators = self.visit_decorators(node, newnode)
else:
- decorators = None
+ decorators = nodes.Empty
newnode.postinit([self.visit(child, newnode)
for child in node.bases],
[self.visit(child, newnode)
@@ -457,8 +456,8 @@ class TreeRebuilder(object):
"""visit an ExceptHandler node by returning a fresh instance of it"""
newnode = nodes.ExceptHandler(node.lineno, node.col_offset, parent)
# /!\ node.name can be a tuple
- newnode.postinit(_visit_or_none(node, 'type', self, newnode),
- _visit_or_none(node, 'name', self, newnode),
+ newnode.postinit(_visit_or_empty(node, 'type', self, newnode),
+ _visit_or_empty(node, 'name', self, newnode),
[self.visit(child, newnode)
for child in node.body])
return newnode
@@ -467,15 +466,14 @@ class TreeRebuilder(object):
"""visit an Exec node by returning a fresh instance of it"""
newnode = nodes.Exec(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.body, newnode),
- _visit_or_none(node, 'globals', self, newnode),
- _visit_or_none(node, 'locals', self, newnode))
+ _visit_or_empty(node, 'globals', self, newnode),
+ _visit_or_empty(node, 'locals', self, newnode))
return newnode
def visit_extslice(self, node, parent):
"""visit an ExtSlice node by returning a fresh instance of it"""
newnode = nodes.ExtSlice(parent=parent)
- newnode.postinit([self.visit(dim, newnode)
- for dim in node.dims])
+ newnode.postinit([self.visit(dim, newnode) for dim in node.dims])
return newnode
def _visit_for(self, cls, node, parent):
@@ -509,11 +507,11 @@ class TreeRebuilder(object):
if node.decorator_list:
decorators = self.visit_decorators(node, newnode)
else:
- decorators = None
+ decorators = nodes.Empty
if PY3 and node.returns:
returns = self.visit(node.returns, newnode)
else:
- returns = None
+ returns = nodes.Empty
newnode.postinit(self.visit(node.args, newnode),
[self.visit(child, newnode)
for child in node.body],
@@ -660,7 +658,7 @@ class TreeRebuilder(object):
def visit_print(self, node, parent):
"""visit a Print node by returning a fresh instance of it"""
newnode = nodes.Print(node.nl, node.lineno, node.col_offset, parent)
- newnode.postinit(_visit_or_none(node, 'dest', self, newnode),
+ newnode.postinit(_visit_or_empty(node, 'dest', self, newnode),
[self.visit(child, newnode)
for child in node.values])
return newnode
@@ -668,9 +666,9 @@ class TreeRebuilder(object):
def visit_raise(self, node, parent):
"""visit a Raise node by returning a fresh instance of it"""
newnode = nodes.Raise(node.lineno, node.col_offset, parent)
- newnode.postinit(_visit_or_none(node, 'type', self, newnode),
- _visit_or_none(node, 'inst', self, newnode),
- _visit_or_none(node, 'tback', self, newnode))
+ newnode.postinit(_visit_or_empty(node, 'type', self, newnode),
+ _visit_or_empty(node, 'inst', self, newnode),
+ _visit_or_empty(node, 'tback', self, newnode))
return newnode
def visit_return(self, node, parent):
@@ -698,9 +696,9 @@ class TreeRebuilder(object):
def visit_slice(self, node, parent):
"""visit a Slice node by returning a fresh instance of it"""
newnode = nodes.Slice(parent=parent)
- newnode.postinit(_visit_or_none(node, 'lower', self, newnode),
- _visit_or_none(node, 'upper', self, newnode),
- _visit_or_none(node, 'step', self, newnode))
+ newnode.postinit(_visit_or_empty(node, 'lower', self, newnode),
+ _visit_or_empty(node, 'upper', self, newnode),
+ _visit_or_empty(node, 'step', self, newnode))
return newnode
def visit_subscript(self, node, parent):
@@ -767,7 +765,7 @@ class TreeRebuilder(object):
with_item = nodes.WithItem(node.context_expr.lineno,
node.context_expr.col_offset, newnode)
context_expr = self.visit(node.context_expr, with_item)
- optional_vars = _visit_or_none(node, 'optional_vars', self, with_item)
+ optional_vars = _visit_or_empty(node, 'optional_vars', self, with_item)
with_item.postinit(context_expr, optional_vars)
newnode.postinit([with_item],
[self.visit(child, newnode) for child in node.body])
@@ -795,8 +793,8 @@ class TreeRebuilder3(TreeRebuilder):
if node.name:
name = self.visit_assignname(node, newnode, node.name)
else:
- name = None
- newnode.postinit(_visit_or_none(node, 'type', self, newnode),
+ name = nodes.Empty
+ newnode.postinit(_visit_or_empty(node, 'type', self, newnode),
name,
[self.visit(child, newnode)
for child in node.body])
@@ -812,8 +810,8 @@ class TreeRebuilder3(TreeRebuilder):
"""visit a Raise node by returning a fresh instance of it"""
newnode = nodes.Raise(node.lineno, node.col_offset, parent)
# no traceback; anyway it is not used in Pylint
- newnode.postinit(_visit_or_none(node, 'exc', self, newnode),
- _visit_or_none(node, 'cause', self, newnode))
+ newnode.postinit(_visit_or_empty(node, 'exc', self, newnode),
+ _visit_or_empty(node, 'cause', self, newnode))
return newnode
def visit_starred(self, node, parent):
@@ -852,7 +850,7 @@ class TreeRebuilder3(TreeRebuilder):
newnode = nodes.WithItem(node.context_expr.lineno,
node.context_expr.col_offset, parent)
context_expr = self.visit(node.context_expr, newnode)
- optional_vars = _visit_or_none(node, 'optional_vars', self, newnode)
+ optional_vars = _visit_or_empty(node, 'optional_vars', self, newnode)
newnode.postinit(context_expr=context_expr, optional_vars=optional_vars)
return newnode
diff --git a/astroid/tree/scoped_nodes.py b/astroid/tree/scoped_nodes.py
index 6744ec82..355ad650 100644
--- a/astroid/tree/scoped_nodes.py
+++ b/astroid/tree/scoped_nodes.py
@@ -202,7 +202,7 @@ class Module(QualifiedNameMixin, lookup.LocalsDictNode):
self.body = []
self.external_attrs = collections.defaultdict(list)
- def postinit(self, body=None):
+ def postinit(self, body=()):
self.body = body
@property
@@ -447,15 +447,15 @@ class ComprehensionScope(lookup.LocalsDictNode):
class GeneratorExp(ComprehensionScope):
_astroid_fields = ('elt', 'generators')
# _other_other_fields = ('locals',)
- elt = None
- generators = None
+ elt = node_classes.Empty
+ generators = node_classes.Empty
def __init__(self, lineno=None, col_offset=None, parent=None):
super(GeneratorExp, self).__init__(lineno, col_offset, parent)
- def postinit(self, elt=None, generators=None):
+ def postinit(self, elt=node_classes.Empty, generators=node_classes.Empty):
self.elt = elt
- if generators is None:
+ if generators is node_classes.Empty:
self.generators = []
else:
self.generators = generators
@@ -468,17 +468,17 @@ class GeneratorExp(ComprehensionScope):
class DictComp(ComprehensionScope):
_astroid_fields = ('key', 'value', 'generators')
# _other_other_fields = ('locals',)
- key = None
- value = None
- generators = None
+ key = node_classes.Empty
+ value = node_classes.Empty
+ generators = node_classes.Empty
def __init__(self, lineno=None, col_offset=None, parent=None):
super(DictComp, self).__init__(lineno, col_offset, parent)
- def postinit(self, key=None, value=None, generators=None):
+ def postinit(self, key=node_classes.Empty, value=node_classes.Empty, generators=node_classes.Empty):
self.key = key
self.value = value
- if generators is None:
+ if generators is node_classes.Empty:
self.generators = []
else:
self.generators = generators
@@ -491,15 +491,15 @@ class DictComp(ComprehensionScope):
class SetComp(ComprehensionScope):
_astroid_fields = ('elt', 'generators')
# _other_other_fields = ('locals',)
- elt = None
- generators = None
+ elt = node_classes.Empty
+ generators = node_classes.Empty
def __init__(self, lineno=None, col_offset=None, parent=None):
super(SetComp, self).__init__(lineno, col_offset, parent)
- def postinit(self, elt=None, generators=None):
+ def postinit(self, elt=node_classes.Empty, generators=node_classes.Empty):
self.elt = elt
- if generators is None:
+ if generators is node_classes.Empty:
self.generators = []
else:
self.generators = generators
@@ -512,10 +512,10 @@ class SetComp(ComprehensionScope):
class _ListComp(treebase.NodeNG):
"""class representing a ListComp node"""
_astroid_fields = ('elt', 'generators')
- elt = None
- generators = None
+ elt = node_classes.Empty
+ generators = node_classes.Empty
- def postinit(self, elt=None, generators=None):
+ def postinit(self, elt=node_classes.Empty, generators=node_classes.Empty):
self.elt = elt
self.generators = generators
@@ -892,10 +892,10 @@ class FunctionDef(LambdaFunctionMixin, lookup.LocalsDictNode,
if six.PY3:
_astroid_fields = ('decorators', 'args', 'body', 'returns')
- returns = None
+ returns = node_classes.Empty
else:
_astroid_fields = ('decorators', 'args', 'body')
- decorators = None
+ decorators = node_classes.Empty
special_attributes = frozenset(
('__doc__', '__name__', '__qualname__', '__module__', '__defaults__',
@@ -916,7 +916,7 @@ class FunctionDef(LambdaFunctionMixin, lookup.LocalsDictNode,
super(FunctionDef, self).__init__(lineno, col_offset, parent)
# pylint: disable=arguments-differ; different than Lambdas
- def postinit(self, args, body, decorators=None, returns=None):
+ def postinit(self, args, body, decorators=node_classes.Empty, returns=node_classes.Empty):
self.args = args
self.body = body
self.decorators = decorators
@@ -1035,7 +1035,7 @@ class FunctionDef(LambdaFunctionMixin, lookup.LocalsDictNode,
# lineno is the line number of the first decorator, we want the def
# statement lineno
lineno = self.lineno
- if self.decorators is not None:
+ if self.decorators is not node_classes.Empty:
lineno += sum(node.tolineno - node.lineno + 1
for node in self.decorators.nodes)
@@ -1084,7 +1084,7 @@ class FunctionDef(LambdaFunctionMixin, lookup.LocalsDictNode,
"""return a list of decorator qualified names"""
result = set()
decoratornodes = []
- if self.decorators is not None:
+ if self.decorators is not node_classes.Empty:
# pylint: disable=unsupported-binary-operation; damn flow control.
decoratornodes += self.decorators.nodes
decoratornodes += self.extra_decorators
@@ -1144,7 +1144,7 @@ class FunctionDef(LambdaFunctionMixin, lookup.LocalsDictNode,
# metaclass generators, and filter it out later.
if (self.name == 'with_metaclass' and
len(self.args.args) == 1 and
- self.args.vararg is not None):
+ self.args.vararg is not node_classes.Empty):
metaclass = next(caller.args[0].infer(context))
if isinstance(metaclass, ClassDef):
c = ClassDef('temporary_class', None)
@@ -1157,7 +1157,7 @@ class FunctionDef(LambdaFunctionMixin, lookup.LocalsDictNode,
return
returns = self.nodes_of_class(node_classes.Return, skip_klass=FunctionDef)
for returnnode in returns:
- if returnnode.value is None:
+ if returnnode.value is node_classes.Empty:
yield node_classes.NameConstant(None)
else:
try:
@@ -1279,7 +1279,7 @@ class ClassDef(QualifiedNameMixin, base.FilterStmtsMixin,
_astroid_fields = ('decorators', 'bases', 'body')
- decorators = None
+ decorators = node_classes.Empty
special_attributes = frozenset(
('__name__', '__module__', '__dict__', '__bases__', '__doc__',
'__qualname__', '__mro__', '__subclasses__', '__class__'))
diff --git a/astroid/tree/zipper.py b/astroid/tree/zipper.py
index cf306e08..78643a6b 100644
--- a/astroid/tree/zipper.py
+++ b/astroid/tree/zipper.py
@@ -108,12 +108,6 @@ class Zipper(wrapt.ObjectProxy):
# local variable, avoiding a super() call, two globals lookups,
# and two dict lookups (on wrapt's and ObjectProxy's dicts).
def __init__(self, focus, path=None, init=wrapt.ObjectProxy.__init__):
- try:
- assert(isinstance(focus, (base.NodeNG, collections.Sequence)))
- except AssertionError:
- print(focus)
- print(path)
- raise
init(self, focus)
self._self_path = path