@simple_debug

Jesse 发表于 2008-07-12 20:19:29

Update(08-07-22):
I continued with <Learning Python>, which enlightened me with this @.
@ brings what is called 'function decorator',  and it's VERY simple, much simpler than what I wrote below ;-)

1 @foo
    # foo be a callable object
2 def bar():
3     ...

The above code works as: bar = foo(bar). No more, no less.
It again reflects the simple YET powerful nature of Python. Enjoy !-)

####original stuff########
In the source of gnome-sudoku, they use '@simple_debug' to debug and step through the program. However, I can't find a lesson on Python's '@' on the web. How to let google search such non-alphanumberic characters for me?

But I tried out this @, as following.
Try this,
###########
def bar (par1):
    print 'in bar with', par1

def debug (f):
    print 'in debug'
    return bar

@debug
def foo (a):
    print 'FOO!', a

foo('hello')
###########

output:
in debug
in bar with hello

###########
How does it work?
1. First use '@' before a function define(foo here).
2. When you call foo(), Python will not run foo(),
instead, the function after '@', debug() here, is executed.
3. Python hands foo to debug() as a argument and debug() is supposed to return one function, bar() here.
4. Moreover, the returned function bar() should receive the same parameters as the defined foo
5. Then besides foo is itself passed to debug(), foo's arguments are passed to bar.
6. bar() with arguments from foo is executed.

foo() is NOT executed.
In order to run foo(), we have to do so manually in debug() and bar(). This is how gnome-sudoku does:
###########
1if options.debug:
2    def simple_debug (f):
3        def _ (self, *args,**kwargs):
4            print self.__class__,f.__name__,args,kwargs
5            return f(self,*args,**kwargs)
6
        return _
###########
The original function f runs at line 5 and its return value is returned as well.
To debug all kinds of function, it use *args and **kwargs.

###########

Then following definition let simple_debug do nothing.
else:
    def simple_debug (f): return f
###########

Jesse
关键词(Tag): python

收藏: QQ书签 del.icio.us 订阅: Google 抓虾

最新评论

发表评论

* 昵称

已经注册过? 请登录

新用户请先注册 以便能显示头像及追踪评论回复

Email
网址
* 评论
表情
 
 

分类小组论坛
杂谈, 娱乐、八卦, 文学、艺术, 体育, 旅游、同城, 象牙塔, 情感, 时尚、生活, 星座, 科技

请注意遵守中华人民共和国法律法规, 如威胁到本站生存, 将依法向有关部门报告, 同时本站的相关记录可能成为对您不利的证据.

相关法律法规
全国人大常委会关于维护互联网安全的决定
中华人民共和国计算机信息系统安全保护条例
中华人民共和国计算机信息网络国际联网管理暂行规定
计算机信息网络国际联网安全保护管理办法
计算机信息系统国际联网保密管理规定