Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created August 4, 2012 06:57

Revisions

  1. podhmo revised this gist Aug 4, 2012. 1 changed file with 1 addition and 4 deletions.
    5 changes: 1 addition & 4 deletions intercept.py
    Original file line number Diff line number Diff line change
    @@ -16,11 +16,8 @@ def __init__(self, name):

    def intercept(cls, method):
    def doaction(caller, *args, **kwargs):
    original_type = caller.__class__
    caller.__class__ = cls
    v = method(caller, *args, **kwargs)
    caller.__class = original_type
    return v
    return method.im_func(caller, *args, **kwargs)
    return doaction


  2. podhmo created this gist Aug 4, 2012.
    38 changes: 38 additions & 0 deletions intercept.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    class A(object):
    fmt = "tweets %s"
    def hello(self):
    return "hello " + self.name

    @classmethod
    def tweets(cls, mes):
    return cls.fmt % mes
    def __init__(self, name):
    self.name = name

    class B(object):
    fmt = "called with B: %s"
    def __init__(self, name):
    self.name = name

    def intercept(cls, method):
    def doaction(caller, *args, **kwargs):
    original_type = caller.__class__
    caller.__class__ = cls
    v = method(caller, *args, **kwargs)
    caller.__class = original_type
    return v
    return doaction


    print A("foo").hello()
    try:
    print A.hello(B("bar"))
    except TypeError, e:
    print e
    print intercept(A, A.hello)(B("bar"))

    print "=="

    print A.tweets("hey")
    B.tweets = A.__dict__["tweets"]
    print B.tweets("bar")