[Tutor] assigning __doc__ strings (manually)
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Sep 2 07:34:12 CEST 2004
> Since the main computation is done in real_f(), I thought I'd create a
> doc-string in real_f() that explains the computation being implemented
> etc (as done above).
[text cut]
Hi Hans,
Kent's solution, to manually assign to the function's __doc__ attribute,
after the function is defined, should do the trick.
The reason that:
> def f(x):
> real_f.__doc__
> return real_f(x)[0]
didn't work is because Python looks for the first line in a function for a
real string literal, and not just any expression that could be evaluated
as a string.
This is consistant with the way that Python doesn't do any evaluation of
functions unless they're explicitely called. For example:
###
>>> def testEvaluation():
... print x
...
###
would be invalid if 'x' weren't defined. But since Python doesn't
evaluate function bodies on definition time, we're still fine until we
actually start trying to use it:
###
>>> testEvaluation()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in testEvaluation
NameError: global name 'x' is not defined
###
As soon as we define an 'x', we're ok:
###
>>> x = "hello sailor"
>>> testEvaluation()
hello sailor
###
Anyway, I'd better try to tie this back to the original question. *grin*
When we look at:
> def f(x):
> real_f.__doc__
> return real_f(x)[0]
we now know that Python's not allowed to actually try evaluating
expressions like 'real_f.__doc__'. At most, Python can do a quick scan
for string literals, like:
###
def f(x):
"this is some docstring."
return real_f(x)[0]
###
For this reason, Python's automatic detection of documentation strings is
limited to paying attention to literal strings, since finding those is
technically trivial. It's easy to do, and doesn't really violate the
"don't try to evaluate the function body until we're called" rule that
functions follow.
Hope that made some sense. *grin* Good luck!
More information about the Tutor
mailing list