Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython Modules

I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?

like image 862
sharjeel Avatar asked Dec 03 '22 15:12

sharjeel


2 Answers

You should not be saving the IPython extension stuff (?, !, %run) in files. Ever. Those are interactive tools and they are something you type with your hands but never save to a file.

  1. Find the common features among your files. You have exactly four kinds of things that are candidates for this.

    • Imports (import)

    • Function definitions (def)

    • Class definitions (class)

    • Global variable assignments

    You must remove all IPython interactive features from this code. All of it.

  2. Rewrite your scripts so they (1) import your common stuff, (2) do the useful work they're supposed to do.

    You must remove all IPython interactive features from this code. All of it.

    Now you can run your scripts and they're do their work like proper Python scripts are supposed.

You can still use IPython extension features like !, ? and %run when you're typing, but you should not save these into files.

like image 157
S.Lott Avatar answered Dec 24 '22 05:12

S.Lott


technically if you save a script with the .ipy extension, ipython will see that and use all it's fancy stuff rather than passing directly to the python interpreter. however, i would generally recommend against this, and go the route of S.Lott above.

like image 21
Autoplectic Avatar answered Dec 24 '22 03:12

Autoplectic