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

StrictDefaultUndefined not working #57

Closed
hardiksondagar opened this issue Jul 28, 2022 · 3 comments
Closed

StrictDefaultUndefined not working #57

hardiksondagar opened this issue Jul 28, 2022 · 3 comments

Comments

@hardiksondagar
Copy link

Code

from typing import Any
from liquid import Environment
from liquid import StrictUndefined
from liquid.exceptions import UndefinedError
from liquid.expression import EMPTY
from liquid import Mode

from liquid.filter import liquid_filter
from liquid import is_undefined

@liquid_filter
def default_undefined(
    obj: object,
    default_: object = "",
    *,
    allow_false: bool = False
) -> object:
    """Return a default value if the input is undefined, nil, false, or empty."""
    _obj = obj
    # import ipdb; ipdb.set_trace()
    if hasattr(obj, "__liquid__"):
        _obj = obj.__liquid__()

    if allow_false is True and _obj is False:
        return obj

    if is_undefined(_obj) or _obj in (None, False, EMPTY):
        return default_

    return obj

class StrictDefaultUndefined(StrictUndefined):

    def __getattribute__(self, name: str) -> Any:
        if name in (
            "__repr__",
            "__liquid__",
            "__class__",
            "name",
            "hint",
            "obj",
            "hint",
            "msg",
        ):
            return super().__getattribute__(name)
        raise UndefinedError(self.msg)



env = Environment(undefined=StrictDefaultUndefined, tolerance=Mode.STRICT)
env.add_filter("default", default_undefined)

template = env.from_string('Hello {{ username | default: "user" }}')
print(template.render())

Output

Traceback (most recent call last):
  File "/Work/test_liquid.py", line 54, in <module>
    print(template.render())
  File "/Work/env/lib/python3.9/site-packages/liquid/template.py", line 100, in render
    self.render_with_context(context, buf)
  File "/Work/env/lib/python3.9/site-packages/liquid/template.py", line 155, in render_with_context
    self.env.error(err, linenum=node.token().linenum)
  File "/Work/env/lib/python3.9/site-packages/liquid/environment.py", line 416, in error
    raise exc
  File "/Work/env/lib/python3.9/site-packages/liquid/template.py", line 138, in render_with_context
    node.render(context, buffer)
  File "/Work/env/lib/python3.9/site-packages/liquid/ast.py", line 53, in render
    return self.render_to_output(context, buffer)
  File "/Work/env/lib/python3.9/site-packages/liquid/builtin/statement.py", line 75, in render_to_output
    val = self.expression.evaluate(context)
  File "/Work/env/lib/python3.9/site-packages/liquid/expression.py", line 578, in evaluate
    result = func(result, *_filter.evaluate_args(context))
  File "/Work/env/lib/python3.9/site-packages/liquid/filter.py", line 110, in wrapper
    return _filter(val, *args, **kwargs)
  File "/Work/test_liquid.py", line 21, in default_undefined
    if hasattr(obj, "__liquid__"):
  File "/Work/test_liquid.py", line 45, in __getattribute__
    return super().__getattribute__(name)
  File "/Work/env/lib/python3.9/site-packages/liquid/context.py", line 306, in __getattribute__
    raise UndefinedError(self.msg)
liquid.exceptions.UndefinedError: 'username' is undefined, on line 1

After changing this code to the following seems to fix the issue. Though I have no idea if it's a right place to add these lines.

    def __getattribute__(self, name: str) -> Any:
        if name in (
            "__repr__",
            "__liquid__",
            "__class__",
            "name",
            "hint",
            "obj",
            "hint",
            "msg",
        ):
            return super().__getattribute__(name)
        raise UndefinedError(self.msg)
jg-rp added a commit that referenced this issue Jul 28, 2022
@jg-rp
Copy link
Owner

jg-rp commented Jul 28, 2022

Hi hardiksondagar,

Sorry about that. For now, please try this definition of StrictDefaultUndefined.

class StrictDefaultUndefined(StrictUndefined):
    def __getattribute__(self, name: str) -> object:
        if name in (
            "__repr__",
            "__liquid__",
            "__class__",
            "name",
            "hint",
            "obj",
            "msg",
        ):
            return object.__getattribute__(self, name)
        raise UndefinedError(object.__getattribute__(self, "msg"))

StrictDefaultUndefined will be built-in in the next release, and the standard default filter will work without modification. So, in the future, you'll be able to do this.

from liquid import Environment
from liquid import StrictDefaultUndefined

env = Environment(undefined=StrictDefaultUndefined, tolerance=Mode.STRICT)

template = env.from_string('Hello {{ username | default: "user" }}')
print(template.render())

output

Hello user

@jg-rp
Copy link
Owner

jg-rp commented Aug 6, 2022

Python Liquid version 1.4.0 has been release. It includes StrictDefaultUndefined. Docs have been updated here.

More generally, StrictUndefined has been fixed to improve subclassing, by using object.__getattribute__() to avoid infinite recursion rather than super().__getattribute__().

@jg-rp jg-rp closed this as completed Aug 6, 2022
@hardiksondagar
Copy link
Author

Thanks @jg-rp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants