1

Given the python code:

import sys
import os 

def MyPythonMethod(value1, value2):
    # defining some variables 
    a = 4
    myValue = 15.65
    listValues = [4, 67, 83, -23]

    # check if a file exists
    if ( os.path.exists('/home/hello/myfile.txt') ):
        pass

    # doing some operation on the list
    listValues[0] = listValues[1]       

    # check if a file exists
    print sys.path

    # looping through the values
    for i in listValues:
        print i 

How can I extract the names of all external methods in function MyPythonMethod?

Ideally, I'd like to get a list of all external methods/members that are being invoked.

For MyPythonMethod, this will return:

moduleNames = ["os", "sys"]

methodsInvoked = ["os.path.exists", "sys.path"]

(yes, I know that 'path' is a member of sys, not a method; but I think you get the idea).

Any ideas?

2
  • I'd like to find things like ["os.path.exists", "sys.path"]. How will you solution help in doing so? Commented May 13, 2011 at 11:52
  • @user540009: Are you saying the phrase "all external methods" really means "functions defined outside my code"? Is that what you're searching for? Commented May 13, 2011 at 12:32

1 Answer 1

1

You can't ever fully know what functions (and in your case we're talking about plain functions, not methods, since methods are member functions of a class), a function will call without parsing it, because it might do so dynamically and their names may depend on what is imported into the global namespace when the function gets called.

But you can see the module and function names that are referenced by a function by inspecting MyPythonMethod.func_code.co_names. In your case, this attribute would return the tuple ('os', 'path', 'exists', 'sys').

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Boaz. Can you tell me what else can be retrieved using func_code? what other info can it give on the function?
You can try dir(MyPythonMethod.func_code) and see for yourself. You can get the name of the variables in the function, the consts (literals) defined in there and so on.
Great Boaz. Thanks & Shabbat Shalom!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.