Self-identifying functions and macro-ish behavior
Iain King
iainking at gmail.com
Wed Feb 15 04:15:59 EST 2006
63q2o4i02 at sneakemail.com wrote:
> Hi, I was wondering how I may get a python function to know what its
> name is without me having to write it manually? For example:
>
> def func1():
> <do some stuff1>
> print 'func1'
> return True
>
> def func2():
> <do some stuff2>
> print 'func2'
> return True
>
> should be more like
> def func1():
> <do some stuff 1>
> print <self-name>
> return True
>
> def func2():
> <do some stuff 2>
> print <self-name>
> return True
>
> I imagine this means things like closures which I'm not familiar with
> (I'm not a CS person). In this case, each function is part of a class,
> so I imagine I can take a dir() of the class if necessary.
Yeah, I think these are closures (though when I learnt CS we didn't get
taught them). Try this:
def makeFunction(name):
def func():
<do stuff>
print name
return True
return func
func1 = makeFunction('func1')
func2 = makeFunction('func2')
>
> This leads into my next related question, which is How do I get some
> sort of macro behavior so I don't have to write the same thing over and
> over again, but which is also not neatly rolled up into a function,
> such as combining the return statements with a printing of <self-name>?
I think I've answered this too?
Iain
More information about the Python-list
mailing list