[Answered ]-Evaluate variable in context

1👍

Would this work:

>>> C = Context({"person": p})
>>> C.get("person")
<class '__main__.PersonClass'>
>>> C.get("person").name
'Test'

EDIT: A more generic version:

def get_attr_from_context(ctx, attr_str):
    attrs = iter(attr_str.split('.'))
    ans = ctx.get(next(attrs))
    for attr in attrs:
        ans = getattr(ans, attr)
    return ans

# Prints 'Test'
print(get_attr_from_context(C, 'person.name'))

1👍

The best way to do this is to use the Django template language to resolve the variables.

Otherwise, you will have to recreate all of the functionality that Django provides (dictionary lookup, attribute lookup …) which would be complicated and error prone.

from django.template.base import Variable, Context

def resolve_variable(variable, context_dict):
    """
    Resolve variable using the given dictionary context_dict 
    """
    return Variable(variable).resolve(Context(context_dict))

>>> resolve_variable('person.name', {'person': {'name': 'Ninja420'}})
'Ninja420'

Note, I believe Variable is a private API, so it’s possible (but not likely) that this could break in a future version of Django.

Leave a comment