Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get names of all the variables defined in methods of a class

I have the following class:

class Foo(object):
    def setUp(self):
        self.var1 = "some value"
        self.var2 = something
    def bar(self):
        var3 = some value
    def baz(self, var):
        var4 = some value

I want to print the names of all variables defined inside the methods, like:

setUp, bar, baz, var1, var2, var3, var4

I have tried using locals(), vars(), globals() but I am getting only the names of method and not variable names.

I also tried using ast module, but no success.

like image 752
atg Avatar asked Dec 13 '16 06:12

atg


People also ask

How to display all available methods in Python?

To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.

What is a class variable Java?

Class variables − Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.


1 Answers

You can use ast.parse to generate AST node. Then ast.walk can be used to recursively iterate over the node and its` descendants. For each node you can check the type and then extract the correct attribute.

Below is an example that is working with your code but don't expect it to work as such with more complex files:

source = '''
class Foo(object):
    def setUp(self):
        self.var1 = "some value"
        self.var2 = 1
    def bar(self):
        var3 = 2
    def baz(self, var):
        var4 = var
'''

import ast

def hack(source):
    root = ast.parse(source)

    for node in ast.walk(root):
        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
            yield node.id
        elif isinstance(node, ast.Attribute):
            yield node.attr
        elif isinstance(node, ast.FunctionDef):
            yield node.name

print(list(hack(source)))

Output:

['setUp', 'bar', 'baz', 'var1', 'var2', 'var3', 'var4']
like image 53
niemmi Avatar answered Oct 28 '22 14:10

niemmi