473,395 Members | 1,526 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

access __doc__ from within function without reference to function name

The subject of this message might be a little cryptic, so here's an
example of what I mean:

def foo():
"""doc string of foo"""
print foo.__doc__
>>foo()
doc string of foo

What I want to know is whether it is possible to call __doc__ against
some builtin method, like __func__ or something like that. So calling
__doc__ without the functions name, something like this:

def foo():
"""doc string of foo"""
print __func__.__doc__ # pseudo code

So basically, my question is: is there a way to access a function from
within itself without using its name?

Regards, Sander.

Oct 2 '07 #1
6 2035
SanPy <jh******@gmail.comwrote:
So basically, my question is: is there a way to access a function from
within itself without using its name?
Not really, no. Python is executing a code block, it has no idea which
function referenced that code block.

You can get the current code object quite easily (inspect.currentframe
().f_code), but the reference from function to code is one way: a single
code object could be used by multiple functions.

You can get the source code though, so if you are desperate enough you
could try parsing the source code to extract the docstring:

print inspect.getsource(inspect.currentframe())

Use the name of the function, that's the best way.
Oct 2 '07 #2
The subject of this message might be a little cryptic, so here's an
example of what I mean:

def foo():
"""doc string of foo"""
print foo.__doc__
>>>foo()
doc string of foo

What I want to know is whether it is possible to call __doc__ against
some builtin method, like __func__ or something like that. So calling
__doc__ without the functions name, something like this:

def foo():
"""doc string of foo"""
print __func__.__doc__ # pseudo code

So basically, my question is: is there a way to access a function from
within itself without using its name?

Well, I don't know if it's the best way to do it, but the
following code I just threw together does the trick for me:

################################################## #########
"A module docstring"
import inspect
def get_doc_string():
frame = inspect.stack()[1]
funcname = frame[3]
try: # for straight functions
return eval(funcname).__doc__
except:
locals = frame[0].f_locals
try: # for object methods
return getattr(locals["self"], funcname).__doc__
except:
try: # for class and module docstrings
return locals["__doc__"]
except:
print "If you got here, there's something I missed"
import pdb; pdb.set_trace()
return funcname

if __name__ == "__main__":

def outer_function():
"A function docstring"
s = get_doc_string()
print s
return s

class Foo(object):
"A class docstring"
zip = get_doc_string()
def bar(self):
"A method's docstring"
s = get_doc_string()
print s
return s

def f1(func):
"this is f1"
s = func()
print s
return s

test = outer_function()
assert test == "A function docstring"
foo = Foo()
assert foo.bar() == "A method's docstring"
print Foo.zip
assert Foo.zip == "A class docstring"
module_docstring = get_doc_string()
print module_docstring
assert module_docstring == "A module docstring"
assert f1(get_doc_string) == "this is f1"

################################################## #########

I couldn't find a handy way to get the actual
function-object/class-object/module/method object for the given
context without the convoluted try/except block. Perhaps someone
with more knowledge of the inspect module could reudce that do
something far more simple. There may also be problems if this is
imported across modules. But this might help point you in the
right direction.

-tkc


Oct 2 '07 #3
Tim Chase <py*********@tim.thechases.comwrote:
>So basically, my question is: is there a way to access a function from
within itself without using its name?


Well, I don't know if it's the best way to do it, but the
following code I just threw together does the trick for me:
The original request was to do it without using the function's name, but
you are depending on that name so your code is easy enough to break. e.g.
change the definition of f1 to:

def f2(func):
"this is f1"
s = func()
print s
return s
f1 = f2
del f2

and the output is:

A function docstring
A method's docstring
A class docstring
A module docstring
If you got here, there's something I missed
c:\temp\docstring.py(18)get_doc_string()
-return funcname
(Pdb)
Oct 2 '07 #4
The original request was to do it without using the function's
name, but you are depending on that name so your code is easy
enough to break. e.g. change the definition of f1 to:

def f2(func):
"this is f1"
s = func()
print s
return s
f1 = f2
del f2
Even Python-proper seems to get "confused" by this (though I
would contend it's correct behavior):
===================================
def f1():
raise Exception
f2 = f1
del(f1)
f2()
===================================
The traceback references f1() instead of f2. (other printing than
the calling line of code from the python file itself)
===================================
Traceback (most recent call last):
File "x.py", line 5, in ?
f2()
File "x.py", line 2, in f1
raise Exception
Exception
===================================

pdb suffers the same problem:

===================================
def f1():
import pdb; pdb.set_trace()
print 'hello'
f2 = f1
del(f1)
f2()
===================================
then, when run, use "where" to ask where Python thinks you are:
===================================
c:\temp\z.py(3)f1()
-print 'hello'
(Pdb) where
c:\temp\z.py(7)?()
-f2()
c:\temp\z.py(3)f1()
-print 'hello'
===================================

It thinks we're in f1 as well even though f1 no longer exists.
My understanding was that the OP wanted a way to refrain from
hard-coding the function-name into the body of the function,
rather than to completely avoid the name of the function ever
being used anywhere.

Unless there's a mapping that I couldn't find (that would take
the current frame and map it to the calling
function/method/module object) the only way to completely avoid
this (AFAICT) would be to take the location information returned
by the stack frame, parse the file, and extract the doc-string
from the resulting line(s).

It gets hairier when the python is poorly written as one could
have pessimal cases of "valid" python docstrings that look like

def f(x): "docstring"; return x*2

or

def f(x):
"docstring"; return x*2

or common multiline items like

def f(x):
"""docstring1
docstring2"""
pass

or even worse,

def f(x):
"""this is a \"""docstring\"""
with \\\"""and\""" mutliple lines"""
pass

def f(x):
"this is\
a docstring"
pass

The parser also has to accomodate "raw" and "unicode" string
prefixes, as they're valid too:

def f(x):
r"raw!"
pass

def f(x):
u"Unicode"
pass
in addition. Okay...in most of these cases, the pathological
coder should be taken out back and beaten, but it's a non-trivial
problem :)

-tkc


Oct 2 '07 #5
Tim Chase <py*********@tim.thechases.comwrote:
The parser also has to accomodate "raw" and "unicode" string
prefixes, as they're valid too:

def f(x):
r"raw!"
pass

def f(x):
u"Unicode"
pass
in addition. Okay...in most of these cases, the pathological
coder should be taken out back and beaten, but it's a non-trivial
problem :)
Fortunately someone already wrote a parser for Python code, so it is pretty
trivial:
>>import compiler
class Visitor(compiler.visitor.ASTVisitor):
def visitFunction(self, node):
print node.doc
>>def showdoc(source):
compiler.walk(compiler.parse(source), Visitor())

>>showdoc(r'''def f(x):
"""this is a \"""docstring\"""
with \\\"""and\""" mutliple lines"""
pass
''')
this is a """docstring"""
with \"""and""" mutliple lines
>>showdoc(r'''def f(x):
u"Unicode" " with concatenation"
pass
''')
Unicode with concatenation
>>>
Oct 2 '07 #6
En Tue, 02 Oct 2007 19:01:27 -0300, wang frank <fw*@hotmail.co.jp>
escribi�:
I am writing Python script now. The project will grow bigger in future.
I need to import some packages for several functions, such as numpy.
Where is the best plalce to put the import numpy command? Is it fine to
put on the first line in the file?
Yes, this is the usual way.
Is it better to put it into each function after the def functionname? or
they are the same.
I only place an import inside a function when it's expensive (e.g. loads a
lot of things) and not always required, or when it's irrelevant to the
main purpose of the module (e.g. "import traceback" when it's used just to
handle some special exceptions).
Since numpy function will be used in all files, so I have to import it
in each files. Does this will increase the memory usuage or there are
better way to do it.
No. Only the first import actually has to load the module; later imports
quickly return a reference to the already loaded module.

--
Gabriel Genellina

Oct 3 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Steven | last post by:
I'm writing a Python script which can be called from the command-line, and I want to use my module doc string as the CL help text, but I don't know how to access my module object from inside the...
2
by: Reid Priedhorsky | last post by:
Dear group, I'd have a class defined in one module, which descends from another class defined in a different module. I'd like the superclass to be able to access objects defined in the first...
6
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object...
3
by: Random Person | last post by:
Does anyone know how to use VBA to relink tables between two MS Access databases? We have two databases, one with VBA code and the other with data tables. The tables are referenced by linked...
23
by: JustMe | last post by:
I don't know if this has anything to do with AccessXP running on Terminal Services with Access97/2000 also installed, but here is one example of a query that does not work any longer: SELECT...
16
by: bobueland | last post by:
Look at the code below: # mystringfunctions.py def cap(s): print s print "the name of this function is " + "???" cap ("hello")
5
by: Lyle Fairfield | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/callnetfrcom.asp The Joy of Interoperability Sometimes a revolution in programming forces you to abandon all...
7
by: gtb | last post by:
Greetings, Don't know the daily limit for dumb questions so I will ask one or more. In a function I can use the statement n = sys._getframe().f_code.co_name to get the name of the current...
7
by: thebarefootnation | last post by:
Hi, I have created an access db that I would like to secure. The database will exist on a shared drive and be used at a number of different locations hence the reason to secure the database. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.