diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index 5ff10b5f7f74..b0fa1dd6ab85 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -13,17 +13,21 @@ # pylint: disable=invalid-name """Backend abstract interface for providers.""" +from __future__ import annotations - +import typing from abc import ABC from abc import abstractmethod import datetime -from typing import List, Union, Iterable, Tuple +from collections.abc import Iterable from qiskit.providers.provider import Provider from qiskit.providers.models.backendstatus import BackendStatus from qiskit.circuit.gate import Instruction +if typing.TYPE_CHECKING: + from qiskit.providers.models import BackendConfiguration, BackendProperties + class Backend: """Base common type for all versioned Backend abstract classes. @@ -34,7 +38,7 @@ class Backend: directly. """ - version = 0 + version: str | int = 0 class BackendV1(Backend, ABC): @@ -69,9 +73,9 @@ class BackendV1(Backend, ABC): .. automethod:: _default_options """ - version = 1 + version: str | int = 1 - def __init__(self, configuration, provider=None, **fields): + def __init__(self, configuration: BackendConfiguration, provider=None, **fields): """Initialize a backend class Args: @@ -138,7 +142,7 @@ def set_options(self, **fields): raise AttributeError("Options field %s is not valid for this backend" % field) self._options.update_options(**fields) - def configuration(self): + def configuration(self) -> BackendConfiguration: """Return the backend configuration. Returns: @@ -146,7 +150,7 @@ def configuration(self): """ return self._configuration - def properties(self): + def properties(self) -> BackendProperties | None: """Return the backend properties. Returns: @@ -323,11 +327,11 @@ class BackendV2(Backend, ABC): def __init__( self, - provider: Provider = None, - name: str = None, - description: str = None, - online_date: datetime.datetime = None, - backend_version: str = None, + provider: Provider | None = None, + name: str | None = None, + description: str | None = None, + online_date: datetime.datetime | None = None, + backend_version: str | None = None, **fields, ): """Initialize a BackendV2 based backend @@ -373,17 +377,17 @@ def __init__( self._coupling_map = None @property - def instructions(self) -> List[Tuple[Instruction, Tuple[int]]]: + def instructions(self) -> list[tuple[Instruction, tuple[int, ...]]]: """A list of Instruction tuples on the backend of the form ``(instruction, (qubits)``""" return self.target.instructions @property - def operations(self) -> List[Instruction]: + def operations(self) -> list[Instruction]: """A list of :class:`~qiskit.circuit.Instruction` instances that the backend supports.""" return list(self.target.operations) @property - def operation_names(self) -> List[str]: + def operation_names(self) -> list[str]: """A list of instruction names that the backend supports.""" return list(self.target.operation_names) @@ -440,7 +444,7 @@ def _default_options(cls): pass @property - def dt(self) -> Union[float, None]: + def dt(self) -> float | None: """Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse @@ -466,7 +470,7 @@ def dtm(self) -> float: raise NotImplementedError @property - def meas_map(self) -> List[List[int]]: + def meas_map(self) -> list[list[int]]: """Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse @@ -487,9 +491,7 @@ def instruction_schedule_map(self): instructions defined in this backend's target.""" return self.target.instruction_schedule_map() - def qubit_properties( - self, qubit: Union[int, List[int]] - ) -> Union[QubitProperties, List[QubitProperties]]: + def qubit_properties(self, qubit: int | list[int]) -> QubitProperties | list[QubitProperties]: """Return QubitProperties for a given qubit. If there are no defined or the backend doesn't support querying these diff --git a/qiskit/providers/backend_compat.py b/qiskit/providers/backend_compat.py index 1e75f4a4a8a6..04ae485d1cd6 100644 --- a/qiskit/providers/backend_compat.py +++ b/qiskit/providers/backend_compat.py @@ -14,7 +14,9 @@ from __future__ import annotations import logging -from typing import List, Iterable, Any, Dict, Optional, Tuple +import typing +from collections.abc import Iterable +from typing import Any from qiskit.providers.backend import BackendV1, BackendV2 from qiskit.providers.backend import QubitProperties @@ -25,17 +27,21 @@ from qiskit.providers.options import Options from qiskit.providers.exceptions import BackendPropertyError +if typing.TYPE_CHECKING: + from qiskit.pulse import Instruction + from qiskit.transpiler.target import Target + logger = logging.getLogger(__name__) def convert_to_target( configuration: BackendConfiguration, - properties: BackendProperties = None, - defaults: PulseDefaults = None, - custom_name_mapping: Optional[Dict[str, Any]] = None, + properties: BackendProperties | None = None, + defaults: PulseDefaults | None = None, + custom_name_mapping: dict[str, Any] | None = None, add_delay: bool = True, filter_faulty: bool = True, -): +) -> Target: """Decode transpiler target from backend data set. This function generates ``Target`` instance from intermediate @@ -95,8 +101,8 @@ def convert_to_target( # Create instruction property placeholder from backend configuration basis_gates = set(getattr(configuration, "basis_gates", [])) gate_configs = {gate.name: gate for gate in configuration.gates} - inst_name_map = {} # type: Dict[str, Instruction] - prop_name_map = {} # type: Dict[str, Dict[Tuple[int, ...], InstructionProperties]] + inst_name_map: dict[str, Instruction] = {} + prop_name_map: dict[str, dict[tuple[int, ...], InstructionProperties]] = {} all_instructions = set.union(basis_gates, set(required)) faulty_ops = set() @@ -268,11 +274,11 @@ def convert_to_target( def qubit_props_list_from_props( properties: BackendProperties, -) -> List[QubitProperties]: +) -> list[QubitProperties]: """Uses BackendProperties to construct and return a list of QubitProperties. """ - qubit_props: List[QubitProperties] = [] + qubit_props: list[QubitProperties] = [] for qubit, _ in enumerate(properties.qubits): try: t_1 = properties.t1(qubit) @@ -324,7 +330,7 @@ class should only be used if you need a :class:`~.BackendV2` and still need def __init__( self, backend: BackendV1, - name_mapping: Optional[Dict[str, Any]] = None, + name_mapping: dict[str, Any] | None = None, add_delay: bool = True, filter_faulty: bool = True, ): @@ -364,13 +370,13 @@ def __init__( if hasattr(self._backend, "defaults"): self._defaults = self._backend.defaults() - self._target = None + self._target: Target | None = None self._name_mapping = name_mapping self._add_delay = add_delay self._filter_faulty = filter_faulty @property - def target(self): + def target(self) -> Target: """A :class:`qiskit.transpiler.Target` object for the backend. :rtype: Target @@ -399,7 +405,7 @@ def dtm(self) -> float: return self._config.dtm @property - def meas_map(self) -> List[List[int]]: + def meas_map(self) -> list[list[int]]: return self._config.meas_map def drive_channel(self, qubit: int): diff --git a/qiskit/providers/basicaer/basicaertools.py b/qiskit/providers/basicaer/basicaertools.py index 768febaecc75..cff65e9b2806 100644 --- a/qiskit/providers/basicaer/basicaertools.py +++ b/qiskit/providers/basicaer/basicaertools.py @@ -13,20 +13,21 @@ """Contains functions used by the basic aer simulators. """ +from __future__ import annotations from string import ascii_uppercase, ascii_lowercase -from typing import List, Optional import numpy as np import qiskit.circuit.library.standard_gates as gates +from qiskit.circuit import Gate from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = ("U", "u", "h", "p", "u1", "u2", "u3", "rz", "sx", "x") -def single_gate_matrix(gate: str, params: Optional[List[float]] = None): +def single_gate_matrix(gate: str, params: list[float] | None = None): """Get the matrix for a single qubit. Args: @@ -41,6 +42,7 @@ def single_gate_matrix(gate: str, params: Optional[List[float]] = None): if params is None: params = [] + gc: type[Gate] if gate == "U": gc = gates.UGate elif gate == "u3": diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 35e993185bfe..1b0949159a78 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -21,8 +21,7 @@ import json import os import re - -from typing import List, Iterable +from collections.abc import Iterable from qiskit import circuit from qiskit.providers.models import BackendProperties, BackendConfiguration, PulseDefaults @@ -42,7 +41,7 @@ class _Credentials: - def __init__(self, token="123456", url="https://"): + def __init__(self, token: str = "123456", url: str = "https://"): self.token = token self.url = url self.hub = "hub" @@ -98,7 +97,7 @@ def _parse_channels(self, channels): } identifier_pattern = re.compile(r"\D+(?P\d+)") - channels_map = { + channels_map: dict[str, dict[tuple, list]] = { "acquire": collections.defaultdict(list), "drive": collections.defaultdict(list), "measure": collections.defaultdict(list), @@ -220,7 +219,7 @@ def dtm(self) -> float: return None @property - def meas_map(self) -> List[List[int]]: + def meas_map(self) -> list[list[int]]: """Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. diff --git a/qiskit/providers/fake_provider/fake_qasm_backend.py b/qiskit/providers/fake_provider/fake_qasm_backend.py index 55dad4aff601..9a30c6e518ef 100644 --- a/qiskit/providers/fake_provider/fake_qasm_backend.py +++ b/qiskit/providers/fake_provider/fake_qasm_backend.py @@ -30,7 +30,7 @@ class FakeQasmBackend(FakeBackend): """A fake OpenQASM backend.""" - dirname = None + dirname: str = None conf_filename = None props_filename = None backend_name = None diff --git a/qiskit/providers/fake_provider/utils/backend_converter.py b/qiskit/providers/fake_provider/utils/backend_converter.py index 9e038c39df38..3b5c14220ba9 100644 --- a/qiskit/providers/fake_provider/utils/backend_converter.py +++ b/qiskit/providers/fake_provider/utils/backend_converter.py @@ -14,6 +14,10 @@ Utilities for constructing Target object from configuration, properties and pulse defaults json files """ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any from qiskit.transpiler.target import Target, InstructionProperties from qiskit.providers.backend import QubitProperties @@ -27,7 +31,11 @@ from qiskit.providers.models.pulsedefaults import PulseDefaults -def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict = None) -> Target: +def convert_to_target( + conf_dict: Mapping[str, Any], + props_dict: Mapping[str, Any] | None = None, + defs_dict: Mapping[str, Any] | None = None, +) -> Target: """Uses configuration, properties and pulse defaults dicts to construct and return Target class. """ @@ -47,7 +55,7 @@ def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict # Parse from properties if it exsits if props_dict is not None: # Parse instructions - gates = {} + gates: dict[str, dict[tuple, InstructionProperties]] = {} for gate in props_dict["gates"]: name = gate["gate"] if name in name_mapping: @@ -132,7 +140,7 @@ def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict return target -def qubit_props_from_props(properties: dict) -> list: +def qubit_props_from_props(properties: dict) -> list[QubitProperties]: """Returns a dictionary of `qiskit.providers.backend.QubitProperties` using a backend properties dictionary created by loading props.json payload. """ diff --git a/qiskit/providers/fake_provider/utils/configurable_backend.py b/qiskit/providers/fake_provider/utils/configurable_backend.py index a3dd72eed97a..676d7a060454 100644 --- a/qiskit/providers/fake_provider/utils/configurable_backend.py +++ b/qiskit/providers/fake_provider/utils/configurable_backend.py @@ -11,6 +11,8 @@ # that they have been altered from the originals. """Configurable backend.""" +from __future__ import annotations + import itertools from datetime import datetime from typing import Optional, List, Union @@ -38,7 +40,7 @@ def __init__( self, name: str, n_qubits: int, - version: Optional[str] = None, + version: str | None = None, coupling_map: Optional[List[List[int]]] = None, basis_gates: Optional[List[str]] = None, qubit_t1: Optional[Union[float, List[float]]] = None, diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index e346e293a38b..15982b53e5ff 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -11,11 +11,14 @@ # that they have been altered from the originals. """Backend Configuration Classes.""" +from __future__ import annotations + import re import copy import numbers -from typing import Dict, List, Any, Iterable, Tuple, Union from collections import defaultdict +from collections.abc import Iterable +from typing import Any from qiskit.exceptions import QiskitError from qiskit.providers.exceptions import BackendConfigurationError @@ -40,13 +43,13 @@ class GateConfig: def __init__( self, - name, + name: str, parameters, - qasm_def, + qasm_def: str, coupling_map=None, latency_map=None, - conditional=None, - description=None, + conditional: bool | None = None, + description: str | None = None, ): """Initialize a GateConfig object @@ -213,34 +216,34 @@ class QasmBackendConfiguration: def __init__( self, - backend_name, - backend_version, - n_qubits, + backend_name: str, + backend_version: str, + n_qubits: int, basis_gates, gates, - local, - simulator, - conditional, - open_pulse, - memory, - max_shots, + local: bool, + simulator: bool, + conditional: bool, + open_pulse: bool, + memory: bool, + max_shots: int, coupling_map, supported_instructions=None, dynamic_reprate_enabled=False, rep_delay_range=None, - default_rep_delay=None, - max_experiments=None, + default_rep_delay: float = None, + max_experiments: int | None = None, sample_name=None, n_registers=None, register_map=None, - configurable=None, + configurable: bool | None = None, credits_required=None, online_date=None, - display_name=None, - description=None, + display_name: str | None = None, + description: str | None = None, tags=None, - dt=None, - dtm=None, + dt: float | None = None, + dtm: float | None = None, processor_type=None, parametric_pulses=None, **kwargs, @@ -384,7 +387,7 @@ def __getattr__(self, name): raise AttributeError(f"Attribute {name} is not defined") from ex @classmethod - def from_dict(cls, data): + def from_dict(cls: type["QasmBackendConfiguration"], data: dict) -> QasmBackendConfiguration: """Create a new GateConfig object from a dictionary. Args: @@ -506,8 +509,8 @@ def __init__( backend_name: str, backend_version: str, n_qubits: int, - basis_gates: List[str], - gates: GateConfig, + basis_gates: list[str], + gates: list[GateConfig], local: bool, simulator: bool, conditional: bool, @@ -516,31 +519,31 @@ def __init__( max_shots: int, coupling_map, n_uchannels: int, - u_channel_lo: List[List[UchannelLO]], - meas_levels: List[int], - qubit_lo_range: List[List[float]], - meas_lo_range: List[List[float]], + u_channel_lo: list[list[UchannelLO]], + meas_levels: list[int], + qubit_lo_range: list[list[float]], + meas_lo_range: list[list[float]], dt: float, dtm: float, - rep_times: List[float], - meas_kernels: List[str], - discriminators: List[str], - hamiltonian: Dict[str, Any] = None, + rep_times: list[float], + meas_kernels: list[str], + discriminators: list[str], + hamiltonian: dict[str, Any] | None = None, channel_bandwidth=None, acquisition_latency=None, conditional_latency=None, meas_map=None, - max_experiments=None, - sample_name=None, - n_registers=None, + max_experiments: int | None = None, + sample_name: str | None = None, + n_registers: int | None = None, register_map=None, - configurable=None, - credits_required=None, + configurable: bool | None = None, + credits_required: bool | None = None, online_date=None, - display_name=None, - description=None, + display_name: str | None = None, + description: str | None = None, tags=None, - channels: Dict[str, Any] = None, + channels: dict[str, Any] | None = None, **kwargs, ): """ @@ -785,7 +788,7 @@ def sample_rate(self) -> float: return 1.0 / self.dt @property - def control_channels(self) -> Dict[Tuple[int, ...], List]: + def control_channels(self) -> dict[tuple[int, ...], list]: """Return the control channels""" return self._control_channels @@ -829,7 +832,7 @@ def acquire(self, qubit: int) -> AcquireChannel: raise BackendConfigurationError(f"Invalid index for {qubit}-qubit systems.") return AcquireChannel(qubit) - def control(self, qubits: Iterable[int] = None) -> List[ControlChannel]: + def control(self, qubits: Iterable[int] = None) -> list[ControlChannel]: """ Return the secondary drive channel for the given qubit -- typically utilized for controlling multiqubit interactions. This channel is derived from other channels. @@ -859,7 +862,7 @@ def control(self, qubits: Iterable[int] = None) -> List[ControlChannel]: f"This backend - '{self.backend_name}' does not provide channel information." ) from ex - def get_channel_qubits(self, channel: Channel) -> List[int]: + def get_channel_qubits(self, channel: Channel) -> list[int]: """ Return a list of indices for qubits which are operated on directly by the given ``channel``. @@ -879,7 +882,7 @@ def get_channel_qubits(self, channel: Channel) -> List[int]: f"This backend - '{self.backend_name}' does not provide channel information." ) from ex - def get_qubit_channels(self, qubit: Union[int, Iterable[int]]) -> List[Channel]: + def get_qubit_channels(self, qubit: int | Iterable[int]) -> list[Channel]: r"""Return a list of channels which operate on the given ``qubit``. Raises: @@ -910,7 +913,7 @@ def get_qubit_channels(self, qubit: Union[int, Iterable[int]]) -> List[Channel]: f"This backend - '{self.backend_name}' does not provide channel information." ) from ex - def describe(self, channel: ControlChannel) -> Dict[DriveChannel, complex]: + def describe(self, channel: ControlChannel) -> dict[DriveChannel, complex]: """ Return a basic description of the channel dependency. Derived channels are given weights which describe how their frames are linked to other frames. @@ -940,7 +943,13 @@ def describe(self, channel: ControlChannel) -> Dict[DriveChannel, complex]: result[DriveChannel(u_chan_lo.q)] = u_chan_lo.scale return result - def _parse_channels(self, channels: Dict[set, Any]) -> Dict[Any, Any]: + def _parse_channels( + self, channels: dict[str, Any] + ) -> tuple[ + dict[tuple, list[int]], + dict[DriveChannel | ControlChannel | MeasureChannel | AcquireChannel, list], + dict[tuple, list[int]], + ]: r""" Generates a dictionaries of ``Channel``\s, and tuple of qubit(s) they operate on. @@ -954,9 +963,11 @@ def _parse_channels(self, channels: Dict[set, Any]) -> Dict[Any, Any]: control_channels: Dictionary mapping tuple of qubit(s), to list of ``ControlChannel``\s. """ - qubit_channel_map = defaultdict(list) - channel_qubit_map = defaultdict(list) - control_channels = defaultdict(list) + qubit_channel_map: dict[tuple, list[int]] = defaultdict(list) + channel_qubit_map: dict[ + DriveChannel | ControlChannel | MeasureChannel | AcquireChannel, list + ] = defaultdict(list) + control_channels: dict[tuple, list[int]] = defaultdict(list) channels_dict = { DriveChannel.prefix: DriveChannel, ControlChannel.prefix: ControlChannel, @@ -974,7 +985,7 @@ def _parse_channels(self, channels: Dict[set, Any]) -> Dict[Any, Any]: control_channels[qubits].append(channel_type(index)) return dict(qubit_channel_map), dict(channel_qubit_map), dict(control_channels) - def _get_channel_prefix_index(self, channel: str) -> str: + def _get_channel_prefix_index(self, channel: str) -> tuple[str, int]: """Return channel prefix and index from the given ``channel``. Args: diff --git a/qiskit/providers/models/backendproperties.py b/qiskit/providers/models/backendproperties.py index 1f5a190bd5de..c43efcc7f8fe 100644 --- a/qiskit/providers/models/backendproperties.py +++ b/qiskit/providers/models/backendproperties.py @@ -11,10 +11,11 @@ # that they have been altered from the originals. """Backend Properties classes.""" +from __future__ import annotations import copy import datetime -from typing import Any, Iterable, Tuple, Union +from collections.abc import Iterable import dateutil.parser from qiskit.providers.exceptions import BackendPropertyError @@ -31,7 +32,7 @@ class Nduv: value: value. """ - def __init__(self, date, name, unit, value): + def __init__(self, date: datetime.datetime, name: str, unit: str, value: float): """Initialize a new name-date-unit-value object Args: @@ -94,7 +95,7 @@ class GateProperties: _data = {} - def __init__(self, qubits, gate, parameters, **kwargs): + def __init__(self, qubits: list[int], gate: str, parameters: list[Nduv], **kwargs): """Initialize a new :class:`GateProperties` object Args: @@ -171,7 +172,14 @@ class BackendProperties: _data = {} def __init__( - self, backend_name, backend_version, last_update_date, qubits, gates, general, **kwargs + self, + backend_name: str, + backend_version: str, + last_update_date: datetime.datetime | str, + qubits: list[list[Nduv]], + gates: list[GateProperties], + general: list[Nduv], + **kwargs, ): """Initialize a BackendProperties instance. @@ -198,15 +206,17 @@ def __init__( self.qubits = qubits self.gates = gates - self._qubits = {} + self._qubits: dict[int, dict[str, tuple[float, datetime.datetime]]] = {} for qubit, props in enumerate(qubits): - formatted_props = {} + formatted_props: dict[str, tuple[float, datetime.datetime]] = {} for prop in props: value = self._apply_prefix(prop.value, prop.unit) formatted_props[prop.name] = (value, prop.date) self._qubits[qubit] = formatted_props - self._gates = {} + self._gates: dict[ + str, dict[tuple[int, ...], dict[str, tuple[float, datetime.datetime]]] + ] = {} for gate in gates: if gate.gate not in self._gates: self._gates[gate.gate] = {} @@ -279,8 +289,8 @@ def __eq__(self, other): return False def gate_property( - self, gate: str, qubits: Union[int, Iterable[int]] = None, name: str = None - ) -> Tuple[Any, datetime.datetime]: + self, gate: str, qubits: int | Iterable[int] | None = None, name: str | None = None + ) -> tuple[float, datetime.datetime] | dict[tuple[int, ...], tuple[float, datetime.datetime]]: """ Return the property of the given gate. @@ -326,7 +336,7 @@ def faulty_gates(self): faulty.append(gate) return faulty - def is_gate_operational(self, gate: str, qubits: Union[int, Iterable[int]] = None) -> bool: + def is_gate_operational(self, gate: str, qubits: int | Iterable[int] | None = None) -> bool: """ Return the operational status of the given gate. @@ -343,7 +353,7 @@ def is_gate_operational(self, gate: str, qubits: Union[int, Iterable[int]] = Non return bool(properties["operational"][0]) return True # if property operational not existent, then True. - def gate_error(self, gate: str, qubits: Union[int, Iterable[int]]) -> float: + def gate_error(self, gate: str, qubits: int | Iterable[int]) -> float: """ Return gate error estimates from backend properties. @@ -356,7 +366,7 @@ def gate_error(self, gate: str, qubits: Union[int, Iterable[int]]) -> float: """ return self.gate_property(gate, qubits, "gate_error")[0] # Throw away datetime at index 1 - def gate_length(self, gate: str, qubits: Union[int, Iterable[int]]) -> float: + def gate_length(self, gate: str, qubits: int | Iterable[int]) -> float: """ Return the duration of the gate in units of seconds. @@ -369,7 +379,9 @@ def gate_length(self, gate: str, qubits: Union[int, Iterable[int]]) -> float: """ return self.gate_property(gate, qubits, "gate_length")[0] # Throw away datetime at index 1 - def qubit_property(self, qubit: int, name: str = None) -> Tuple[Any, datetime.datetime]: + def qubit_property( + self, qubit: int, name: str | None = None + ) -> tuple[float, datetime.datetime] | dict[str, tuple[float, datetime.datetime]]: """ Return the property of the given qubit. diff --git a/qiskit/providers/models/jobstatus.py b/qiskit/providers/models/jobstatus.py index 2fc58e437ab9..44f2bd8151cd 100644 --- a/qiskit/providers/models/jobstatus.py +++ b/qiskit/providers/models/jobstatus.py @@ -22,7 +22,7 @@ class JobStatus: status_msg (str): status message. """ - _data = {} + _data: dict[str, str] = {} def __init__(self, job_id, status, status_msg, **kwargs): self._data = {} @@ -32,7 +32,7 @@ def __init__(self, job_id, status, status_msg, **kwargs): self._data.update(kwargs) @classmethod - def from_dict(cls, data): + def from_dict(cls, data: dict[str, str]) -> "JobStatus": """Create a new JobStatus object from a dictionary. Args: @@ -45,7 +45,7 @@ def from_dict(cls, data): """ return cls(**data) - def to_dict(self): + def to_dict(self) -> dict[str, str]: """Return a dictionary format representation of the JobStatus. Returns: diff --git a/qiskit/providers/models/pulsedefaults.py b/qiskit/providers/models/pulsedefaults.py index 13becb1c956d..a436c3bc9155 100644 --- a/qiskit/providers/models/pulsedefaults.py +++ b/qiskit/providers/models/pulsedefaults.py @@ -12,7 +12,9 @@ """Model and schema for pulse defaults.""" -from typing import Any, Dict, List +from __future__ import annotations + +from typing import Any from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap, PulseQobjDef from qiskit.qobj import PulseLibraryItem, PulseQobjInstruction @@ -98,9 +100,11 @@ class Command: name: Pulse command name. """ - _data = {} + _data: dict[str, Any] = {} - def __init__(self, name: str, qubits=None, sequence=None, **kwargs): + def __init__( + self, name: str, qubits=None, sequence: PulseQobjInstruction | None = None, **kwargs + ): """Initialize a Command object Args: @@ -123,7 +127,7 @@ def __getattr__(self, name): except KeyError as ex: raise AttributeError(f"Attribute {name} is not defined") from ex - def to_dict(self): + def to_dict(self) -> dict[str, Any]: """Return a dictionary format representation of the Command. Returns: @@ -170,14 +174,14 @@ class PulseDefaults: def __init__( self, - qubit_freq_est: List[float], - meas_freq_est: List[float], + qubit_freq_est: list[float], + meas_freq_est: list[float], buffer: int, - pulse_library: List[PulseLibraryItem], - cmd_def: List[Command], - meas_kernel: MeasurementKernel = None, - discriminator: Discriminator = None, - **kwargs: Dict[str, Any], + pulse_library: list[PulseLibraryItem], + cmd_def: list[Command], + meas_kernel: MeasurementKernel | None = None, + discriminator: Discriminator | None = None, + **kwargs: dict[str, Any], ): """ Validate and reformat transport layer inputs to initialize.