Auto-load a module on python startup

Viewed 13128

I want IPython or the Python interpreter to auto-load a module when I start them.

Is it possible?

For example when I start IPython:

$ ipython

...

>>> from __future__ import division
>>> from mymodule import *

In [1]:

Something like SymPy's live shell found in the tutorial pages.

5 Answers

Another possible solution is to use the argument -i from python interpreter that launches the interaction mode after executing your script.

You could for instance use:

  • python -i your_module.py
  • python -i /path/to/your/module in case you have defined a __main__.py
  • or even python -i -m your.module

To automatically lazily import all top-level importable modules when using them, define this in your PYTHONSTARTUP file:

import pkgutil
from importlib import import_module

class LazyModule:
    def __init__(self, alias, path):
        self._alias = alias
        self._path = path
        globals()[self._alias] = self

    def __getattr__(self, attr):
        module = import_module(self._path)
        globals()[self._alias] = module
        return getattr(module, attr)

# All top-level modules.
modules = [x.name for x in pkgutil.iter_modules()]

for module in modules:
    LazyModule(alias=module, path=module)

# Also include any other custom aliases.
LazyModule("mpl", "matplotlib")
LazyModule("plt", "matplotlib.pyplot")
LazyModule("pd", "pandas")
LazyModule("sns", "seaborn")
LazyModule("tf", "tensorflow")

Now you can access modules without needing to import them manually:

>>> math.sqrt(0)
0
Related