2009-10-08 11 views
8
def applejuice(q): 
    print THE FUNCTION NAME! 

Dovrebbe risultare in "applejuice" come stringa.Come stampare il nome della funzione come una stringa in Python dall'interno di quella funzione

+1

Vedi http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question-on-so/25128#25128 –

+1

Dalla risposta che ha scelto il possibile concludere che questo era davvero un duplicato. In effetti, esisteva già una domanda quasi identica: http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python –

+0

Non sono d'accordo che si tratti di un duplicato di # 251464 - sembra che questa domanda sia l'inversa. –

risposta

19

Questo funziona anche:

import sys 

def applejuice(q): 
    func_name = sys._getframe().f_code.co_name 
    print func_name 
2

È necessario spiegare qual è il problema. Perché la risposta alla tua domanda è:

print "applejuice" 
+2

forse intende: def func (anothah_func): print anothah_func's name – wilhelmtell

+0

Beh, questo è sicuramente possibile. Vedremo se dice qual è il problema. –

7
import traceback 

def applejuice(q): 
    stack = traceback.extract_stack() 
    (filename, line, procname, text) = stack[-1] 
    print procname 

Presumo che ciò viene utilizzato per il debugging, per cui si potrebbe desidera esaminare le altre procedure offerte dallo traceback module. Ti permettono di stampare l'intero stack di chiamate, tracce di eccezione, ecc

3

Un altro modo

import inspect 
def applejuice(q): 
    print inspect.getframeinfo(inspect.currentframe())[2] 
0
def foo(): 
    # a func can just make a call to itself and fetch the name 
    funcName = foo.__name__ 
    # print it 
    print 'Internal: {0}'.format(funcName) 
    # return it 
    return funcName 

# you can fetch the name externally 
fooName = foo.__name__ 
print 'The name of {0} as fetched: {0}'.format(fooName) 

# print what name foo returned in this example 
whatIsTheName = foo() 
print 'The name foo returned is: {0}'.format(whatIsTheName) 
Problemi correlati