模块"重载"

命题

Davies Liu <[email protected]>
sender-time     Sent at 00:42 (GMT+08:00). Current time there: 9:08 AM. ✆
reply-to        [email protected]
to      python-cn <[email protected]>
date    Wed, Mar 10, 2010 at 00:42
subject [CPyUG] 一种实现模块“重载”的方法

今天因重构代码需要,发现了一种巧妙的方法实现模块级别的"重载",即重新实现模块中的若干内部函数的功能得到一个新模块。

使用方法为:

a.py

   1 def bar():
   2    return 'bar in a'
   3 
   4 def foo():
   5    print bar()

b.py

   1 from a import *
   2 from luzong.utils import callby
   3 
   4 @callby(foo)
   5 def bar():
   6  return 'bar in b'

测试

>>> import a, b
>>> a.foo()
bar in a
>>> b.foo()
bar in b

=== callby.py callby callby 的实现也非常简单:

   1 def clone_func(f, g):
   2   "inspect a func f with globals g"
   3   return f.__class__(f.func_code, g, f.func_name, f.func_defaults)
   4 
   5 def callby(caller):
   6   "auto inspect callers for a function"
   7   def deco(f):
   8       g = f.func_globals
   9       callers = [caller,] if not isinstance(caller, (list, tuple)) else caller
  10       for c in callers:
  11           if c.func_globals is not g:
  12               g[c.func_name] = clone_func(c, f.func_globals)
  13       return f
  14   return deco

破题

张沈鹏 <[email protected]>
sender-time     Sent at 01:40 (GMT+08:00). Current time there: 9:10 AM. ✆
reply-to        [email protected]
to      [email protected]
date    Wed, Mar 10, 2010 at 01:40

这样写流程更清晰

   1 import a
   2 
   3 import sys
   4 sys.modules['xxxx']=sys.modules['a']
   5 del sys.modules['a']
   6 
   7 import a
   8 
   9 import xxxx
  10 
  11 from xxxx import *
  12 xxxx.bar = lambda:"b"
  13 
  14 a.foo()
  15 foo()

劝题

limodou <[email protected]>
sender-time     Sent at 09:06 (GMT+08:00). Current time there: 9:10 AM. ✆
reply-to        [email protected]
to      [email protected]
date    Wed, Mar 10, 2010 at 09:06

callby这种用法很不好理解,不直观,


反馈

创建 by -- ZoomQuiet [2010-03-10 01:11:50]

MiscItems/2010-03-10 (last edited 2010-03-10 05:16:43 by ZoomQuiet)