Skip to content

Invoking Q# callables from Python

Stefan J. Wernli edited this page Dec 13, 2024 · 2 revisions

The qsharp Python package makes it easy to call Q# operations and functions from within Python. Each Q# callable defined through calls to qsharp.eval() or in a Q# project loaded via qsharp.init() is automatically added to the qsharp.code module in Python:

import qsharp

qsharp.eval("""
    operation Superposition() : Result {
        use q = Qubit();
        H(q);
        Std.Diagnostics.DumpMachine();
        MResetZ(q)
    }
    """)

qsharp.code.Superposition()
STATE:
|0⟩: 0.7071+0.0000𝑖
|1⟩: 0.7071+0.0000𝑖
One

The same is true for Q# callables defined in Jupyter notebook using the %%qsharp cell magic:

image

These callables can then be invoked as normal Python functions, which will run them in the Q# simulator just as if they were invoked from within a normal Q# context. Any output produced from calls to Message or diagnostics like DumpMachine will appear as normal and the return from the function marshalled into Python:

image

These callables can also be imported within the Python environment:

image

Python literals and variables can be passed directly to Q# callables like any other Python function, and types that support conversion into the equivalent Q# types will work as expected:

image

If a Python value cannot be converted into the correct Q# type or the wrong number of arguments are provided, an exception is raised:

image

Not all Q# types support conversion from/to Python; if a callable has arguments or return values of these types, invoking the function will trigger a runtime exception:

image

Unsupported interop types include Qubits, structs/user-defined-types, and callables.

When using projects, Q# callables will be with a module hierarchy matching the namespace hierarchy of the project:

image

When qsharp.init() is called the current compilation and simulator state is reset, so all callables are removed from the qsharp.code module:

image

Any functions previously imported from qsharp.code are also invalidated:

image