2

Ok, so I have a function that takes a function as an argument.

I would like to append the actual name of the function (not a member) that has been passed in...

def a_specially_named_function(g):
    return ()

def analyze_function(function):
    print ...


analyze_function(a_specially_named_function)
>>> "a_specially_named_function"

How would I do this? In .NET I believe I would use reflections...I would like to do this without having to add members or anything...

Chris
  • 28,822
  • 27
  • 83
  • 158

1 Answers1

3

There is a magic field called .__name__

def a_specially_named_function(g):
    return ()

def analyze_function(function):
    print function.__name__


analyze_function(a_specially_named_function)
>>> a_specially_named_function

Furthermore, you can use dir function to check all available fields of an object in python, including its magic members

dir(a_specially_named_function)
>>> ['__call__', '__class__', '__closure__', '__code__', 
     '__defaults__', '__delattr__', '__dict__', '__doc__',
     '__format__', '__get__', '__getattribute__', '__globals__',
     '__hash__', '__init__', '__module__', '__name__', '__new__', 
     '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
     '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 
     'func_code', 'func_defaults', 'func_dict', 'func_doc', 
     'func_globals', 'func_name']
lejlot
  • 64,777
  • 8
  • 131
  • 164
  • ok, awesome, thanks! – Chris Nov 28 '15 at 18:48
  • This isn't foolproof. Define `foo`, then `foo.__name__` is `"foo"` as expected. But do `bar = foo` and `bar.__name__` is *NOT* `"bar"`, but `"foo"` still. I don't know what you mean by a "magic field" but it aint that magic. – Spacedman Nov 28 '15 at 18:50
  • @Spacedman: it is magic, because it happened automagically. When you do `bar = foo` you do not define a new function, but just declare a new reference to `foo`. So it is hopeful that `bar.__name__` **is** `foo`: all references to same object behave the same. – Serge Ballesta Nov 28 '15 at 18:54
  • @Spacedman I call them **magic** because they are called this way in python community http://www.rafekettler.com/magicmethods.html http://www.diveintopython3.net/special-method-names.html http://stackoverflow.com/questions/1090620/special-magic-methods-in-python – lejlot Nov 28 '15 at 21:21
  • @Spacedman , furthermore, `bar.__name__` **should** be foo, as Serge explained. `__name__` is the name of a function, not a name of a variable (and by putting bar = foo you just create a variable containing a reference to a function) – lejlot Nov 28 '15 at 21:22