跳到主要內容

Using descriptor as explicit delegation in Python

Descriptors in Python is an interesting approach to simplifying many difficult design problems. I would like to share one of my application of this useful feature. Consider the following code snippet:

class MailEvent(object):
   def fire(self, instance, cls):
      print "handling mail event from " + str(cls.__name__) + " " + str(instance.name)

class LogEvent(object):
   def fire(self, instance, cls):
      print "handling log event from " + str(cls.__name__) + " " + str(instance.name)

# using inheritance
class BaseWorker(object):
   def __init__(self, name):
      self.name = name
      self.event_factory = {"mail":MailEvent(), "log":LogEvent()}

   def event(self, evt):
      if evt in self.event_factory:
         self.event_factory[evt].fire(self, type(self))

class Worker(BaseWorker):
   pass

worker = Worker("SIMPLE")
worker.event("mail")
worker.event("log")

In BaseWorker, we have an event_factory created and we fire one of the events in the factory when the method, event(), of BaseWorker is called. With event() defined in BaseWorker class, programmers can inherit it and get the power of event without any effort. However, there are some problems arising when event() is not the only operation in BaseWorker. As time goes by, other programmers might add more and more operations. Therefore BaseWorker became more and more unmaintainable and...ugly. :P

How to solve this issue? There is a simple solution: delegate the responsibilities to those classes who should care about it.

##### delegation approach #####
# naive way
class EventProxyA(object):
   def __init__(self):
      self.event_factory = {"mail":MailEvent(), "log":LogEvent()}

   def handle_event(self, evt, instance, cls):
      if evt in self.event_factory:
         self.event_factory[evt].fire(instance, cls)

class BaseWorkerA(object):
   def __init__(self, name):
      self.name = name
      self.event_proxy = EventProxyA()

   def event(self, evt):
      self.event_proxy.handle_event(evt, self, type(self))

class WorkerA(BaseWorkerA):
   pass

worker = WorkerA("SIMPLE_A")
worker.event("mail")
worker.event("log")
The idea is very simple. We try to separate the work to another class and ask it to do what we need. We can see that BaseWorkerA cleaner than BaseWorker. You know this basic trick very well. Some people give this trick a name, delegation. But there is still a problem. If you see the implementation of BaseWorkerA, could you realize the event a delegation to another class object immediately? Try to imagine the delegation tricks and methods of BaseWorkerA mixed together (just as usual class). Could you really see what you want to describe after weeks? Not easy.

We can use Python's descriptor to make delegations much more obvious. :-)

# using descriptor
class EventProxyB(object):
   def __init__(self):
      self.event_factory = {"mail":MailEvent(), "log":LogEvent()}

   def __get__(self, instance, cls):
      def handle(evt):
         if evt in self.event_factory:
            # access caller's info without passing any parameter
            self.event_factory[evt].fire(instance, cls)
      return handle;

class BaseWorkerB(object):
   event = EventProxyB()
   def __init__(self, name):
      self.name = name

class WorkerB(BaseWorkerB):
   pass

worker = WorkerB("SIMPLE_B")
worker.event("mail")
Each time we access the event variable in BaseWorkerB, we would get a function object. From the view of users of BaseWorkerB, they can not distinguish the difference between methods and descriptors and the author of BaseWorkerB get much clearer for what are delegations and what are the methods of the BaseWorkerB really need to do. Neat, right?

留言

這個網誌中的熱門文章

淺讀Linux root file system初始化流程

在Unix的世界中,file system佔據一個極重要的抽象化地位。其中,/ 所代表的rootfs更是所有後續新增file system所必須依賴前提條件。以Linux為例,黑客 Jserv 就曾經詳細說明過 initramfs的背後設計考量 。本篇文章不再重複背景知識,主要將追蹤rootfs初始化的流程作點整理,免得自己日後忘記。 :-) file system與特定CPU架構無關,所以我觀察的起點從init/main.c的start_kernel()開始,這是Linux作完基本CPU初始化後首先跳進的C function(我閱讀的版本為 3.12 )。跟root file system有關的流程羅列如下: start_kernel()         -> vfs_caches_init_early()         -> vfs_caches_init()                 -> mnt_init()                         -> init_rootfs()                         -> init_mount_tree()         -> rest_init()                 -> kernel_thread(kernel_init,...) 其中比較重要的是mnt_int()中的init_rootfs()與init_mout_tree()。init_rootfs()實作如下: int __init init_rootfs(void) {         int err = register_filesystem(&rootfs_fs_type);         if (err)                 return err;         if (IS_ENABLED(CONFIG_TMPFS) && !saved_root_name[0] &&                 (!root_fs_names || strstr(root_fs_names, "tmpfs"))) {          

誰在呼叫我?不同的backtrace實作說明好文章

今天下班前一個同事問到:如何在Linux kernel的function中主動印出backtrace以方便除錯? 寫過kernel module的人都知道,基本上就是用dump_stack()之類的function就可以作到了。但是dump_stack()的功能是如何作到的呢?概念上其實並不難,慣用手法就是先觀察stack在function call時的變化(一般OS或計組教科書都有很好的說明,如果不想翻書,可以參考 這篇 ),然後將對應的return address一層一層找出來後,再將對應的function名稱印出即可(透過執行檔中的section去讀取函式名稱即可,所以要將KALLSYM選項打開)。在userspace的實作可參考Jserv介紹過的 whocallme 或對岸好手實作過的 backtrace() ,都是針對x86架構的很好說明文章。 不過從前面兩篇文章可以知道,只要知道編譯器的calling convention,就可以實作出backtrace,所以是否GCC有提供現成的機制呢?Yes, that is what __builtin_return_address() for!! 可以參考這篇 文章 。該篇文章還提到了其他可以拿來實作功能更齊全的backtrace的 程式庫 ,在了解了運作原理後,用那些東西還蠻方便的。 OK,那Linux kernel是怎麼做的呢?就是用頭兩篇文章的方式啦~ 每個不同的CPU架構各自手工實作一份dump_stack()。 為啥不用GCC的機制?畢竟...嗯,我猜想,除了backtrace以外,開發者還會想看其他register的值,還有一些有的沒的,所以光是GCC提供的介面是很難印出全部所要的資訊,與其用半套GCC的機制,不如全都自己來~ arm的實作 大致上長這樣,可以看到基本上就只是透過迭代fp, lr, pc來完成: 352 void unwind_backtrace (struct pt_regs * regs , struct task_struct *tsk) 353 { 354 struct stackframe frame ; 355 register unsigned long current_sp asm ( "

kernel panic之後怎麼辦?

今天同事在處理一個陌生的模組時遇到kernel panic,Linux印出了backtrace,同事大致上可以知道是在哪個function中,但該function的長度頗長,短時間無法定位在哪個位置,在這種情況下,要如何收斂除錯範圍呢?更糟的是,由於加入printk會改變模組行為,所以printk基本上無法拿來檢查參數的值是否正常。 一般這樣的問題會backtrace的資訊來著手。從這個資訊我們可以知道在function中的多少offset發生錯誤,以x86為例(從 LDD3 借來的例子): Unable to handle kernel NULL pointer dereference at virtual address 00000000 printing eip: d083a064 Oops: 0002 [#1] SMP CPU:    0 EIP:    0060:[<d083a064>]    Not tainted EFLAGS: 00010246   (2.6.6) EIP is at faulty_write+0x4/0x10 [faulty] eax: 00000000   ebx: 00000000   ecx: 00000000   edx: 00000000 esi: cf8b2460   edi: cf8b2480   ebp: 00000005   esp: c31c5f74 ds: 007b   es: 007b   ss: 0068 Process bash (pid: 2086, threadinfo=c31c4000 task=cfa0a6c0) Stack: c0150558 cf8b2460 080e9408 00000005 cf8b2480 00000000 cf8b2460 cf8b2460        fffffff7 080e9408 c31c4000 c0150682 cf8b2460 080e9408 00000005 cf8b2480        00000000 00000001 00000005 c0103f8f 00000001 080e9408 00000005 00000005 Call Trace:  [<c0150558>] vfs