Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix is_overridden with @contextmanager #152

Merged
merged 2 commits into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

-
- Fixed issue with `is_overridden` falsely returning True when the parent method is wrapped ([#149](https://github.com/Lightning-AI/utilities/pull/149))


## [0.9.0] - 2023-06-29
Expand Down
5 changes: 4 additions & 1 deletion src/lightning_utilities/core/overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def is_overridden(method_name: str, instance: object, parent: Type[object]) -> b
instance_attr = getattr(instance, method_name, None)
if instance_attr is None:
return False
# `functools.wraps()` support
# `functools.wraps()` and `@contextmanager` support
if hasattr(instance_attr, "__wrapped__"):
instance_attr = instance_attr.__wrapped__
# `Mock(wraps=...)` support
Expand All @@ -28,5 +28,8 @@ def is_overridden(method_name: str, instance: object, parent: Type[object]) -> b
parent_attr = getattr(parent, method_name, None)
if parent_attr is None:
raise ValueError("The parent should define the method")
# `@contextmanager` support
if hasattr(parent_attr, "__wrapped__"):
parent_attr = parent_attr.__wrapped__

return instance_attr.__code__ != parent_attr.__code__
14 changes: 14 additions & 0 deletions tests/unittests/core/test_overrides.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from contextlib import contextmanager
from functools import partial, wraps
from typing import Any, Callable
from unittest.mock import Mock
Expand All @@ -16,6 +17,16 @@ def training_step(self):
...


class Strategy:
@contextmanager
def model_sharded_context():
...


class SingleDeviceStrategy(Strategy):
...


def test_is_overridden():
assert not is_overridden("whatever", object(), parent=LightningModule)

Expand Down Expand Up @@ -65,3 +76,6 @@ def bar(self):
model = BoringModel()
model.training_step = partial(model.training_step)
assert is_overridden("training_step", model, parent=LightningModule)

# `@contextmanager` support
assert not is_overridden("model_sharded_context", SingleDeviceStrategy(), Strategy)
Loading