Why this test. Just put `expr = expr.doit()` after the next couple of lines (that check if expr is an instance of Basic).