taotao.li
taotao.li

Reputation: 1082

how does IPython magics work

ipthon-sql is an extension of ipython, I first install it by pip install ipython-sql

the project is here: https://github.com/catherinedevlin/ipython-sql

and my problem is:

when I enter %load_ext sql and press SHIFT+ENTER, what's the detailed procedure of IPython to execute this magic sentence? thanks ...

enter image description here

Upvotes: 5

Views: 1607

Answers (1)

Thomas K
Thomas K

Reputation: 40370

When you run any code in the notebook, an execute_request is sent via the notebook server, to a 'kernel', a process which executes your code.

When the kernel receives your code, it runs it through a sequence of input transformers. One of these detects that this line is a magic command, and rewrites it to:

get_ipython().magic('load_ext sql')

You can see these translated commands using %hist -t.

The .magic() method takes the first word of its argument, load_ext, and looks it up in a dictionary. You can see that dictionary by running:

get_ipython().magics_manager.magics['line']

(this may be a bit different depending on your version of IPython)

That gives it a reference to the method IPython.core.magics.extension.ExtensionMagics.load_ext, which you can see here. It calls that method with the remainder of the string.

That method imports the package sql, and calls sql.load_ipython_extension(ip) to set it up. It's up to the extension what it does then - in this case, it registers some new magic functions.

Upvotes: 7

Related Questions