Syntax#
This section covers common ipython
features such as the ability to use ipython magic.
Embeded magics#
Note that you can embed line-based magic in Python code.
The following code stores the results of the %ls
magic in the result
variable.
result = %ls
print(result)
magics.ipynb
None
Omit %
#
If you don’t have a corresponding name in the namespace, you can omit the %
to call linebase magic.
For example the following cell applies timeit
to the list generator and calls it just by name without any prefixes.
timeit [i for i in range(1000)]
23.6 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
Note: Magics cannot be called without %
if they are in the nested namespace. The following cell tries to refer to the pwd
magic inside the if
block, causing an error.
try:
if True: res = pwd
except Exception as e:
print(e)
name 'pwd' is not defined
But the same syntax, but forcing the interpreter to use magic, works fine.
if True: res = %pwd