pythonnumpyipython

Automatically import modules when entering the python or ipython interpreter


I find myself typing import numpy as np almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported?


Solution

  • Use the environment variable PYTHONSTARTUP. From the official documentation:

    If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session.

    So, just create a python script with the import statement and point the environment variable to it. Having said that, remember that 'Explicit is always better than implicit', so don't rely on this behavior for production scripts.

    For Ipython, see this tutorial on how to make a ipython_config file