AnswerDotAI / AnswerDotAI/fastcore
issue in patch decorator when worker with abstract classes
- Dominant language
- Jupyter Notebook
- Stars
- 1.1k
- Forks
- 295
- Avg merge
- 1d 6h
- Merged PRs (30d)
- 7
Description
`patch` decorator is a little bit problematic when working with abstract classes,
consider the following code:
```python
from abc import ABC, abstractmethod
from fastcore.basics import patch
class A(ABC):
@abstractmethod
def foo(self):
pass
class B(A):
def __init__(self):
pass
@patch
def foo(self : B):
print("foo patched to B")
a = B()
Executing the code yields this error:
```
```prolog
TypeError: Can't instantiate abstract class B with abstract methods foo
```
The reason for that problem is that in Python each class that is inheriting from an abstract class he starts with an attribute called __abstractmethods__ which is a frozenset that contains a set of functions that should be implemented by the child class, this attribute gets updated only in the scope of the class definition and at the end the set should be empty i.e the child class has implemented all the abstractmethods, since we are using patch to separate functions into different cells, Python doesn't see that we actually implemented the required functions.
possible solution, that's the decorator that we used in our code (you can learn from it what you should do to fix on your end):
```python
def patch_method(func : Callable, *args, **kwargs) -> None:
"""
Applies fastcore's `patch` decorator and removes `func` from `cls.__abstractsmethods__` in case
`func` is an `abstractmethods`
"""
cls = next(iter(get_type_hints(func).values()))
try:
abstracts_needed = set(cls.__abstractmethods__)
abstracts_needed.discard(func.__name__)
cls.__abstractmethods__ = abstracts_needed
except AttributeError: # If the class does not inherit from an abstract class
pass
finally:
# Apply the original `patch` decorator
patch(*args, **kwargs)(func)
```
Contributor guide
Research direction
Start at the fastcore.basics.patch decorator and reproduce the abstract-class example from the issue. Confirm that a class patched with its required abstract method can be instantiated and that the patched method runs; use the provided patch_method implementation as a reference for the intended behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100