Skip to content

Incorrect inference on conditional inferred assignment #315

Open
@xmo-odoo

Description

@xmo-odoo

May be related to #192?

m = astroid.builder.parse('''
a = ''
if cond:
    a += thing()
print a
''')

m.body[-1].values[0].infer() will only contain a Const(value=''), completely ignoring the augmented assignment. I would have expected something similar to a regular concatenation-and-assignment:

m = astroid.builder.parse('''
a = ''
if cond:
    a = a + thing()
print a
''')
print list(m.body[-1].values[0].infer())
[<Const(str) l.2 [] at 0x1020d7550>, YES]

since augmented assignment will fallback on a normal operate-then-assign if not overridden, interpreting them as operate-then-assign would be a valid basic inference:

>>> class Foo(object):
...     def __radd__(self, other):
...             return self
... 
>>> a = 'a'
>>> a += Foo()
>>> a
<__main__.Foo object at 0x1020c0a10>

Note: while the inference is not incorrect on unconditional augmented assignment, it blows up entirely:

>>> m = astroid.builder.parse("""
... a = ''
... a += foo()
... print a
... """)
>>> list(m.body[-1].values[0].infer()) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lib/python2.7/site-packages/astroid/bases.py", line 302, in wrapped
    for res in _func(node, context, **kwargs):
  File "lib/python2.7/site-packages/astroid/bases.py", line 108, in _infer_stmts
    raise exceptions.InferenceError(str(stmt))
astroid.exceptions.InferenceError: AssignName(a)

This is with astroid 1.4.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions