Michael Michael - 1 year ago 109
Python Question

Exec and variable scope

Python 3.5.1

Could you have a look at the code and the picture.

This is some Django code, but the question relates to Python.

Well, I get the error:

Exception Value:
name 'objects' is not defined
Exception Location:
/home/michael/workspace/pharchive/pharchive/general/templatetags/md_aux.py in get_aux_info, line 17

Line 17 is context = Context({"objects": objects}). In the picture it is visible.

I tried to add objects=[] a little above. But that didn't help. In this case objects was really empty. So, I commented it out.

Well, in the screenshot we can what we get if we stop at the breakpoint. We can see that objects var is really accessible in the context. And it contains something.

Anyway, I got stuck with variable scope.

I don't understand:
1. Why objects=[] didn't help me.
2. Why I get this error whereas objects is accessible.

Could you give me a kick here?

def get_aux_info(master_document, aux_type):
md = MasterDocument.objects.get(pk=master_document)
template = get_template("general/md_tags.html")

#objects = []
code = "objects = md." + aux_type +"s.all()"
context = Context({"objects": objects})
return template.render(context)

Answer Source

A much easier approach than building and executing the code as a string would be to access the attribute using the built-in getattr function. This makes it clearer what's going on and side-steps your current scope issues entirely:

objects = getattr(md, aux_type + 's').all()

Python has extensive support for this kind of introspection; using exec (and eval) is usually a warning that you're approaching something in the wrong way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download