Custom Search

Sunday, March 27, 2011

Python Using Functions as Decorators

Python Using Functions as Decorators

#############Using Functions as Decorators###########
#http://www.python.org/dev/peps/pep-0318/
#http://www.siafoo.net/article/68

def apply(func):
print "\n------func----", func
print "\n------locals()----", locals()
return func()

@apply
def test():
print "\n----in test-----"
return 'hello'

print "----1----", test

"""
Equal to
fun = apply(test)
"""

print "=========A========="

def apply1(t):
print "\n----t------", t
print "\n----locals()------", locals()
def apply2(f):
print "\n----f------", f
print "\n----vars(f)------", vars(f)
print "\n-----locals()-----", locals()
print "\n-----can access t here--------", t
def apply3(x,y):
print "\n----x,y------", x,y
print "\n----- locals()-----", locals()
print "\n-----can access t here--------", t
print "\n-------apply3--------", apply3, vars(apply3)
print "\n-------globals--------", globals()
return apply3
print "\n-------apply2--------", apply2, vars(apply2)
return apply2

t=100
@apply1(t)
def test1(a, b):
print "\n----in test1-----"
return a+b

print "\n----2-----", test1(5,5)

print "\n-------apply1--------", apply1, vars(apply1)
print "\n-------test1--------", test1, vars(test1)

"""
Equal to
fun = apply1(t)(test1)(a,b)

OR

apply2=apply1(t)
apply3=apply2(test1)
fun=apply3(a,b)
"""

print "=========B========="

"""
http://www.python.org/dev/peps/pep-0318/
http://www.siafoo.net/article/68

@dec2
@dec1
def func(arg1, arg2, ...):
pass

This is equivalent to:

def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))

---------------------------------

@decomaker(argA, argB, ...)
def func(arg1, arg2, ...):
pass

This is equivalent to:

func = decomaker(argA, argB, ...)(func)

"""
print "=========C========="

#############Using Class as Decorators###########
#http://www.artima.com/weblogs/viewpost.jsp?thread=240808


OUTPUT
=======

------func----

------locals()---- {'func': }

----in test-----
----1---- hello
=========A=========

----t------ 100

----locals()------ {'t': 100}

-------apply2-------- {}

----f------

----vars(f)------ {}

-----locals()----- {'t': 100, 'f': }

-----can access t here-------- 100

-------apply3-------- {}

-------globals-------- {'apply1': ,
'__builtins__': ,
'__file__': 'deco.py', '__package__': None, 't': 100,
'apply': , 'test': 'hello',
'__name__': '__main__', '__doc__': None}

----2-----
----x,y------ 5 5

----- locals()----- {'y': 5, 'x': 5, 't': 100}

-----can access t here-------- 100
None

-------apply1-------- {}

-------test1-------- {}
=========B=========
=========C=========


No comments:

Post a Comment