2016-09-27 1 views
3

ich ein Modul mymod haben dieWrap alle Funktionen in einem Modul in einem Wrapper

def myfun1 (a,b,c): 
    ... 
    return d 

ich alle diese Funktionen so verfolgen möchten ein Dutzend Funktionen mit derselben Signatur definiert:

def traced (f): 
    def wrapped (a,b,c): 
     print ">>>%s(%d)" % (f.__name__, (a+b)/c) 
     d = f(a,b,c) 
     print "<<<%s(%g)" % (f.__name__, 1/d) 
     return d 
    return wrap 

@traced 
def myfun1 (a,b,c): 
    ... 
    return d 

(Hier (a+b)/c und 1/d sind Stellvertreter für kompliziertere Sachen).

Gibt es eine elegantere Möglichkeit, dies zu erreichen - abgesehen von @traced vor Funktionsdefinition?

PS. A similar question wurde vor 5 Jahren gefragt. Ich frage mich, ob es neue Antworten gibt.

+0

https://pypi.python.org/pypi/metamodule von Interesse sein könnten. – chepner

+0

http://stackoverflow.com/questions/39184338/how-can-i-decorate-all-functions-imported-from-a-file dupe? [meine Antwort mindestens] –

Antwort

0

die globals() dict Durch den Besuch ist es möglich:

def myfun1 (a,b,c): 
    return 1.+a+b+c 

def myfun2 (a,b,c): 
    return 1.+a+b-c 

def traced (f): 
    def wrapped (a,b,c): 
     print ">>>%s(%d)" % (f.__name__, (a+b)/c) 
     d = f(a,b,c) 
     print "<<<%s(%g)" % (f.__name__, 1/d) 
     return d 
    return wrapped 

print 'myfun1(1,2,3): ', myfun1(1,2,3) 
print 'myfun2(1,2,3): ', myfun2(1,2,3) 

import types 
for x in globals().copy(): # copy() is mandatory because globals() is being updated 
    if x == 'traced' or x.startswith('__'): # Ignore trace function and private ones 
     continue 
    if isinstance(globals()[x], types.FunctionType): 
     print "Found function:", x 
     globals()[x] = traced(globals()[x]) 


print 'myfun1(1,2,3): ', myfun1(1,2,3) 
print 'myfun2(1,2,3): ', myfun2(1,2,3) 

Ergebnis:

myfun1(1,2,3): 7.0 
myfun2(1,2,3): 1.0 
Found function: myfun1 
Found function: myfun2 
myfun1(1,2,3): >>>myfun1(1) 
<<<myfun1(0.142857) 
7.0 
myfun2(1,2,3): >>>myfun2(1) 
<<<myfun2(1) 
1.0