2

Given the python function:

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

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

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

How can I extract the names and types of all the variables in method MyPythonMethod?

Ideally, I'd like to get all variable names and their types given a method name. for example, the output for method MyPythonMethod will look like this:

varNames = ["a", "myValue", "listValues", "i"]

varTypes = ["int", "float", "list", "float"]

Any ideas?

8
  • 2
    Why would you want that? Commented May 12, 2011 at 18:16
  • 1
    Start digging. docs.python.org/library/language.html Commented May 12, 2011 at 18:16
  • My sense is that although this might not be impossible, it is almost certainly unnecessary unless your goal is to create a comically obfuscated rube-goldbergesque contraption. Say more about why you want this and we can probably tell you a better way to do what you want. Commented May 12, 2011 at 18:23
  • 1
    >>> MyPythonMethod.func_code.co_varnames ('value1', 'value2', 'a', 'myValue', 'listValues') Commented May 12, 2011 at 18:42
  • 1
    Why do you care what variable names they use so long as the function/method produces the desired behavior? Commented May 12, 2011 at 18:44

3 Answers 3

7

1 Variables don't have a type in python. Objects have a type, and variables point to objects.

[2] you can use the inspect module to get info about the internals of your function. Read the docs -- they will tell you what is available for inspection. MyPythonMethod.func_code.co_varnames will give you the local variable names, for example. ( And note that MyPythonMethod, as defined, is actually a function, not a method. )

[3] But even when you get the names of the local variables, the aren't bound to any objects except while the function is executing. The value 4 is bound to local var 'a' in the function -- before and after the function is called, there is no 'a' and it's not bound to anything.

[4] If you run the function in the debugger, you can halt the execution at any point and inspect the variables and objects created in the function.

[5] If the function raises an exception, you can catch the exception and get access to some of the state of the function at the time of the exception.

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

3 Comments

thank you. it looks like MyPythonMethod.func_code.co_varnames returns also the function arguments as part of the list. is there a way to get just the local variables of the method?
m.func_code.co_varnames[m.func_code.co_argcount:] may work, but it the count doesn't account for an optional "rest" arg. I don't know if there are any other cases where argcount wouldn't work. And relying on the arg order may be implementation specific and may not be guaranteed to work in the future.
Thanks again. Suppose now that the method above also invokes calls to methods of other modules. for example, os.path.exists(...), sys.exit() etc. Is it possible to get a list of these methods as well?
4

You can't do this "from the outside".

  • Local variables don't exist until the method runs. Although the scope of all variables is known statically, i.e. at compiletime, I don't think you can get this information easily without crawling through the AST or bytecode yourself. (Edit: Steven proved me wrong about this one... code objects have a tuple containing all local variable names)
  • A given chunk of code doesn't have access to any scopes but its own and the sourrounding "lexical" scopes (builtins, module-level globals, local scopes of enclosing functions).
  • There is no such thing as the type of a variable (in Python) - any variable can refer to any number of objects of completely different types during its lifetime. What should the output be if you add a = "foo"? And if you then add a = SomeClass()?

Inside the method itself, you could use locals() to get a dictionary of local variables and the objects they currently refer to, and you could proceed to call type on the values (the objects). Of course this only gets you the type of the object currently referred to. As hinted in the comment, I doubt that this is useful. What do you really want to do, i.e. what problem are you trying to solve?

Comments

0

If you use pdb can't you set the last line as a breakpoint and then ask the debugger to look at the top stack frame and list the variables for you? Or you could look at the pdb code and copy its tricks for how to introduce the breakpoint and then inspect the stack frame beneath the breakpoint function that you register.

Comments

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.