python - How can I cleanly associate a constant with a function? -


i have series of functions apply each record in dataset generate new field store in dictionary (the records—"documents"—are stored using mongodb). broke them unrelated, , tie them passing them list function iterates through each operation each record , adds on results.

what irks me how i'm going in seems inelegant manner; semi-duplicating names among other things.

def _midline_length(blob):     '''generate midline sequence *blob*'''     return 42 midline_length = {         'func':  _midline_length,         'key': 'calc_seq_midlen'} #: midline sequence key/function pair. 

lots of these...

do_calcs = [midline_length, ] # functions ... 

then called like:

for record in mongo_collection.find():     calc in do_calcs:         record[calc['key']] = calc['func'](record) # add new data record     # update record in db 

splitting keys makes easier remove calculated fields in database (pointless after set, while developing code , methodology it's handy).

i had thought maybe use classes, seems more abuse:

class midline_length(object):     key = 'calc_seq_midlen'     @staticmethod     def __call__(blob):         return 42 

i make list of instances (do_calcs = [midline_length(), ...]) , run through calling each thing or pulling out it's key member. alternatively, seems can arbitrarily add members functions, def myfunc(): myfunc.key = 'mykey'...that seems worse. better ideas?

you might want use decorators purpose.

import collections recordfunc = collections.namedtuple('recordfunc', 'key func')  def record(key):     def wrapped(func):         return recordfunc(key, func)     return wrapped  @record('midline_length') def midline_length(blob):     return 42 

now, midline_length not function, recordfunc object.

>>> midline_length recordfunc(key='midline_length', func=<function midline_length @ 0x24b92f8>) 

it has func attribute, original function, , key attribute.

if added same dictionary, can in decorator:

record_parsers = {}  def record(key):     def wrapped(func):         record_parsers[key] = func         return func     return wrapped  @record('midline_length') def midline_length(blob):     return 42 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -