Skip to content

[BUG] KeyError in init_subroutine_scope when custom_gates key missing in Context initialization #8931

@huhu37

Description

@huhu37

Expected behavior

The Context class should handle missing optional keys. Specifically, if custom_gates is not provided during initialization, it should default to an empty dictionary or similar structure to avoid runtime errors.

Actual behavior

When a Context object is initialized with a dictionary that does not contain the custom_gates key, calling init_subroutine_scope results in a KeyError.

Additional information

No response

Source code

from pennylane.io.qasm_interpreter import Context

class MockName:
    def __init__(self, name):
        self.name = name

class MockSubroutineDefinition:
    def __init__(self, name, arguments, body):
        self.name = name
        self.arguments = arguments
        self.body = body
        
context_dict = {'scopes': {'subroutines': {}}}
ctx = Context(context_dict)
node = MockSubroutineDefinition(name=MockName('subroutine_example'), arguments=[], body=[])
ctx.init_subroutine_scope(node)

Tracebacks

Traceback (most recent call last):
  File "/path/to/dict_error.py", line 16, in <module>
    ctx.init_subroutine_scope(node)
  File "/path/to/pennylane/io/qasm_interpreter.py", line 335, in init_subroutine_scope
    "custom_gates": self.scopes["custom_gates"],
                    ~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'custom_gates'

System information

Name: pennylane
Version: 0.44.0
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page: 
Author: 
License: 
Location: /home/xyzb/miniconda3/envs/qml440/lib/python3.11/site-packages
Platform info:           Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39
Python version:          3.11.14
Numpy version:           2.4.1
Scipy version:           1.17.0
JAX version:             None
Installed devices:
- default.clifford (pennylane-0.44.0)
- default.gaussian (pennylane-0.44.0)
- default.mixed (pennylane-0.44.0)
- default.qubit (pennylane-0.44.0)
- default.qutrit (pennylane-0.44.0)
- default.qutrit.mixed (pennylane-0.44.0)
- default.tensor (pennylane-0.44.0)
- null.qubit (pennylane-0.44.0)
- reference.qubit (pennylane-0.44.0)
- lightning.qubit (pennylane_lightning-0.44.0)

Existing GitHub issues

  • I have searched existing GitHub issues to make sure the issue does not already exist.

Metadata

Metadata

Labels

bug 🐛Something isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions