20

I am programmatically printing out a list of function in python. I can get the name from __name__

for i, func in enumerate(list_of_functions): print(str(i) + func.__name__) 

How to get the source filename where the function is defined as well?

and in case the function it is attribute of a object, how to get the type of parent object?


portability python2/3 is a must

2
  • 1
    The title says "from which file a function is called", but you are actually asking in which file a function is defined, which is different... Commented May 31, 2018 at 10:31
  • will edit.you are right Commented May 31, 2018 at 11:21

5 Answers 5

27
func.__module__ 

Will return the module in which it is defined

func.__globals__['__file__'] 

will return the whole path of the file where it is defined. Only for user-defined functions

Sign up to request clarification or add additional context in comments.

Comments

11

How to get the source filename where the function is defined ... ?

import inspect inspect.getfile(func) 

and in case the function it is attribute of a object, how to get the type of parent object?

To get the class of a method (i.e. when the function is an attribute of a object):

if inspect.ismethod(func): the_class = func.__self__.__class__ 

ref: https://docs.python.org/3/library/inspect.html

Comments

2

As stated here https://docs.python.org/3/library/inspect.html func.__globals__ returns the global namespace where the function was defined.

Comments

1

For getting the filename just use -

print(os.path.basename(__file__)) 

if you want the full file path you can just use

print __file__ 

1 Comment

not quite. this will give me the filename of the current script. I am editing to clarify
0

You can use __file__ variable.

print(__file__)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.