Skip to content

Commit

Permalink
Raise warning when a method is overwritten (#161)
Browse files Browse the repository at this point in the history
* Raise warning when a method is overwritten

* Test MethodRedefintionWarning

* Explicity resolve registrations
  • Loading branch information
wesselb authored Jun 13, 2024
1 parent 9e23f75 commit 25f4e5f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
11 changes: 11 additions & 0 deletions plum/resolver.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pydoc
import sys
import warnings
from functools import wraps
from typing import Callable, Optional, Tuple, Union

Expand All @@ -14,6 +15,10 @@
__all__ = ["AmbiguousLookupError", "NotFoundLookupError"]


class MethodRedefinitionWarning(Warning):
"""A method is redefined."""


def _render_function_call(f: str, target: Union[Tuple, Signature]) -> str:
"""Render a function call.
Expand Down Expand Up @@ -260,6 +265,12 @@ def register(self, method: Method) -> None:
f"The added method `{method}` is equal to {sum(existing)} "
f"existing methods. This should never happen."
)
previous_method = self.methods[existing.index(True)]
warnings.warn(
f"`{method}` overwrites the earlier definition `{previous_method}`.",
category=MethodRedefinitionWarning,
stacklevel=0,
)
self.methods[existing.index(True)] = method
else:
self.methods.append(method)
Expand Down
29 changes: 29 additions & 0 deletions tests/test_resolver.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import sys
import textwrap
import typing
import warnings

import pytest

import plum.resolver
from plum.dispatcher import Dispatcher
from plum.method import Method
from plum.resolver import (
AmbiguousLookupError,
MethodRedefinitionWarning,
NotFoundLookupError,
Resolver,
_document,
Expand Down Expand Up @@ -242,3 +245,29 @@ def f(x):
assert r.resolve(m_c1.signature) == m_b1
m_b2.signature.precedence = 2
assert r.resolve(m_c1.signature) == m_b2


def test_redefinition_warning():
dispatch = Dispatcher()

with warnings.catch_warnings():
warnings.simplefilter("error")

@dispatch
def f(x: int):
pass

@dispatch
def f(x: str):
pass

# Warnings are only emitted when all registrations are resolved.
f._resolve_pending_registrations()

with pytest.warns(MethodRedefinitionWarning):

@dispatch
def f(x: int):
pass

f._resolve_pending_registrations()

0 comments on commit 25f4e5f

Please sign in to comment.