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?: recursion error on Sanic subclass initialisation #2072

Merged
merged 4 commits into from
Mar 21, 2021
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
27 changes: 4 additions & 23 deletions sanic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,19 @@
from sanic.mixins.signals import SignalMixin


class Base(type):
def __new__(cls, name, bases, attrs):
init = attrs.get("__init__")

def __init__(self, *args, **kwargs):
nonlocal init
nonlocal name

bases = [
b for base in type(self).__bases__ for b in base.__bases__
]

for base in bases:
base.__init__(self, *args, **kwargs)

if init:
init(self, *args, **kwargs)

attrs["__init__"] = __init__
return type.__new__(cls, name, bases, attrs)


class BaseSanic(
RouteMixin,
MiddlewareMixin,
ListenerMixin,
ExceptionMixin,
SignalMixin,
metaclass=Base,
):
__fake_slots__: Tuple[str, ...]

def __init__(self, *args, **kwargs) -> None:
for base in BaseSanic.__bases__:
base.__init__(self, *args, **kwargs) # type: ignore

def __str__(self) -> str:
return f"<{self.__class__.__name__} {self.name}>"

Expand Down
1 change: 1 addition & 0 deletions sanic/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def __init__(
version: Optional[int] = None,
strict_slashes: Optional[bool] = None,
):
super().__init__()

self._apps: Set[Sanic] = set()
self.ctx = SimpleNamespace()
Expand Down
7 changes: 7 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,10 @@ def test_app_set_context(app):

retrieved = Sanic.get_app(app.name)
assert retrieved.ctx.foo == 1


def test_subclass_initialisation():
class CustomSanic(Sanic):
pass

CustomSanic("test_subclass_initialisation")