Skip to content

Commit

Permalink
Add deprecation warnings for main module imports (#1813)
Browse files Browse the repository at this point in the history
This instructs users to use direct imports or to use
`DeviceFactory.create()` instead of importing directly through the
`miio` module.
  • Loading branch information
rytilahti authored Aug 27, 2023
1 parent fb0a63b commit 6171ec5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
28 changes: 28 additions & 0 deletions miio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,32 @@

from miio.discovery import Discovery


def __getattr__(name):
"""Create deprecation warnings on classes that are going away."""
from warnings import warn

current_globals = globals()

def _is_miio_integration(x):
"""Return True if miio.integrations is in the module 'path'."""
module_ = current_globals[x]
if "miio.integrations" in str(module_):
return True

return False

deprecated_module_mapping = {
str(x): current_globals[x] for x in current_globals if _is_miio_integration(x)
}
if new_module := deprecated_module_mapping.get(name):
warn(
f"Importing {name} directly from 'miio' is deprecated, import {new_module} or use DeviceFactory.create() instead",
DeprecationWarning,
)
return globals()[new_module.__name__]

raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


__version__ = version("python-miio")
16 changes: 16 additions & 0 deletions miio/tests/test_miio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Tests for the main module."""
import pytest

import miio


@pytest.mark.parametrize(
("old_name", "new_name"),
[("RoborockVacuum", "miio.integrations.roborock.vacuum.vacuum.RoborockVacuum")],
)
def test_deprecation_warning(old_name, new_name):
"""Check that deprecation warning gets emitted for deprecated imports."""
with pytest.deprecated_call(
match=rf"Importing {old_name} directly from 'miio' is deprecated, import <class '{new_name}'> or use DeviceFactory.create\(\) instead"
):
miio.__getattr__(old_name)

0 comments on commit 6171ec5

Please sign in to comment.