Skip to content
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
36 changes: 36 additions & 0 deletions packages/reflex-base/src/reflex_base/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,9 @@ def _post_init(self, **kwargs):
for key, env_value in env_kwargs.items():
setattr(self, key, env_value)

# Normalize plugins: auto-instantiate Plugin subclasses, reject bad values.
self._normalize_plugins()

# Normalize disable_plugins: convert strings and Plugin subclasses to instances.
self._normalize_disable_plugins()

Expand Down Expand Up @@ -382,6 +385,39 @@ def _post_init(self, **kwargs):
msg = f"{self._prefixes[0]}REDIS_URL is required when using the redis state manager."
raise ConfigError(msg)

def _normalize_plugins(self):
"""Normalize ``plugins`` entries to Plugin instances.

Auto-instantiates Plugin subclasses passed without parentheses (e.g.
``plugins=[SitemapPlugin]``) so they behave the same as
``plugins=[SitemapPlugin()]``. Any entry that is neither a Plugin
subclass nor a Plugin instance raises ``ConfigError`` with a message
that names the offending value, instead of failing later in the
compiler with a confusing ``TypeError`` about a missing ``self``.
"""
normalized: list[Plugin] = []
for entry in self.plugins:
if isinstance(entry, Plugin):
normalized.append(entry)
elif isinstance(entry, type) and issubclass(entry, Plugin):
try:
normalized.append(entry())
except TypeError as exc:
msg = (
f"reflex.Config.plugins entry {entry.__name__!r} could not be "
f"instantiated and may require arguments; pass an instance "
f"instead, e.g. plugins=[{entry.__name__}(...)]."
)
raise ConfigError(msg) from exc
Comment on lines +403 to +411

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 TypeError catch is too broad

TypeError can be raised inside a Plugin's __init__ for reasons unrelated to missing arguments (e.g. an internal type mismatch). When that happens the user sees "requires constructor arguments; pass an instance instead" even though the real failure is a bug inside __init__. The from exc chain surfaces the real cause, but the primary message is misleading.

A tighter guard would inspect inspect.signature before calling the constructor:

import inspect

elif isinstance(entry, type) and issubclass(entry, Plugin):
    sig = inspect.signature(entry.__init__)
    required = [
        p for p in list(sig.parameters.values())[1:]  # skip 'self'
        if p.default is inspect.Parameter.empty
        and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
    ]
    if required:
        msg = (
            f"reflex.Config.plugins entry {entry.__name__!r} is a Plugin "
            f"class that requires constructor arguments; pass an instance "
            f"instead, e.g. plugins=[{entry.__name__}(...)]."
        )
        raise ConfigError(msg)
    normalized.append(entry())

This raises ConfigError before attempting construction, so any unrelated TypeError from inside __init__ propagates as-is rather than being swallowed into the misleading message.

else:
msg = (
f"reflex.Config.plugins must contain Plugin instances, but got "
f"{entry!r} of type {type(entry).__name__}. "
f"Pass an instance, e.g. plugins=[SitemapPlugin()]."
)
raise ConfigError(msg)
self.plugins = normalized

def _normalize_disable_plugins(self):
"""Normalize disable_plugins list entries to Plugin subclasses.

Expand Down
34 changes: 34 additions & 0 deletions tests/units/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from reflex_base.constants import Endpoint, Env
from reflex_base.plugins import Plugin
from reflex_base.plugins.sitemap import SitemapPlugin
from reflex_base.utils.exceptions import ConfigError

import reflex as rx
from reflex.environment import (
Expand Down Expand Up @@ -557,3 +558,36 @@ def test_no_disable_adds_builtin(self):
"""Test that builtin plugins are added when not disabled."""
config = rx.Config(app_name="test")
assert any(isinstance(p, SitemapPlugin) for p in config.plugins)


def test_plugins_instance_passthrough():
"""A Plugin instance is kept as-is (issue #6440)."""
instance = SitemapPlugin()
config = rx.Config(app_name="test", plugins=[instance])
assert instance in config.plugins


def test_plugins_class_auto_instantiated():
"""A Plugin subclass is auto-instantiated rather than raising deep in the compiler (issue #6440)."""
config = rx.Config(app_name="test", plugins=[SitemapPlugin]) # pyright: ignore[reportArgumentType]
instances = [p for p in config.plugins if isinstance(p, SitemapPlugin)]
assert len(instances) == 1
# And it must be an instance, not the class itself.
assert not isinstance(instances[0], type)


def test_plugins_invalid_value_raises_config_error():
"""A non-Plugin value raises ConfigError naming the entry, not a deep TypeError (issue #6440)."""
with pytest.raises(ConfigError, match=r"reflex\.Config\.plugins"):
rx.Config(app_name="test", plugins=["not-a-plugin"]) # pyright: ignore[reportArgumentType]


def test_plugins_class_requiring_args_raises_config_error():
"""A Plugin subclass that needs constructor args raises a clear ConfigError (issue #6440)."""

class NeedsArgs(Plugin):
def __init__(self, required):
self.required = required

with pytest.raises(ConfigError, match="NeedsArgs"):
rx.Config(app_name="test", plugins=[NeedsArgs]) # pyright: ignore[reportArgumentType]
Loading