bende yok' de iç içe işlevlerini desteklemek için her kod karşılaşabileceğiniz nesnenin üzerine yinelemeli döngü gerekir Kod nesnesini inceleyebilirsiniz çünkü iç işlevler tembeldir ve kod nesneleri yalnızca c tam zamanında ıslatıldı. Muhtemelen bakmak istediğiniz şey ast modülüdür. İşte size kısa bir örnek:
import ast, inspect
# this is the test scenario
def function1():
f1_var1 = 42
def function2():
f2_var1 = 42
f2_var2 = 42
def function3():
f3_var1 = 42
# derive source code for top-level function
src = inspect.getsource(function1)
# derive abstract syntax tree rooted at top-level function
node = ast.parse(src)
# next, ast's walk method takes all the difficulty out of tree-traversal for us
for x in ast.walk(node):
# functions have names whereas variables have ids,
# nested-classes may all use different terminology
# you'll have to look at the various node-types to
# get this part exactly right
name_or_id = getattr(x,'name', getattr(x,'id',None))
if name_or_id:
print name_or_id
sonuçlar şunlardır: fonksiyonu1, İşlevsiz2, f1_var1, 3 işlevi, f2_var1, f2_var2, f3_var1. Zorunlu feragatname: Muhtemelen bu tür bir şey yapmak için iyi bir neden yoktur .. ama eğlenin :)
Oh ve sadece iç fonksiyonların isimlerini istiyorsan?
print dict([[x.name,x] for x in ast.walk(ast.parse(inspect.getsource(some_function))) if type(x).__name__=='FunctionDef'])
Bu tek düzeyde bir şey mi yoksa yuvalanmış işlevler mi istiyorsunuz? –