[email protected] wrote:
>
>> Hello,
>> I am embedding python support in my C++ application and was looking at
>> adding "Intellisense" or "AutoComplete" support.
>>
>> I found a way to do it using the "dir" function, but this creates a
>> problem. Here's why. Let's say I have the following code in my editor:
>>
>> import sys
>> x = sys
>>
>>
>> Now, I would like to get all attributes of the object called 'x'. I
>> can "instrument" the code and add "print dir(x)" at the end,
>> temporarily redirect the python output to a string and execute the
>> code.
>>
>> But this is not safe: I do NOT want to execute the code while the user
>> is typing!
>>
>> Is there a way to "compile" the python code and get access to the
>> symbol table from that compiled block?
>>
>> Did anybody ever implement AutoComplete in a editor for Python?
>>
>> cheers.
>>
>
I implemented autocomplete in my application by using the exec() function to
load a namespace. To demonstrate, type the following into the interpreter:
txt = "x = 'hello'\nprint x"
exec(txt)
You will get "hello" to print out. Not good. How about this?
txt = "def say_hello():\n\tx = 'hello'\n\tprint x"
exec(txt)
Nothing happens. Because the print statement is inside the function
say_hello(), exec() just loads the function into the globals() namespace.
Now type:
say_hello()
"Hello" prints out. To answer your question, executing code is not
necessarily a bad thing. Calling exec() on our function just loaded it into
the globals namespace, where you can use introspection on the objects
contained therein. None of the statements in the function were executed.
My autocomplete system uses exec() on the user scripts to load a namespace.
But before that occurs, the system checks for top-level statements that
would execute.
Assignment statements are usually pretty safe: exec("x = 42") is a pretty
safe statement.
Top-level calls to functions are bad: exec('launch_missiles()') would in
fact launch the missiles. Remove any lines that have top-level function
calls.
Or you can create your own mini-parser, which I considered but thought it
would be too much work.
_______________________________________________
Pythonmac-SIG maillist - [email protected]
http://mail.python.org/mailman/listinfo/pythonmac-sig