ptvs

How to determine when function overrides another in the chain of inheritance?


I am using PTVS assemblies to generate strongly typed bindings for a Python library. I've got an instance of ModuleAnalysis, which I use to perform various queries about guessed types in Python code.

At this moment I stumbled upon a need in my C# output to explicitly mark all overriden methods with override keyword. However, I can't seem to figure how to determine if the one of the parent classes already has a member with a same name, that is being overriden.

Here is a sample of what I am trying to convert:

class Base:
    def virt(self):
        print("Base.virt")

class A(Base):   
    def virt(self):
        super().virt()

    def non_virt(self):
        pass

When processing A's virt, I tried to do this:

analysis.GetValuesByIndex("super()." + node.Name, node.Body.EndIndex)

Here, ModuleAnalysis analysis and FunctionDefinition node. I also tried Body.StartIndex and "super(A, self)." + node.Name.

Unexpectedly, this gives no results.


Solution

  • The best way to achieve this is going to be to look at the MRO of the class and inspect each base class definition.

    This sequence of steps should work most of the time - PTVS doesn't pretend to do static analysis quality type inferencing, so there are many situations where it "gives up" (particularly when cross-module imports start getting complicated):

    1. Find the type of self within the function (make sure the location is within the function scope)
    2. Find ClassInfo.Mro
    3. Find self in the MRO (should be first), and then after that check each ClassInfo.ClassDefinition node to see if it contains the function, or BuiltinClassInfo.PythonType.GetMember() for an imported definition