__doc__ of current function?

T

Trevor Taylor

Hi,

I thought it would be simple but couldn't figure it out, nor find it
addressed already:

I can do:

def validatePassword(p):
'do something'
print validatePassword.__doc__

.... can I write a general docOfCurrentFunction() function so that I
can rewrite it:

def validatePassword(p):
'do something'
print docOfCurrentFunction()

Thanks,

Trevor
 
K

Ksenia Marasanova

... can I write a general docOfCurrentFunction() function so that I
can rewrite it:

def validatePassword(p):
'do something'
print docOfCurrentFunction()

def docOfCurrentFunction():
import sys
func_name = sys._getframe(1).f_code.co_name
return eval(func_name + '.__doc__')

But I hope that a more intelligent way exists than using 'eval' :)


Ksenia.
 
P

Peter Otten

Ksenia said:
def docOfCurrentFunction():
import sys
func_name = sys._getframe(1).f_code.co_name
return eval(func_name + '.__doc__')

But I hope that a more intelligent way exists than using 'eval' :)
Maybe
.... f = sys._getframe(1)
.... return f.f_globals[f.f_code.co_name]
........ "Demo docstring"
.... print caller().__doc__
....
Or can that fail in some cases?

Peter
 
S

Sean Ross

Peter Otten said:
Ksenia said:
def docOfCurrentFunction():
import sys
func_name = sys._getframe(1).f_code.co_name
return eval(func_name + '.__doc__')

But I hope that a more intelligent way exists than using 'eval' :)
Maybe
... f = sys._getframe(1)
... return f.f_globals[f.f_code.co_name]
...... "Demo docstring"
... print caller().__doc__
...
Or can that fail in some cases?

Peter


Hi.
Yes, it fails for methods:
.... f = sys._getframe(1)
.... return f.f_globals[f.f_code.co_name]
........ def m(self):
.... "mmmmmmmmmm"
.... print caller().__doc__
....Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 4, in m
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top