[Tutor] how to reference a function itself when accessing its private functions?
spir
denis.spir at free.fr
Tue May 5 11:27:28 CEST 2009
Le Mon, 04 May 2009 16:08:38 -0700,
Emile van Sebille <emile at fenx.com> s'exprima ainsi:
> On 5/4/2009 3:37 PM Tim Michelsen said...
> > Dear Tutors and fellow pythonistas,
> > I would like to get access to the private methods of my function.
> >
> > For instance:
> > Who can I reference the docstring of a function within the function
> > itself?
> <snip>
> >
> > def show2(str):
> > """prints str"""
> > print str
> > d = self.__doc__
> > print d
>
> >>> def show2(str):
> ... """prints str"""
> ... print str
> ... print globals()['show2'].__doc__
> ...
> >>> show2('hello')
> hello
> prints str
> >>>
Hello Emile,
Why don't you use the func name directly?
print show2.__doc__
I mean it's a constant in the sense that it is know at design time, right? And you need it anyway, as shown by the fact that it becomes a string literal in the your version.
It's not like if you would _not_ know it ;-) Fortunately, funcs (and methods and classes and modules -- but not other object AFAIK) know their own (birth)name:
def docString(obj):
name = obj.__name__
return globals()[name].__doc__
Should work for the above listed object types. Anyway, other types have no docstring...
> This is the easy way -- ie, you know where to look and what name to use.
> You can discover the name using the inspect module, but it can get
> ugly. If you're interested start with...
>
> from inspect import getframeinfo, currentframe
------
la vita e estrany
More information about the Tutor
mailing list