Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot resolve callable context variable

please take a look at the code below. I am trying to store a lambda expression in a context variable and retrieve it in my custom template tag. but the variable lookup returns an empty string instead of the lambda that I expected. why? any idea?

thanks

konstantin

>>> c = dict(f = lambda x : 'x=%s' % x)
>>> c['f']
<function <lambda> at 0x02D7FFB0>
>>> template.Variable('f').resolve(c)
''
>>>
like image 329
akonsu Avatar asked Jun 25 '26 03:06

akonsu


2 Answers

Passing lambdas to the template in Django 1.2.4 worked fine, after upgrading my code to Django 1.3, I was bit by the same issue too. I gave up on trying to set alters_data flag and trying to apply the patch in ticket 15791 that adds a do_not_call_in_templates flag too (apparently merged in the dev version). The way I sidestepped the problem until a proper solution is in place was to use a factory function without arguments that returned the lambda instead of passing the lambda to the template.

def return_a_lambda():
    return lambda x : 'x=%s' % x

c = dict(f=return_a_lambda)
>>> c['f']
<function return_l at 0x33bc668>
template.Variable('f').resolve(c)
<function <lambda> at 0x33ccaa0>

Django's template calls all context variables as long as they don't need an argument, hence return_a_lambda is executed and the template gets the lambda in return.

https://docs.djangoproject.com/en/dev/ref/templates/api/ under "Rendering a context"

Update: A reusable hack would be a factory function that returns a factory function:

def encapsulate(func):
    def wrapper():
        return func
    return wrapper

or a shorter version:

def encapsulate(func):
    return lambda: func

with the final code looking like this:

c = dict(f=encapsulate(lambda x : 'x=%s' % x))

which is easier to interpret. In my case (https://github.com/rosarior/mayan) I now have to do this some 30 times aprox to get the code running in Django 1.3 :'(

like image 69
Roberto Rosario Avatar answered Jun 27 '26 16:06

Roberto Rosario


here is a ticket that I found (that I have just reopened because I have found, I think, a "better" solution): https://code.djangoproject.com/ticket/15791

like image 28
akonsu Avatar answered Jun 27 '26 15:06

akonsu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!