This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author xtreak
Recipients Windson Yang, pablogsal, serhiy.storchaka, xtreak, yselivanov
Date 2018-11-03.06:25:03
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1541226303.71.0.788709270274.issue35113@psf.upfronthosting.co.za>
In-reply-to
Content
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')
History
Date User Action Args
2018-11-03 06:25:03xtreaksetrecipients: + xtreak, serhiy.storchaka, yselivanov, pablogsal, Windson Yang
2018-11-03 06:25:03xtreaksetmessageid: <1541226303.71.0.788709270274.issue35113@psf.upfronthosting.co.za>
2018-11-03 06:25:03xtreaklinkissue35113 messages
2018-11-03 06:25:03xtreakcreate