Published in: Python
Just call "selfupdate()" in a method and all local variables are magically assigned to self (except for "self", of course). Less magical is update(self, locals())
def selfupdate(onlyargs=False, exclude=[]): """Call in any method to set instance attributes from local variables. @param onlyargs: If True, use only named arguments and not locals @param exclude: Names of other variables to exclude. @note: First argument to the caller is taken to be the "self" to update @note: Equivalent to 'vars(self).update(vars()); del self.self' """ import inspect # Get caller frame (must be disposed of!) cf = inspect.currentframe().f_back try: # Instance is first argument to the caller instance = cf.f_locals[cf.f_code.co_varnames[0]] # Get names of variables to use if onlyargs: varnames = cf.f_code.co_varnames[1:cf.f_code.co_argcount] else: varnames = cf.f_code.co_varnames[1:] # Update instance with those names for var in varnames: if var not in exclude: setattr(instance, var, cf.f_locals[var]) finally: del cf def testSelfUpdate(self): """For utils.selfupdate()""" class X: a = 1 def __init__(s, a, b): c = 3 selfupdate() x = X(2,4) self.assertEqual(x.a,2) self.assertEqual(x.b,4) self.assertEqual(x.c,3) def update(instance, variables, exclude=['self']): """Update instance attributes For example, C{update(self, locals())}, which is less magical than L{selfupdate}. @param instance: Instance to update via setattr() @param variables: Dictionary of variables @param exclude: Variables to exclude, defaults to ['self'] """ for k, v in variables.iteritems(): if k not in exclude: setattr(instance, k, v)
You need to login to post a comment.
