Skip to content

Commit a9d9863

Browse files
arbitrary_subfolders: Add labscript_devices.deprecated_import_alias to declare when a device
class has moved, providing the ability to still import it under the old name whilst printing a deprecation warning pointing to the new name. Use this function in DummyPseudoclock/__init__.py.
1 parent c6a78d2 commit a9d9863

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

DummyPseudoclock/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,10 @@
1515
if PY2:
1616
str = unicode
1717

18-
from .labscript_device import DummyPseudoclock
18+
from labscript_devices import deprecated_import_alias
19+
20+
21+
# For backwards compatibility with old experiment scripts:
22+
DummyPseudoclock = deprecated_import_alias(
23+
"labscript_devices.DummyPseudoclock.labscript_device.DummyPseudoclock"
24+
)

__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,26 @@ def _import_class_by_fullname(fullname):
159159
return getattr(module, class_name)
160160

161161

162+
def deprecated_import_alias(fullname):
163+
"""A way of allowing a class to be imported from an old location whilst a) not
164+
actually importing it until it is instantiated and b) emitting a warning pointing to
165+
the new import location. fullname must be a fully qualified class name with an
166+
absolute import path. Use by calling in the module where the class used to be:
167+
ClassName = deprecated_import_alias("new.path.to.ClassName")"""
168+
calling_module_name = inspect.getmodule(inspect.stack()[1][0]).__name__
169+
def wrapper(*args, **kwargs):
170+
cls = _import_class_by_fullname(fullname)
171+
shortname = fullname.split('.')[-1]
172+
newmodule = '.'.join(fullname.split('.')[:-1])
173+
msg = """Importing %s from %s is deprecated, please instead import it from %s.
174+
Importing anyway for backward compatibility, but this may cause some
175+
unexpected behaviour."""
176+
msg = dedent(msg) % (shortname, calling_module_name, newmodule)
177+
warnings.warn(msg, stacklevel=2)
178+
return cls(*args, **kwargs)
179+
return wrapper
180+
181+
162182
# Dictionaries containing the import paths to BLACS tab and runviewer parser classes,
163183
# not the classes themselves. These will be populated by calls to register_classes from
164184
# code within register_classes.py files within subfolders of labscript_devices.

0 commit comments

Comments
 (0)