Context Class

An isolated Q# interpreter environment.

A Context provides a self-contained Q# execution environment where code is evaluated, compiled, and executed in isolation from other Context instances. Each Context maintains its own code namespace.

A context has a code attribute which is a Python module containing all Q# operations and types defined in this context. This allows you to call Q# operations from Python.

Example:


   ctx = qdk.Context()
   ctx.eval("operation Main() : Result { use q = Qubit(); X(q); MResetZ(q) }")
   assert ctx.run("Main()", 2) == [qdk.Result.One, qdk.Result.One]
   assert ctx.code.Main() == qdk.Result.One

Initializes a new isolated Q# context.

Constructor

Context(*, target_profile: TargetProfile = TargetProfile.Unrestricted, target_name: str | None = None, project_root: str | None = None, language_features: List[str] | None = None, _trace_circuit: bool | None = None, _is_global_context: bool = False)

Keyword-Only Parameters

Name Description
target_profile

Setting the target profile allows the Q# interpreter to generate programs that are compatible with a specific target. See TargetProfile.

Default value: Unrestricted
target_name

An optional name of the target machine to use for inferring the compatible target_profile setting.

Default value: None
project_root

An optional path to a root directory with a Q# project to include. It must contain a qsharp.json project manifest.

Default value: None
language_features

An optional list of language feature flags to enable. These correspond to experimental or preview Q# language features. Valid values are:

  • "v2-preview-syntax": Enables Q# v2 preview syntax. This removes support for

the scoped qubit allocation block form (use q = Qubit() { ... }), requiring the statement form instead (use q = Qubit();). It also removes the requirement to use the set keyword for mutable variable assignments.

Default value: None
_trace_circuit
Default value: None
_is_global_context
Default value: False

Methods

circuit

Synthesizes a circuit for a Q# program. Either an entry expression or an operation must be provided.

compile

Compiles the Q# source code into a program that can be submitted to a target. Either an entry expression or a callable with arguments must be provided.

Example:

dump_machine

Returns the sparse state vector of the simulator as a StateDump object.

eval

Evaluates Q# source code.

Output is printed to console.

get_target_profile

Returns target profile for this Context.

import_openqasm

Imports OpenQASM source code into this context's interpreter.

logical_counts

Extracts logical resource counts from Q# source code. Either an entry expression or a callable with arguments must be provided.

run

Runs the given Q# expression for the given number of shots. Each shot uses an independent instance of the simulator.

set_classical_seed

Sets the seed for the random number generator used for standard library classical random number operations. This applies to all Q# code executed, compiled, or estimated in this Context.

set_quantum_seed

Sets the seed for the random number generator used for quantum measurements. This applies to all Q# code executed, compiled, or estimated in this Context.

circuit

Synthesizes a circuit for a Q# program. Either an entry expression or an operation must be provided.

circuit(entry_expr: str | Callable | GlobalCallable | Closure | None = None, *args, operation: str | None = None, generation_method: CircuitGenerationMethod | None = None, max_operations: int | None = None, source_locations: bool = False, group_by_scope: bool = True, prune_classical_qubits: bool = False) -> Circuit

Parameters

Name Description
entry_expr

An entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

Default value: None
*args
Required

The arguments to pass to the callable, if one is provided.

Keyword-Only Parameters

Name Description
operation
str

The operation to synthesize. This can be a name of an operation or a lambda expression. The operation must take only qubits or arrays of qubits as parameters.

Default value: None
generation_method

The method to use for circuit generation. ClassicalEval evaluates classical control flow at circuit generation time. Simulate runs a full simulation to trace the circuit. Static uses partial evaluation and requires a non-Unrestricted target profile. Defaults to None which auto-selects the generation method.

Default value: None
max_operations
int

The maximum number of operations to include in the circuit. Defaults to None which means no limit.

Default value: None
source_locations

If True, annotates each gate with its source location.

Default value: False
group_by_scope

If True, groups operations by their containing scope, such as function declarations or loop blocks.

Default value: True
prune_classical_qubits

If True, removes qubits that are never used in a quantum gate (e.g. qubits only used as classical controls).

Default value: False

Returns

Type Description
<xref:Circuit>

The synthesized circuit.

Exceptions

Type Description

If there is an error synthesizing the circuit.

compile

Compiles the Q# source code into a program that can be submitted to a target. Either an entry expression or a callable with arguments must be provided.

Example:

compile(entry_expr: str | Callable | GlobalCallable | Closure, *args) -> QirInputData

Parameters

Name Description
entry_expr
Required

The Q# expression that will be used as the entrypoint for the program. Alternatively, a callable can be provided, which must be a Q# callable.

*args
Required

The arguments to pass to the callable, if one is provided.

Returns

Type Description
<xref:QirInputData>

The compiled program. Use str() to get the QIR string.

dump_machine

Returns the sparse state vector of the simulator as a StateDump object.

dump_machine() -> StateDump

Returns

Type Description

The state of the simulator.

eval

Evaluates Q# source code.

Output is printed to console.

eval(source: str, *, save_events: bool = False) -> Any

Parameters

Name Description
source
Required

The Q# source code to evaluate.

Keyword-Only Parameters

Name Description
save_events

If true, all output will be saved and returned. If false, they will be printed.

Default value: False

Returns

Type Description
Any

The value returned by the last statement in the source code, or the saved output if save_events is true.

Exceptions

Type Description

If there is an error evaluating the source code.

get_target_profile

Returns target profile for this Context.

get_target_profile() -> TargetProfile

import_openqasm

Imports OpenQASM source code into this context's interpreter.

import_openqasm(source: str, **kwargs: Any) -> Any

Parameters

Name Description
source
Required
str

An OpenQASM program or fragment.

**kwargs
Required

Additional keyword arguments. Common options:

  • name (str): The name of the program. This is used as the entry point for the program.

  • search_path (str): The optional search path for resolving file references.

  • output_semantics (OutputSemantics): The output semantics for the compilation.

  • program_type (ProgramType): The type of program compilation to perform:

    • ProgramType.Operation (default): the source becomes a Q# operation in the global namespace with parameters for any declared classical inputs and parameters for each of the declared qubits, while any explicit or implicit output declarations become the return type of the operation.

    • ProgramType.File: will treat the input source as a stand-alone program and create an operation in the qasm_import namespace that only takes classical parameters, allocates the required qubits internally and releases them at the end of the operation.

    • ProgramType.Fragments: executes the provided source in the current interactive interpreter, defining any declared variables or operations in the current scope and returning the value of the last statement in the source.

Returns

Type Description
Any

The value returned by the last statement in the source code.

Exceptions

Type Description

If there is an error generating, parsing, or analyzing the OpenQASM source.

If there is an error compiling the program.

logical_counts

Extracts logical resource counts from Q# source code. Either an entry expression or a callable with arguments must be provided.

logical_counts(entry_expr: str | Callable | GlobalCallable | Closure, *args) -> LogicalCounts

Parameters

Name Description
entry_expr
Required

The entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

Returns

Type Description

Program resources in terms of logical gate counts.

run

Runs the given Q# expression for the given number of shots. Each shot uses an independent instance of the simulator.

run(entry_expr: str | Callable | GlobalCallable | Closure, shots: int, *args, on_result: Callable[[ShotResult], None] | None = None, save_events: bool = False, noise: Tuple[float, float, float] | PauliNoise | BitFlipNoise | PhaseFlipNoise | DepolarizingNoise | NoiseConfig | None = None, qubit_loss: float | None = None, seed: int | None = None, type: Literal['sparse', 'clifford'] | None = None, num_qubits: int | None = None) -> List[Any]

Parameters

Name Description
entry_expr
Required

The entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

shots
Required

The number of shots to run.

*args
Required

The arguments to pass to the callable, if one is provided.

on_result
Required

A callback function that will be called with each result.

save_events
Required

If true, the output of each shot will be saved. If false, they will be printed.

noise
Required

The noise to use in simulation.

qubit_loss
Required

The probability of qubit loss in simulation.

seed
Required

The seed to use for the random number generator in simulation, if any.

type
Required

The type of simulator to use. If not specified, the default sparse state vector simulation will be used.

num_qubits
Required

The number of qubits to use for the simulation type "clifford". If not specified, the Clifford simulator assumes a default of 1000 qubits.

Keyword-Only Parameters

Name Description
on_result
Default value: None
save_events
Default value: False
noise
Default value: None
qubit_loss
Default value: None
seed
Default value: None
type
Default value: None
num_qubits
Default value: None

Returns

Type Description

A list of results or runtime errors. If save_events is true, a list of ShotResult is returned.

Exceptions

Type Description

If there is an error interpreting the input.

If the number of shots is less than 1.

set_classical_seed

Sets the seed for the random number generator used for standard library classical random number operations. This applies to all Q# code executed, compiled, or estimated in this Context.

set_classical_seed(seed: int | None) -> None

Parameters

Name Description
seed
Required

The seed to use for the classical random number generator. If None, the seed will be generated from entropy.

set_quantum_seed

Sets the seed for the random number generator used for quantum measurements. This applies to all Q# code executed, compiled, or estimated in this Context.

set_quantum_seed(seed: int | None) -> None

Parameters

Name Description
seed
Required

The seed to use for the quantum random number generator. If None, the seed will be generated from entropy.

Attributes

code

code: Any