Better way of checking whether in iPython

**Changes:**
- Move imports out of function body
- Use ``getattr`` instead of checking if key is in dict