function name

Discussion in 'Python' started by Richard Lamboj, Apr 28, 2010.

  1. Hello,

    is there any way to get the name from the actual called function, so that the
    function knows its own name?

    Kind Regards,

    Richi
    Richard Lamboj, Apr 28, 2010
    #1
    1. Advertising

  2. Richard Lamboj

    Peter Otten Guest

    Richard Lamboj wrote:

    > is there any way to get the name from the actual called function, so that
    > the function knows its own name?


    >>> import sys
    >>> def my_name():

    .... return sys._getframe(1).f_code.co_name
    ....
    >>> def rumpelstilzchen():

    .... print u"Ach, wie gut dass niemand weiß, dass ich", my_name().title(), u"heiß"
    ....
    >>> rumpelstilzchen()

    Ach, wie gut dass niemand weiß, dass ich Rumpelstilzchen heiß

    Peter
    Peter Otten, Apr 28, 2010
    #2
    1. Advertising

  3. Richard Lamboj

    Brendan Abel Guest

    On Apr 28, 11:44 am, Richard Lamboj <> wrote:
    > Hello,
    >
    > is there any way to get the name from the actual called function, so that the
    > function knows its own name?
    >
    > Kind Regards,
    >
    > Richi


    If you want to get the function name from within the function itself,
    check out the inspect module.
    http://docs.python.org/library/inspect.html#inspect.currentframe
    Brendan Abel, Apr 28, 2010
    #3
  4. * Richard Lamboj:
    >
    > is there any way to get the name from the actual called function, so that the
    > function knows its own name?


    There was an earlier thread about this not very long ago.

    General consensus, as I recall, to replace function with an object of a class
    (possibly with __call__ method if it is to be function-like, "functor").

    An alternative is to treat the function itself as an object. I posted code for a
    decorator to help do that. Of course today I deleted that code (I just use a
    single 'x.py' file for various examples), but you may find it by Googling;
    however, I recommend the consensus view of "real" object.

    A third way, even less desirable IMVHO, might be to use introinspection.

    Let's see, ... reusing that 'x.py' file again ...

    <code file="x.py">
    #Py3

    import inspect

    def foo():
    frame = inspect.currentframe()
    info = inspect.getframeinfo( frame )
    print( info )

    foo()
    </code>

    <output>
    Fatal Python error: Py_Initialize: can't initialize sys standard streams
    Traceback (most recent call last):
    File "C:\Program Files\cpython\python31\lib\encodings\__init__.py", line 31,
    in <module>
    import codecs
    File "C:\Program Files\cpython\python31\lib\codecs.py", line 8, in <module>
    """#"
    KeyboardInterrupt

    This application has requested the Runtime to terminate it in an unusual way.
    Please contact the application's support team for more information.
    </output>


    Oh my, I crashed the Python interpreter! This is my third time stumbling upon a
    crash-the-interpreter bug in CPython 3.x. I think I'm good at crashing things.

    But OK, let's see. Well. Hm.


    <code file="x.py">
    #Py3

    import inspect

    def foo():
    frame = None; info = None; s = None;
    frame = inspect.currentframe()
    info = inspect.getframeinfo( frame )
    s = "Pleased to meet you, I was originally called '{}'!".format(
    info.function )
    print( s )

    bar = foo
    del foo

    bar()
    </code>

    <output>
    Pleased to meet you, I was originally called 'foo'!
    </output>


    But as mentioned, I'd personally choose a "real" object instead of a bare function.


    Cheers & hth.,

    - Alf
    Alf P. Steinbach, Apr 28, 2010
    #4
  5. Richard Lamboj

    Terry Reedy Guest

    On 4/28/2010 3:20 PM, Alf P. Steinbach wrote:
    > * Richard Lamboj:
    >>
    >> is there any way to get the name from the actual called function, so
    >> that the
    >> function knows its own name?

    >
    > There was an earlier thread about this not very long ago.
    >
    > General consensus, as I recall, to replace function with an object of a
    > class (possibly with __call__ method if it is to be function-like,
    > "functor").
    >
    > An alternative is to treat the function itself as an object. I posted
    > code for a decorator to help do that. Of course today I deleted that
    > code (I just use a single 'x.py' file for various examples), but you may
    > find it by Googling; however, I recommend the consensus view of "real"
    > object.
    >
    > A third way, even less desirable IMVHO, might be to use introinspection.
    >
    > Let's see, ... reusing that 'x.py' file again ...
    >
    > <code file="x.py">
    > #Py3
    >
    > import inspect
    >
    > def foo():
    > frame = inspect.currentframe()
    > info = inspect.getframeinfo( frame )
    > print( info )
    >
    > foo()
    > </code>
    >
    > <output>
    > Fatal Python error: Py_Initialize: can't initialize sys standard streams
    > Traceback (most recent call last):
    > File "C:\Program Files\cpython\python31\lib\encodings\__init__.py", line
    > 31, in <module>
    > import codecs
    > File "C:\Program Files\cpython\python31\lib\codecs.py", line 8, in <module>
    > """#"
    > KeyboardInterrupt
    >
    > This application has requested the Runtime to terminate it in an unusual
    > way.
    > Please contact the application's support team for more information.
    > </output>
    >
    >
    > Oh my, I crashed the Python interpreter! This is my third time stumbling
    > upon a crash-the-interpreter bug in CPython 3.x. I think I'm good at
    > crashing things.


    Perhaps you push harder, perhaps you are more observant and persistent
    in verifying such things.

    However, in this case, with "Python 3.1.2 (r312:79149, Mar 21 2010,
    00:41:52) [MSC v.1500 32 bit (Intel)] on win32", I reproducibly get

    Traceback(filename='C:\\Programs\\Python31\\misc\\t1.py', lineno=5,
    function='foo', code_context=[' info = inspect.getframeinfo( frame
    )\n'], index=0)

    on fresh IDLE and

    Traceback(filename='<stdin>', lineno=3, function='foo',
    code_context=None, index=None)

    with a fresh command window. Both are more or less as expected. Were you
    using an earlier version? Different system? Did you run other code first?

    Terry Jan Reedy
    Terry Reedy, Apr 28, 2010
    #5
  6. On Wed, 28 Apr 2010 21:03:36 +0200, Peter Otten wrote:

    > Richard Lamboj wrote:
    >
    >> is there any way to get the name from the actual called function, so
    >> that the function knows its own name?

    >
    >>>> import sys
    >>>> def my_name():

    > ... return sys._getframe(1).f_code.co_name


    Be aware though, that sys._getframe is marked as a private function (the
    leading underscore), which means that:

    (1) It only exists in some Python implementations (CPython and possible
    nothing else?); and

    (2) It is officially subject to change without warning, although that's
    unlikely.


    In practice, it's probably safe to use, but be aware that you are using a
    documented internal feature.


    --
    Steven
    Steven D'Aprano, Apr 29, 2010
    #6
  7. Richard Lamboj

    Peter Otten Guest

    Steven D'Aprano wrote:

    > Be aware though, that sys._getframe is marked as a private function (the
    > leading underscore), which means that:
    >
    > (1) It only exists in some Python implementations (CPython and possible
    > nothing else?); and


    $ jython
    Jython 2.2.1 on java1.6.0_0
    Type "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> def f(): return sys._getframe().f_code.co_name

    ....
    >>> f()

    'f'

    $ ipy
    IronPython 1.1.1 (1.1.1) on .NET 2.0.50727.1433
    Copyright (c) Microsoft Corporation. All rights reserved.
    >>> import sys
    >>> sys._getframe()

    Traceback (most recent call last):
    ValueError: _getframe is not implemented
    >>> raise SystemExit # is there a sane way to quit ipy?


    A quick websearch unearthed

    http://blogs.msdn.com/dinoviehland/archive/2009/12/11/ironpython-2-6-
    released.aspx

    """
    IronPython 2.6 Released!

    [...]

    This release also changes how we support sys._getframe: a fully working
    version is now available by a command line option; when not enabled
    sys._getframe doesn’t exist at all.
    """

    Peter
    Peter Otten, Apr 29, 2010
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?iso-8859-1?B?bW9vcJk=?=
    Replies:
    7
    Views:
    802
    Roedy Green
    Jan 2, 2006
  2. ding feng
    Replies:
    2
    Views:
    2,782
    ding feng
    Jun 25, 2003
  3. Bobby Chamness
    Replies:
    2
    Views:
    2,376
    Joe Smith
    Apr 22, 2007
  4. Jack-2
    Replies:
    3
    Views:
    253
    Jack-2
    Dec 24, 2003
  5. Java  script  Dude

    IE name="name" & form.name property bug

    Java script Dude, Jun 29, 2004, in forum: Javascript
    Replies:
    5
    Views:
    221
    Java script Dude
    Jun 30, 2004
Loading...

Share This Page