diff --git a/quantecon/filter.py b/quantecon/filter.py index a78a67d2..36e93928 100644 --- a/quantecon/filter.py +++ b/quantecon/filter.py @@ -5,6 +5,9 @@ import warnings from . import _filter +# Cache for DeprecationWarning messages to avoid repeated message construction +_warn_msg_cache: dict[str, str] = {} + __all__ = ['hamilton_filter'] @@ -16,13 +19,20 @@ def __dir__(): def __getattr__(name): if name not in __all__: raise AttributeError( - "`quantecon.filter` is deprecated and has no attribute " - f"'{name}'." - ) - - warnings.warn(f"Please use `{name}` from the `quantecon` namespace, " - "the `quantecon.filter` namespace is deprecated. You can use" - f" the following instead:\n `from quantecon import {name}`.", - category=DeprecationWarning, stacklevel=2) + "`quantecon.filter` is deprecated and has no attribute " + f"'{name}'." + ) + + # Optimize warning message formatting + msg = _warn_msg_cache.get(name) + if msg is None: + msg = ( + f"Please use `{name}` from the `quantecon` namespace, " + "the `quantecon.filter` namespace is deprecated. You can use" + f" the following instead:\n `from quantecon import {name}`." + ) + _warn_msg_cache[name] = msg + + warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return getattr(_filter, name)