16

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

for ifunc,func in enumerate(list_of_functions):
    print(str(ifunc)+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

00__00__00
  • 4,834
  • 9
  • 41
  • 89

5 Answers5

23
func.__module__

Will return the module in witch it is defined

func.__globals__['__file__']

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

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
7

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

JobJob
  • 3,822
  • 3
  • 33
  • 34
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__
Ran Sasportas
  • 2,256
  • 1
  • 14
  • 21
1

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

Moberg
  • 5,253
  • 4
  • 38
  • 54
0

You can use __file__ variable.

print(__file__)

AlexShein
  • 166
  • 1
  • 13