Why does Python magic timeit function return a syntax error?

I am trying to use the python magic function %timeit, but it returns a syntax error:

%timeit sum(range(100))
  File "<input>", line 1
    %timeit sum(range(100))
    ^
SyntaxError: invalid syntax

The error returns in both console and debug contexts.

It is like %timeit is an unrecognised module, but I can’t see anyway to import/add the magics and in any case I thought they were part of the standard Python library.

I’m using Python 3.10 in PyCharm 2022.1.2 (Community Edition)

I hope I’m not missing something obvious!

>Solution :

The % directives are an IPython convenience when running interactive Python code. They’re commands you directly give to the interpreter. They are not valid Python syntax and cannot be used in actual Python source files.

Leave a Reply