Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #35505 > unrolled thread

Finding the name of a function while defining it

Started byAbhas Bhattacharya <abhasbhattacharya2@gmail.com>
First post2012-12-25 18:00 -0800
Last post2012-12-27 17:25 -0800
Articles 12 on this page of 32 — 10 participants

Back to article view | Back to comp.lang.python


Contents

  Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-25 18:00 -0800
    Re: Finding the name of a function while defining it Roy Smith <roy@panix.com> - 2012-12-25 22:11 -0500
      Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:26 -0800
        Re: Finding the name of a function while defining it Chris Angelico <rosuav@gmail.com> - 2012-12-27 18:48 +1100
          Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:52 -0800
          Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:52 -0800
      Re: Finding the name of a function while defining it Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-12-27 12:59 +0000
    Re: Finding the name of a function while defining it Tim Roberts <timr@probo.com> - 2012-12-26 20:52 -0800
      Re: Finding the name of a function while defining it Chris Angelico <rosuav@gmail.com> - 2012-12-27 16:44 +1100
        Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:46 -0800
          Re: Finding the name of a function while defining it Chris Angelico <rosuav@gmail.com> - 2012-12-27 18:52 +1100
            Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:55 -0800
            Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:55 -0800
        Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:46 -0800
          Re: Finding the name of a function while defining it Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-12-27 10:58 +0000
            Re: Finding the name of a function while defining it Tim Chase <python.list@tim.thechases.com> - 2012-12-27 07:32 -0600
              Re: Finding the name of a function while defining it Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-12-27 13:34 +0000
            Re: Finding the name of a function while defining it Roy Smith <roy@panix.com> - 2012-12-27 10:09 -0500
              Re: Finding the name of a function while defining it Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-12-28 01:07 +0000
      Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-26 23:45 -0800
        Re: Finding the name of a function while defining it Mitya Sirenef <msirenef@lightbird.net> - 2012-12-27 03:03 -0500
          Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-27 00:26 -0800
            Re: Finding the name of a function while defining it Mitya Sirenef <msirenef@lightbird.net> - 2012-12-27 04:07 -0500
          Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-27 00:26 -0800
        Re: Finding the name of a function while defining it Chris Rebert <clp2@rebertia.com> - 2012-12-27 00:58 -0800
        Re: Finding the name of a function while defining it Tim Roberts <timr@probo.com> - 2012-12-28 21:01 -0800
        Re: Finding the name of a function while defining it Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2012-12-29 12:18 +0200
    Re: Finding the name of a function while defining it Chris Rebert <clp2@rebertia.com> - 2012-12-27 00:26 -0800
      Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-27 00:42 -0800
      Re: Finding the name of a function while defining it Abhas Bhattacharya <abhasbhattacharya2@gmail.com> - 2012-12-27 00:42 -0800
    Re: Finding the name of a function while defining it Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-12-27 13:31 +0000
      Re: Finding the name of a function while defining it alex23 <wuwei23@gmail.com> - 2012-12-27 17:25 -0800

Page 2 of 2 — ← Prev page 1 [2]


#35598

FromMitya Sirenef <msirenef@lightbird.net>
Date2012-12-27 03:03 -0500
Message-ID<mailman.1333.1356595418.29569.python-list@python.org>
In reply to#35588
On 12/27/2012 02:45 AM, Abhas Bhattacharya wrote:
> On Thursday, 27 December 2012 10:22:15 UTC+5:30, Tim Roberts  wrote:
>> Abhas Bhattacharya <abhasbhattacharya2@gmail.com> wrote:
>>
>>> While I am defining a function, how can I access the name (separately as
>>> string as well as object) of the function without explicitly naming
>>> it(hard-coding the name)?
>>> For eg. I am writing like:
>>> def abc():
>>>     #how do i access the function abc here without hard-coding the name?
>>
>>
>> Why?  Of what value would that be?
>>
>>
>>
>> Note that I'm not merely being obstructionist here.  What you're asking
>>
>> here is not something that a Python programmer would normally ask.  The
>>
>> compiled code in a function, for example, exists as an object without a
>>
>> name.  That unnamed object can be bound to one or more function names, but
>>
>> the code doesn't know that.  Example:
>>
>>
>>
>> def one():
>>
>>      print( "Here's one" )
>>
>>
>>
>> two = one
>>
>>
>>
>> That creates one function object, bound to two names.  What name would you
>>
>> expect to grab inside the function?
>>
>>
>>
>> Even more obscure:
>>
>>
>>
>> two = lamba : "one"
>>
>> one = two
>>
>>
>>
>> Which one of these is the "name" of the function?
>>
>> -- 
>>
>> Tim Roberts, timr@probo.com
>>
>> Providenza & Boekelheide, Inc.
> It is of quite value to me.
> Because I have this situation:
> I have used a dictionary with "function_name":value pair in the top of the code. Now when some function is called, I need to print the value assigned to its name in the dictionary (the functions are defined after the dictionary). Now there is only one bad way-around for me: I need to hard-code the name in the function like this:
> def function_name():
>      print(dict_name.get("function_name"))
> but ofcourse it is a bad thing to do because I have a lot of this type of  functions. It would be better if I can can use the same code for all of them, because they are all essentially doing the same thing.
>
> Now, for your questions:
> If i call one() and two() respectively, i would like to see "one" and "two".
> I dont have much knowledge of lambda functions, neither am i going to use them, so that's something I cant answer.

How about defining a function that prints value and then calls a function?

def call(func_name):
   print(mydict[func_name])
   globals()[func_name]()


You could also define a custom class that does the same thing on attribute
lookup and do something like Call.func_name() .

  -m

-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

[toc] | [prev] | [next] | [standalone]


#35599

FromAbhas Bhattacharya <abhasbhattacharya2@gmail.com>
Date2012-12-27 00:26 -0800
Message-ID<1b2e7f59-6edd-40dd-9d60-35265d67a42d@googlegroups.com>
In reply to#35598
On Thursday, 27 December 2012 13:33:34 UTC+5:30, Mitya Sirenef  wrote:
> 
> How about defining a function that prints value and then calls a function?
> 
> 
> 
> def call(func_name):
> 
>    print(mydict[func_name])
> 
>    globals()[func_name]()
> 
> 
> 
> 
> 
> You could also define a custom class that does the same thing on attribute
> 
> lookup and do something like Call.func_name() .
> 
> 
> 
>   -m
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/

Can you explain me what this means?
globals()[func_name]()

[toc] | [prev] | [next] | [standalone]


#35605

FromMitya Sirenef <msirenef@lightbird.net>
Date2012-12-27 04:07 -0500
Message-ID<mailman.1338.1356599241.29569.python-list@python.org>
In reply to#35599
On 12/27/2012 03:26 AM, Abhas Bhattacharya wrote:
> On Thursday, 27 December 2012 13:33:34 UTC+5:30, Mitya Sirenef  wrote:
>> How about defining a function that prints value and then calls a function?
>>
>>
>>
>> def call(func_name):
>>
>>     print(mydict[func_name])
>>
>>     globals()[func_name]()
>>
>>
>>
>>
>>
>> You could also define a custom class that does the same thing on attribute
>>
>> lookup and do something like Call.func_name() .
>>
>>
>>
>>    -m
>>
>>
>>
>> -- 
>>
>> Lark's Tongue Guide to Python: http://lightbird.net/larks/
> Can you explain me what this means?
> globals()[func_name]()

globals() is a globals dictionary that maps function
names to function objects (along with other things),
so we get the function object by name and then
run it.

  -m

-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

[toc] | [prev] | [next] | [standalone]


#35600

FromAbhas Bhattacharya <abhasbhattacharya2@gmail.com>
Date2012-12-27 00:26 -0800
Message-ID<mailman.1334.1356596827.29569.python-list@python.org>
In reply to#35598
On Thursday, 27 December 2012 13:33:34 UTC+5:30, Mitya Sirenef  wrote:
> 
> How about defining a function that prints value and then calls a function?
> 
> 
> 
> def call(func_name):
> 
>    print(mydict[func_name])
> 
>    globals()[func_name]()
> 
> 
> 
> 
> 
> You could also define a custom class that does the same thing on attribute
> 
> lookup and do something like Call.func_name() .
> 
> 
> 
>   -m
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/

Can you explain me what this means?
globals()[func_name]()

[toc] | [prev] | [next] | [standalone]


#35604

FromChris Rebert <clp2@rebertia.com>
Date2012-12-27 00:58 -0800
Message-ID<mailman.1337.1356598710.29569.python-list@python.org>
In reply to#35588

[Multipart message — attachments visible in raw view] — view raw

On Dec 26, 2012 11:55 PM, "Abhas Bhattacharya" <abhasbhattacharya2@gmail.com>
wrote:
>
> On Thursday, 27 December 2012 10:22:15 UTC+5:30, Tim Roberts  wrote:
> > Abhas Bhattacharya <abhasbhattacharya2@gmail.com> wrote:
> >
[Oh god please stop/avoid using Google Groups with its godawful
reply-quoting style that adds excessive blank lines]
> > >While I am defining a function, how can I access the name (separately
as
> > >string as well as object) of the function without explicitly naming
> > >it(hard-coding the name)?
> > >For eg. I am writing like:
> >
> > >def abc():
> > >    #how do i access the function abc here without hard-coding the
name?
> >
> > Why?  Of what value would that be?
<snip>
> Because I have this situation:
> I have used a dictionary with "function_name":value pair in the top of
the code. Now when some function is called, I need to print the value
assigned to its name in the dictionary (the functions are defined after the
dictionary). Now there is only one bad way-around for me: I need to
hard-code the name in the function like this:
> def function_name():
>     print(dict_name.get("function_name"))
> but ofcourse it is a bad thing to do because I have a lot of this type of
 functions. It would be better if I can can use the same code for all of
them, because they are all essentially doing the same thing.

I agree with the general outline of Mitya's suggestion, i.e. refactor the
"print the associated value" step into a separate function, thus obviating
the self-reference issue; it'd be bad to repeat that code in each function
anyway.

Anyhow, here's a simple variation that exploits decorators (because they're
generally awesome & one of my favorite features):

def printing_name_beforehand(func):
    def wrapper(*args, **kwargs):
        print(the_dict.get(func.__name__))
        return func(*args, **kwargs)
    return wrapper

Usage:

@printing_name_beforehand
def some_func(...):
    # whatever

(Forgive me if there are typos; composing this reply on a tablet is
cumbersome.)

[toc] | [prev] | [next] | [standalone]


#35739

FromTim Roberts <timr@probo.com>
Date2012-12-28 21:01 -0800
Message-ID<d1usd8d6h2upjhqrn3cqrmnulkcte98vpc@4ax.com>
In reply to#35588
Abhas Bhattacharya <abhasbhattacharya2@gmail.com> wrote:
>
>Now, for your questions:
>If i call one() and two() respectively, i would like to see "one" and "two".
>I dont have much knowledge of lambda functions, neither am i going to use
>them, so that's something I cant answer.

My point is not that these are special cases to consider, but rather that
all of these are the GENERAL case.  A function, now matter how it was
created, is an anonymous object that lives out in object space.  Like all
objects, a function object can be bound to many different names.  An object
doesn't know just one name, and when a function object is invoked, it has
NO IDEA what name was used to invoke it.  The information is simply not
available.
-- 
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

[toc] | [prev] | [next] | [standalone]


#35743

FromJussi Piitulainen <jpiitula@ling.helsinki.fi>
Date2012-12-29 12:18 +0200
Message-ID<qotd2xtgo0y.fsf@ruuvi.it.helsinki.fi>
In reply to#35588
Abhas Bhattacharya writes:

[...]

> If i call one() and two() respectively, i would like to see "one"
> and "two". I dont have much knowledge of lambda functions, neither
> am i going to use them, so that's something I cant answer.

It's not about lambda. The following does not contain lambda. What
should be name(one)? name(two)? name(foo)? name(fun(1))? name(fun(3))?

def foo():
    return 3

def fun(x):
    def foo(): return x
    return foo

one = fun(1)
two = one

Note that fun(1)() is a valid call where fun(1) is not given any name
outside fun.

[toc] | [prev] | [next] | [standalone]


#35601

FromChris Rebert <clp2@rebertia.com>
Date2012-12-27 00:26 -0800
Message-ID<mailman.1335.1356597235.29569.python-list@python.org>
In reply to#35505

[Multipart message — attachments visible in raw view] — view raw

On Dec 25, 2012 6:06 PM, "Abhas Bhattacharya" <abhasbhattacharya2@gmail.com>
wrote:
>
> While I am defining a function, how can I access the name (separately as
string as well as object) of the function without explicitly naming
it(hard-coding the name)?
> For eg. I am writing like:
> def abc():
>     #how do i access the function abc here without hard-coding the name?

Not possible per se without resorting to sys._getframe() or similar hackery.
A simple+elegant way to do this would require PEP 3130 (
http://www.python.org/dev/peps/pep-3130/ ) or similar, but that particular
proposal got rejected.

[toc] | [prev] | [next] | [standalone]


#35602

FromAbhas Bhattacharya <abhasbhattacharya2@gmail.com>
Date2012-12-27 00:42 -0800
Message-ID<b0863853-4dd0-44e3-9845-35a9ae1c554e@googlegroups.com>
In reply to#35601
On Thursday, 27 December 2012 13:56:24 UTC+5:30, Chris Rebert  wrote:
> On Dec 25, 2012 6:06 PM, "Abhas Bhattacharya" <abhasbhat...@gmail.com> wrote:
> 
> >
> 
> > While I am defining a function, how can I access the name (separately as string as well as object) of the function without explicitly naming it(hard-coding the name)?
> 
> > For eg. I am writing like:
> 
> > def abc():
> 
> >     #how do i access the function abc here without hard-coding the name?
> 
> Not possible per se without resorting to sys._getframe() or similar hackery.
> 
> A simple+elegant way to do this would require PEP 3130 (http://www.python.org/dev/peps/pep-3130/ ) or similar, but that particular proposal got rejected.

Thanks for telling that. I thought that there is a direct way, and now you have confirmed that there isn't. So, as I can see, Mitya's code can be a perfect way-around, although it will require another function.

[toc] | [prev] | [next] | [standalone]


#35603

FromAbhas Bhattacharya <abhasbhattacharya2@gmail.com>
Date2012-12-27 00:42 -0800
Message-ID<mailman.1336.1356598346.29569.python-list@python.org>
In reply to#35601
On Thursday, 27 December 2012 13:56:24 UTC+5:30, Chris Rebert  wrote:
> On Dec 25, 2012 6:06 PM, "Abhas Bhattacharya" <abhasbhat...@gmail.com> wrote:
> 
> >
> 
> > While I am defining a function, how can I access the name (separately as string as well as object) of the function without explicitly naming it(hard-coding the name)?
> 
> > For eg. I am writing like:
> 
> > def abc():
> 
> >     #how do i access the function abc here without hard-coding the name?
> 
> Not possible per se without resorting to sys._getframe() or similar hackery.
> 
> A simple+elegant way to do this would require PEP 3130 (http://www.python.org/dev/peps/pep-3130/ ) or similar, but that particular proposal got rejected.

Thanks for telling that. I thought that there is a direct way, and now you have confirmed that there isn't. So, as I can see, Mitya's code can be a perfect way-around, although it will require another function.

[toc] | [prev] | [next] | [standalone]


#35620

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-12-27 13:31 +0000
Message-ID<50dc4d98$0$29967$c3e8da3$5496439d@news.astraweb.com>
In reply to#35505
On Tue, 25 Dec 2012 18:00:38 -0800, Abhas Bhattacharya wrote:

> While I am defining a function, how can I access the name (separately as
> string as well as object) of the function without explicitly naming
> it(hard-coding the name)? For eg. I am writing like:
> def abc():
>     #how do i access the function abc here without hard-coding the name?

You can't easily get the function name from inside the function. But you 
*can* easily get the function name from outside the function, so the 
simple solution is to use a decorator to wrap the function with something 
that knows its name. For example:


import functools

def print_function_name(func):
    # Decorate func so that it prints a message when called.
    @functools.wraps(func)
    def inner(*args, **kwargs):
        print "Calling function %s" % func.__name__
        return func(*args, **kwargs)
    return inner


@print_function_name
def spam(n):
    return ' '.join(['spam']*n)

@print_function_name
def breakfast(n):
    return ' and '.join(['ham', 'eggs', spam(n)])


And then in use:

py> spam(3)
Calling function spam
'spam spam spam'
py> 
py> breakfast(5)
Calling function breakfast
Calling function spam
'ham and eggs and spam spam spam spam spam'


I recommend you use this solution if possible.

Unfortunately this doesn't help if you actually need the function name 
*inside* the function, for example:

def invert(n):
    if n != 0:
        return 1/n
    else:
        raise ZeroDivisionError(
            'divide by zero error in function %s' % ***MAGIC GOES HERE***)

(But note, why would I bother doing this? When the traceback prints, it 
already displays the function name. Why am I doing by hand what Python 
automatically does for me?)

If you really must do this, you can do it like this:


import traceback

def get_current_function_name():
    """If this looks like magic, that's because it is."""
    x = traceback.extract_stack(limit=2)
    return x[0][2]


def invert(n):
    if n != 0:
        return 1/n
    else:
        me = get_current_function_name()
        raise ZeroDivisionError('divide by zero error in func %s' % me)



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#35667

Fromalex23 <wuwei23@gmail.com>
Date2012-12-27 17:25 -0800
Message-ID<e6ad625e-8615-4920-8638-44b46633b7f4@d2g2000pbd.googlegroups.com>
In reply to#35620
On Dec 27, 11:31 pm, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> wrote:
> Unfortunately this doesn't help if you actually need the function name
> *inside* the function

Here's an extension of Steven's original decorator that adds a
reference to the function itself into the function's globals, and then
composes a new function from the component parts:

    import new

    def IdentityAwareFunctionDecorator( fn ):
        _globals = fn.__globals__
        _globals['selffunc'] = fn
        name_aware_func = new.function(
            fn.__code__, _globals, fn.__name__, fn.__defaults__,
fn.__closure__ )
        return name_aware_func

    id = IdentityAwareFunctionDecorator

    @id
    def foo():
        return selffunc.__name__

Unfortunately, it also only knows about the original function name, so
'bar = foo; bar()' will still give you 'foo'.

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.python


csiph-web