On Fri, Aug 31, 2012 at 8:25 AM, lucas <sjluk...@gmail.com> wrote:
>> Far as I can see, you never actually called that function anywhere.
>> ChrisA
>
> doesn't the exec command call the function?

(Side point: You don't have to post to both comp.lang.python and
python-list - they mirror each other.)

What you executed included the 'def' statement. That's an executable
statement that creates a function object:

'lucas53': <function lucas53 at 0x214348c>

In Python, functions are objects just like dictionaries, strings, and
integers; you can construct them (usually with 'def' or 'lambda'),
pass them around, tinker with their attribututes, and ultimately, call
them.

But unless you do actually call that function, none of its code will
be executed. You can test this by putting a 'print' inside the
function; you'll see screen output when the function's called, and
your code above won't show that.

To access the local variables/names from the function itself, you'll
need to put a call to locals() inside that function, because as soon
as it finishes, those locals disappear. Try this:

>>> xx2 = """
def lucas53():
        harry = (4+16) / 2
        rtn = dict(harry=harry)
        return rtn

foo = lucas53()
"""
>>> env = {}
>>> exec(xx2,env)

(This is Python 3 syntax, exec is now a function - otherwise
equivalent to what you did.)

You'll now see a name 'foo' in env, with the mapping returned from
your function. There's no peeking into locals here, just a straight
function return value.

Is this what you were looking for?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to