Skip to content

<c-element c-is="..."> raises TypeError when the tag comes from a constant input #107

Closed

Description

@joeyjurjens

Version

citry 0.4.6, citry-core 1.6.1

What happened?

A component reads a Kwargs value and passes it to <c-element c-is="...">.

Calling the component from Python works. Rendering the same component from a
template raises:

TypeError: expected string or bytes-like object, got '_ConstProxy'

The traceback ends in citry/components/dynamic.py:

def _validate_tag_name(tag: Any) -> None:
    if not tag or not isinstance(tag, str):
        msg = f"<c-element> requires an 'is' value naming the HTML tag, got {type(tag).__name__}."
        raise TypeError(msg)
    if not _VALID_NAME_RE.fullmatch(tag):   # <- raises here

The value is a _ConstProxy. It passes isinstance(tag, str), so the guard on
the line above does not catch it, but re.fullmatch rejects it.

Const is documented as "a transparent marker that a value is constant across
renders", and const_value() returns the underlying 'span':

>>> is_const(value)
True
>>> const_value(value)
'span'
>>> re.fullmatch(r"[a-z]+", const_value(value))
<re.Match object; span=(0, 4), match='span'>

I expected rendering from a template to behave the same as calling the
component from Python.

Which forms trigger it:

call result
Heading(as_="span") from Python works
<c-heading as_="span" /> TypeError
<c-heading c-as_="'span'" /> TypeError
<c-heading c-as_="tag" /> with tag a render variable works
<c-heading c-bind="d" /> with d = {"as_": "span"} works

The failing cases are the ones where the value is constant-foldable.

Minimal reproduction

from citry import Citry, Component

app = Citry(autodiscover=False)


class Heading(Component):
    citry = app

    class Kwargs:
        as_: str = "div"

    def template_data(self, kwargs, slots):
        return {"tag": kwargs.as_}

    template = '<c-element c-is="tag">hello</c-element>'


print(str(Heading(as_="span")))
print(app.render_template('<c-heading as_="span" />', {}).serialize())


Output:

<span data-cid-cnjt5sc1u="">hello</span>

Traceback (most recent call last):
  ...
  File ".../citry/components/dynamic.py", line 198, in _validate_tag_name
    if not _VALID_NAME_RE.fullmatch(tag):
TypeError: An error occurred while rendering components TemplateRoot > Heading > DynamicElement:
expected string or bytes-like object, got '_ConstProxy'

Environment

Python 3.12.9, macOS 15.3.2

Activity

  1. added
    bug
    on Sep 9, 2026
  2. JuroOravec commented on Sep 9, 2026

    @JuroOravec
    Member

    Hey Joey, thanks for reporting! I'm fixing it now, will release 0.5.0 with the fix later today.

  3. JuroOravec commented on Sep 10, 2026

    @JuroOravec
    Member

    Now fixed in v0.5.0 🎉

  4. joeyjurjens commented on Sep 10, 2026

    @joeyjurjens
    Author

    Now fixed in v0.5.0 🎉

    Still some issues depending on python version

    python 3.11: str-subclass=True base=ObjectProxy | /tmp/x
    python 3.13: str-subclass=True base=ObjectProxy | TypeError: expected str,
                 bytes or os.PathLike object, not _ConstProxy
    
  5. joeyjurjens commented on Sep 11, 2026

    @joeyjurjens
    Author

    @JuroOravec I'm still having some issues regarding this:

    The 0.5.0 fix covers the path where citry itself consumes a marked value - this now works, where 0.4.6 raised TypeError: ... got '_ConstProxy':

    <c-element c-is="tag" c-class="cls">x</c-element>
    

    But the marker still reaches template_data, so component code gets it.

    ContainerFluid = Breakpoint | Literal["fluid"] | bool   # True, or "md" for a breakpoint
    
    
    class Container(LibraryComponent):
        class Kwargs:
            fluid: ContainerFluid | None = None
    
        def template_data(self, kwargs, slots):
            if kwargs.fluid is True:                       # False: it is a _ConstProxy
                container_class = "container-fluid"
            elif kwargs.fluid:                             # truthy, so this branch wins
                container_class = f"container-{kwargs.fluid}"
            ...
    <c-container c-fluid="True">x</c-container>
    
    got:  <div class="container-True">x</div>
    want: <div class="container-fluid">x</div>
    

    Note the c-, so fluid really is the boolean True, not the string. No exception - just wrong output. Five components in my library render this way, and it took a while to find because isinstance(x, str) is True and str(x), == and bool(x) all behave.

    It also raises. citry-phosphor-icons passes a kwarg to a path lookup:

    class Icon(LibraryComponent):
        class Kwargs:
            name: str
            weight: str = "regular"
    
        def template_data(self, kwargs, slots):
            return {"svg": get_svg_inner(kwargs.name, kwargs.weight, style)}
            #                            builds SVGS_DIR / style / weight / f"{name}.svg"
    py3.11: ok
    py3.13: TypeError: expected str, bytes or os.PathLike object, not _ConstProxy
    

    Whether you get an exception or silence depends on whether the callee coerces.
    django.utils.text.slugify starts with value = str(value) and survives; re.sub, "".join and os.fspath do not. All of this behaves identically on 0.4.6 and 0.5.0.

    Workaround, which fixed it for me (for now).

    class PlainValues(Extension):
        name = "plain_values"
        def on_component_input(self, ctx):
            for key, value in list(ctx.kwargs.items()):
                ctx.kwargs[key] = const_value(value)

    This does break cache, cause citry can no longer tell the input was constant and potentially it breaks other things as well, not sure xD

  6. JuroOravec commented on Sep 11, 2026

    @JuroOravec
    Member

    Looking into this. This issue relates to the Const() feature, which is for optimising rendering by telling Citry which inputs never change and can be reused across renders.

    Three relevant parts of the Const() feature is that:

    1. When you define a literal value in a template like <c-MyCard c-disabled="True" />, then Citry knows it's a literal Python True, behind the scenes converts it to <c-MyCard c-disabled="Const(True)" />
    2. Wrapping a value in Const() should create an invisible proxy
    3. The Const() values travel down the component tree just like regular values. This way, there's multiple places that can be optimized if a constant value lands there.

    However, @joeyjurjens what you discovered is that the proxying logic isn't working correctly, two issues:

    1. Turns out that is keyword (value is True) bypasses the proxy logic, and sees _ConstProxy instead of the underlying value.
    2. There's some Python APIs which stubbornly reject the proxy, which resulted in TypeError: expected str, bytes or os.PathLike object, not _ConstProxy

    You've hit those bugs because Citry was passing those proxies directly to template_data() and other methods. But this is a footgun. So instead, template_data() will receive the plain unwrapped values.

    So before:

    <!-- Passes to MyCard {"disabled": Const(True)} -->
    <c-MyCard c-disabled="True" /> 
    class MyCard(Component):
        class Kwargs:
            disabled: bool
    
        def template_data(self, kwargs, slots):
            return {
                # Still Const(True)
                "disabled": kwargs.disabled,
           }

    Afterwards, reexported template variables will no longer keep their proxies:

    <!-- Passes to MyCard {"disabled": Const(True)} -->
    <c-MyCard c-disabled="True" /> 
    class MyCard(Component):
        class Kwargs:
            disabled: bool
    
        def template_data(self, kwargs, slots):
            return {
                # NO LONGER Const(True), BUT ONLY PLAIN True
                "disabled": kwargs.disabled,
           }

    This is something that will have to be fixed upstream either in wrapt or in Python itself. So I opened #124 to track that.


    Note: Turning off the proxies adds about 25% to the overall render time, which is pretty bad. So I'm trying a smart approach where the inputs to methods like template_data() are unwrapped, but if individual results from template_data() match what was originally passed to the component, then I re-wrap it. I'm yet to see if that helps with perf.

  7. joeyjurjens commented on Sep 11, 2026

    @joeyjurjens
    Author

    @JuroOravec Thanks, that plan matches what I did on my side as a temporary fix, so it sounds right to me.

    Two things.

    It is not only is True. is None breaks the same way, and it is much more common in real code. My Bootstrap port does 40 identity tests on its inputs, spread over 16 components, and 33 of them are is not None.

    <c-probe c-flag="None" />
    
    kwargs.flag is None      -> False
    kwargs.flag is not None  -> True
    

    Where you unwrap decides what gets fixed. If you unwrap at the template_data() call, then self.kwargs, js_data() and on_render() still get proxies, and so does the typed Kwargs. That last one matters, because a Pydantic Kwargs with a str field cannot render from a template at all right now:

    class Probe(Component):
        class Kwargs(BaseModel):
            name: str
    
        template = "<span>{{ name }}</span>"
    Probe(name="bob")           -> works
    <c-probe name="bob" />      -> ValidationError: Input should be a valid string
                                   [type=string_type, input_type=_ConstProxy]
    <c-probe c-name="'bob'" />  -> same
    

    Only fields typed str are affected, and str | None too. int, float, bool, list, dict and Literal all pass, because Pydantic either converts the value or compares it. That is why the age: int example in the inputs and validation docs works.

    Unwrapping before cls.Kwargs(**raw_kwargs) in _finalize_inputs() would cover all of it in one place, I think.

    This is the extension I use for now. It keeps the Const() optimisation: extract_const_vars() sees the same variables with it as without.

    from citry import Const, Extension, const_value, is_const
    
    _MARKED = "_plain_inputs_marked"
    
    
    class PlainInputs(Extension):
        name = "plain_inputs"
    
        def on_component_input(self, ctx) -> None:
            marked = {}
            for key, value in ctx.kwargs.items():
                if is_const(value):
                    ctx.kwargs[key] = plain = const_value(value)
                    marked[id(plain)] = plain
            if marked:
                # Held by value as well as by id, so the id cannot be reused by a
                # later object while this render is still running.
                setattr(ctx.component, _MARKED, marked)
    
        def on_component_data(self, ctx) -> None:
            marked = getattr(ctx.component, _MARKED, None)
            if not marked:
                return
            for name, value in ctx.template_data.items():
                if id(value) in marked:
                    ctx.template_data[name] = Const(value)

    I match on identity, not on equality, so a value that only compares equal to an input is not wrapped again.

    I'm not sure about the performance penalty and whether above introduces other bugs I haven't noticed yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions