Karthikeyan Singaravelan <tir.kar...@gmail.com> added the comment:
Thanks Serhiy, object.__qualname__ can be used to get qualified name of the object but ast nodes don't have qualified name for the node where I can match against it. node.name returns unqualified name and hence using ast module I can't differentiate between Spam and NestedA.Spam since both return 'Spam' for node.name . I am also using a recursive decorator found at https://stackoverflow.com/a/14661325/2610955 which solves problem iterating through nested classes. But for matching module level class object and nested class level object when I parse a syntax tree for Spam and NestedA.Spam both nodes for class definition return 'Spam'. Is there a way to get qualified names in ast module or do I need to store it somewhere? My current approach for inspect.findsource is as below : class ClassVisitor(ast.NodeVisitor): def recursive(func): """ decorator to make visitor work recursive """ def wrapper(self, node): func(self, node) for child in ast.iter_child_nodes(node): self.visit(child) return wrapper def __init__(self, source, name, *args, **kwargs): self.source = source self.line_number = None self.name = name super().__init__(*args, **kwargs) @recursive def visit_ClassDef(self, node): # Need to match qualified name to differentiate between Spam and NestedA.Spam if node.name == self.name: # decrement by one since lines list starts with indexing by zero self.line_number = node.lineno - 1 name = object.__name__ # can use object.__qualname__ but node.name is not qualified source = ''.join(lines) tree = ast.parse(source) class_visitor = ClassVisitor(source, name) class_visitor.visit(tree) if class_visitor.line_number is not None: return lines, class_visitor.line_number else: raise OSError('could not find class definition') ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue35113> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com