[Tutor] How to have the name of a function inside the code of this function?

Karim kliateni at gmail.com
Fri Apr 6 21:19:07 CEST 2012


Le 06/04/2012 19:31, Alan Gauld a écrit :
> On 06/04/12 09:47, Karim wrote:
>
>> If you have any idea to get the caller name inside the caller.
>
>
> Its not normally very helpful since in Python the same function can 
> have many names:
>
> def F(x):
>    return x*x
>
> a = F
> b = F
> c - lambda y: F(y)
>
> print F(1), a(2), b(3), c(4)
>
> Now, why would knowing whether the caller used F,a or b
> to call the same function object help? And what do you
> do in the case of c()? Do you return 'c' or 'F'?
>
> Maybe you could use it to tell you the context from
> which they were calling? But in that case there are
> usually better, more reliable, techniques
>  - like examining the stackframe.
>
> HTH,

Thanks Steven, Moduok and Steven for all your answers!

The reason is simple I wanted to optimize some code using pyuno for 
openoffice.org doc generation I have several methods to set
text with "Heading 1", ... "Heading <N>" title style:

def title(self, text='', style="Heading 1"):
      self._cursor_text.setPropertyValue('ParaStyleName', style)
      self.add_text(text)

def title1(self, text=''):
      self.title(text=text)

def title2(self, text=''):
      self.title(text='', style="Heading 2")

...

def title9(self, text=''):
      self.title(text='', style="Heading 9")

---------------------------------------------------------------------------------

I just wanted to improve a little by doing something like that (pseudo 
code):

def title9(self, text=''):
      self.title(text='', style="Heading " + <func_name>.split()[1])


In short the number in the funtion name is the number of the title depth 
in the document.
There is no big deal if Iit's not feasible;

Cheers
Karim










More information about the Tutor mailing list