0

Can I, inside the decorator, refer to the name of the object being decorated? E.g.,

def add_debug_info(func):
    # how to write magic_function?
    name = magic_function(func)
    # name is 'execute' when applied as
    # @add_debug_info
    # def execute():

I'm trying to print out debugging statements that incude this name, since I'm passing higher level functions around and it's hard to tell which function the debugging statement is referring to.

I'm only aware of one approach to get to the name of an object, but it doesn't work well here (multiple names can refer to an object, but I want the one specific name that happened to be decorated).

Community
  • 1
  • 1
max
  • 49,282
  • 56
  • 208
  • 355
  • You can use `func.__name__` or `func.func_name` I believe... – mgilson Jan 16 '13 at 21:25
  • @mgilson: `__name__` is the preferred spelling these days, as it works for more than just functions. – Martijn Pieters Jan 16 '13 at 21:31
  • @MartijnPieters -- I knew one was preferred, but I couldn't remember which. Consequently that's why I didn't post an answer -- Hopefully I'll remember this time around :) – mgilson Jan 16 '13 at 21:35

1 Answers1

3

The original name of a function is stored in the .__name__ attribute:

>>> def foo(): pass
...
>>> foo.__name__
'foo'
>>> bar = foo
>>> bar.__name__
'foo'

You can find interesting bits of information like this in the datamodel documentation, and a lot of that information is also summarized in the documentation for the inspect module.

You may also want to take a look at the functools.wraps decorator, which updates a wrapper function (often used in decorators) with attributes from the original, wrapped function, including it's name and it's documentation string.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343