Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python inspect.getsource gets the wrong source

Running this file foo.py

import inspect

class Parent(object):
    def source1(self):
        class A(object):
            def foo(self):
                pass
        print inspect.getsource(A)
    def source2(self):
        class A(object):
            def bar(self, a, b, c):
                pass
        print inspect.getsource(A)


parent = Parent()
parent.source1()
parent.source2()

produces this output:

    class A(object):
        def foo(self):
            pass

    class A(object):
        def foo(self):
            pass

when I expect it to produce this output:

    class A(object):
        def foo(self):
            pass

    class A(object):
        def bar(self, a, b, c):
            pass

I am encountering this problem in my tests. I reuse the names A and B for class names within the body of the test method. I'm testing a function that relies on inspect.getsource and, well... it doesn't work because later tests are given the source from earlier-named A and B classes.

like image 455
iffy Avatar asked Dec 20 '25 12:12

iffy


1 Answers

The inspect.getsource call actually parses the source file, looking for the class definition, and returns the first one it finds at the lowest level of indentation with the name it's looking for. In other words, it won't do what you're asking it to do.

Here's a slightly different approach that results in the output you're looking for, and perhaps will do what you need:

import inspect

class Parent(object):
    def source1(self):
        class A1(object):
            def foo(self):
                pass
        A = A1
        print inspect.getsource(A)
    def source2(self):
        class A2(object):
            def bar(self, a, b, c):
                pass
        A = A2
        print inspect.getsource(A)


parent = Parent()
parent.source1()
parent.source2()

The class definitions can still be referenced by the names you want (e.g. "A"), but the actual definition in the source code uses a different name, so getsource can find it.

like image 132
Francis Potter Avatar answered Dec 23 '25 00:12

Francis Potter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!