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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With