python - How Awful is My Decorator? -


i created @sequenceable decorator, can applied function takes 1 argument, , causes automatically applicable sequence. code (python 2.5):

def sequenceable(func):     def newfunc(arg):         if hasattr(arg, '__iter__'):             if isinstance(arg, dict):                 return dict((k, func(v)) k, v in arg.iteritems())             else:                 return map(func, arg)         else:             return func(arg)     return newfunc 

in use:

@sequenceable def unixtime(dt):     return int(dt.strftime('%s'))  >>> unixtime(datetime.now()) 1291318284 >>> unixtime([datetime.now(), datetime(2010, 12, 3)]) [1291318291, 1291352400] >>> unixtime({'start': datetime.now(), 'end': datetime(2010, 12, 3)}) {'start': 1291318301, 'end': 1291352400} 

my questions are:

  • is terrible idea, , why?
  • is possibly idea, has significant drawbacks implemented?
  • what potential pitfalls of using code?
  • is there builtin or library i'm doing?

this is terrible idea. loose typing. duck-typing far stuff should taken, imo.

consider this:

def pluralize(f):     def on_seq(seq):         return [f(x) x in seq]     def on_dict(d):          return dict((k, f(v)) k, v in d.iteritems())     f.on_dict = on_dict     f.on_seq = on_seq     return f 

your example becomes

@pluralize def unixtime(dt):     return int(dt.strftime('%s'))   unixtime.on_seq([datetime.now(), datetime(2010, 12, 3)]) unixtime.on_dict({'start': datetime.now(), 'end': datetime(2010, 12, 3)}) 

doing way still requires caller know (to within duck-typing accuracy) being passed in , doesn't add typechecking overhead actual function. work dict-like object whereas original solution depends on being actual subclass of dict.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -