Skip to content

Commit

Permalink
Allow attribute assignment for exception instances
Browse files Browse the repository at this point in the history
  • Loading branch information
PCManticore committed Nov 17, 2019
1 parent b55fc8d commit 05a9106
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
9 changes: 6 additions & 3 deletions astroid/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
from astroid import nodes
from astroid import util

objects = util.lazy_import("objects")

# The name of the transient function that is used to
# wrap expressions to be extracted when calling
# extract_node.
Expand Down Expand Up @@ -224,14 +226,15 @@ def delayed_assattr(self, node):
if inferred is util.Uninferable:
continue
try:
if inferred.__class__ is bases.Instance:
cls = inferred.__class__
if cls is bases.Instance or cls is objects.ExceptionInstance:
inferred = inferred._proxied
iattrs = inferred.instance_attrs
if not _can_assign_attr(inferred, node.attrname):
continue
elif isinstance(inferred, bases.Instance):
# Const, Tuple, ... we may be wrong, may be not, but
# anyway we don't want to pollute builtin's namespace
# Const, Tuple or other containers that inherit from
# `Instance`
continue
elif inferred.is_function:
iattrs = inferred.instance_attrs
Expand Down
22 changes: 22 additions & 0 deletions tests/unittest_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
from astroid import objects
from astroid import test_utils
from astroid import util
from astroid.objects import ExceptionInstance

from . import resources


Expand Down Expand Up @@ -5348,5 +5350,25 @@ def __init__(*args, **kwargs):
assert inferred_data.as_string() == "{1: 2}"


def test_infer_exception_instance_attributes():
code = """
class UnsupportedFormatCharacter(Exception):
def __init__(self, index):
Exception.__init__(self, index)
self.index = index
try:
1/0
except UnsupportedFormatCharacter as exc:
exc #@
"""
node = extract_node(code)
inferred = next(node.infer())
assert isinstance(inferred, ExceptionInstance)
index = inferred.getattr("index")
assert len(index) == 1
assert isinstance(index[0], nodes.AssignAttr)


if __name__ == "__main__":
unittest.main()

0 comments on commit 05a9106

Please sign in to comment.