开发者

Custom dictionary through **kw

开发者 https://www.devze.com 2023-02-07 03:48 出处:网络
I have a library function that makes use of **kw, but I want to pass a dictionary-like class so that I can override __getitem__ to track its accesses to data in the dictionary.For example, in the code

I have a library function that makes use of **kw, but I want to pass a dictionary-like class so that I can override __getitem__ to track its accesses to data in the dictionary. For example, in the code below calling libfn does not print Accessed but libfn2 does.

class Dtracker(dict):
  def __init__(self):
    dict.__init__(self)
  def __getitem__(self,item):
    print "Accessed %s" % str(item)
    return dict.__getitem__(self, item)


def libfn(**kw):
  a = kw["foo"]
  print "a is %s" % a
  return a

def l开发者_StackOverflow中文版ibfn2(kw):
  a = kw["foo"]
  print "a is %s" % a
  return a

d = Dtracker()
d["foo"] = "bar"  
libfn(**d)
libfn2(d)


You can't, without changing Python itself. It's converted to a dict at a lower level.


Do this

class Dtracker(dict):
    def __init__(self,*arg,**kw):
        super(Dtracker,self).__init__(*arg,**kw)
    def __getitem__(self,item):
        print "Accessed %s" % str(item)
        return dict.__getitem__(self, item)

def track( fn ):
    def tracked_fn( **kw ):
        kw= Dtracker( kw )
        fn( kw )
    return tracked_fn

@track
def libfn(kw):
    a = kw["foo"]
    print "a is %s" % a
    return a

This more-or-less works

>>> libfn( **{'foo':'bar'} )
Accessed foo
a is bar
0

精彩评论

暂无评论...
验证码 换一张
取 消