kkawabat
kkawabat

Reputation: 1677

How to get file where function is defined if you only have a class that the function is bounded to?

I have a function (foo) and a class (Bar) that takes in a function as an attribute func.

if I pass in foo to an instance of Bar it's able to determine that func is a foo i.e.

def foo():
     pass

class Bar:
    def __init__(self, func):
         self.func = func

c = Bar(foo)

print(c.func.__name__)
>> foo

print(c.func)
>> <function foo at 0x7ffa86063290>

If foo is defined in a separate file than Bar is it possible to extract the __file__ of where foo is defined?

I tried:

print(c.func.__file__)

but got:

`AttributeError: 'function' object has no attribute '__file__'`

Upvotes: 0

Views: 31

Answers (1)

kkawabat
kkawabat

Reputation: 1677

found what I needed in the inspect module:

print(inspect.getfile(c.func))

Upvotes: 1

Related Questions