By user478514


2011-02-21 08:07:23 8 Comments

I can access a python function's attribute inside of function itself by below code:

def aa():
    print aa.__name__
    print aa.__hash__
    # other simliar

However, if above aa() function is a template for write other code, say bb(), I have to write:

def bb():
    print bb.__name__
    print bb.__hash__
    # other simliar

Is there a "pointer" similar to the self argument in a class method so I could write code like this?

def whatever():
    print self.__name__
    print self.__hash__
    # other simliar

I searched and found someone said to use the class to solve this problem, but that may be a trouble to redefine all the existing functions. Any suggestions?

4 comments

@endolith 2019-08-18 12:49:23

You can at least say self = bb in the first line, and then you only need to change that line when you change the function name, instead of every other reference.

My code editor highlights the variable self the same way it does for classes, too.

@Duncan 2011-02-21 08:37:04

There is no generic way for a function to refer to itself. Consider using a decorator instead. If all you want as you indicated was to print information about the function that can be done easily with a decorator:

from functools import wraps
def showinfo(f):
    @wraps(f)
    def wrapper(*args, **kwds):
         print(f.__name__, f.__hash__)
         return f(*args, **kwds)
    return wrapper

@showinfo
def aa():
    pass

If you really do need to reference the function, then just add it to the function arguments:

def withself(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@withself
def aa(self):
      print(self.__name__)
      # etc.

Edit to add alternate decorator:

You can also write a simpler (and probably faster) decorator that will make the wrapped function work correctly with Python's introspection:

def bind(f):
    """Decorate function `f` to pass a reference to the function
    as the first argument"""
    return f.__get__(f, type(f))

@bind
def foo(self, x):
    "This is a bound function!"
    print(self, x)


>>> foo(42)
<function foo at 0x02A46030> 42
>>> help(foo)
Help on method foo in module __main__:

foo(self, x) method of builtins.function instance
    This is a bound function!

This leverages Python's descriptor protocol: functions have a __get__ method that is used to create bound methods. The decorator simply uses the existing method to make the function a bound method of itself. It will only work for standalone functions, if you wanted a method to be able to reference itself you would have to do something more like the original solution.

@Steve Ferg 2012-08-07 14:24:10

How about a quick hack to make your own "self" name, like this:

>>> def f():
...     self = f
...     print "My name is ", self.__name__, "and I am", self.__hash__
...
>>> f()
My name is  f and I am <method-wrapper '__hash__' of function object at 0x00B50F30>
>>> x = f
>>> x()
My name is  f and I am <method-wrapper '__hash__' of function object at 0x00B50F30>
>>>

@Andy Hayden 2012-09-29 13:55:26

Surely this is no different from the OP referring to f.__name__?

@Sheena 2013-06-14 05:37:29

So x's name is f... this doesn't answer the question at all

@akira 2011-02-21 08:23:30

http://docs.python.org/library/inspect.html looks promising:

import inspect
def foo():
     felf = globals()[inspect.getframeinfo(inspect.currentframe()).function]
     print felf.__name__, felf.__doc__

you can also use the sys module to get the name of the current function:

import sys
def bar():
     felf = globals()[sys._getframe().f_code.co_name]
     print felf.__name__, felf.__doc__

@Florian Mayer 2011-02-21 10:33:45

And a lot more work than just referring to the function explicitly.

@akira 2011-02-21 10:57:27

@FLorian Mayer: thats true, thats why i +1 @Duncan for the self-decorator.

@tom stratton 2012-02-23 17:34:45

this is exactly what was asked for... and, while it is not direct and simple I don't think that the decorated version is as clear. (IMO)

Related Questions

Sponsored Content

39 Answered Questions

33 Answered Questions

[SOLVED] What's the difference between a method and a function?

39 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

23 Answered Questions

[SOLVED] Is there a way to run Python on Android?

17 Answered Questions

[SOLVED] How to make a chain of function decorators?

18 Answered Questions

[SOLVED] Using global variables in a function

26 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

26 Answered Questions

[SOLVED] How do I pass a variable by reference?

10 Answered Questions

[SOLVED] What does the exclamation mark do before the function?

  • 2010-09-20 21:21:51
  • Sebastian Otto
  • 162708 View
  • 1231 Score
  • 10 Answer
  • Tags:   javascript function

Sponsored Content