Posted By

Twain on 10/28/07


Tagged

python magic


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

arcturus
vkolev


Magical self update


 / 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())

  1. def selfupdate(onlyargs=False, exclude=[]):
  2. """Call in any method to set instance attributes from local variables.
  3.  
  4. @param onlyargs: If True, use only named arguments and not locals
  5.  
  6. @param exclude: Names of other variables to exclude.
  7.  
  8. @note: First argument to the caller is taken to be the "self" to update
  9.  
  10. @note: Equivalent to 'vars(self).update(vars()); del self.self'
  11. """
  12. import inspect
  13. # Get caller frame (must be disposed of!)
  14. cf = inspect.currentframe().f_back
  15. try:
  16. # Instance is first argument to the caller
  17. instance = cf.f_locals[cf.f_code.co_varnames[0]]
  18. # Get names of variables to use
  19. if onlyargs:
  20. varnames = cf.f_code.co_varnames[1:cf.f_code.co_argcount]
  21. else:
  22. varnames = cf.f_code.co_varnames[1:]
  23. # Update instance with those names
  24. for var in varnames:
  25. if var not in exclude:
  26. setattr(instance, var, cf.f_locals[var])
  27. finally:
  28. del cf
  29.  
  30.  
  31. def testSelfUpdate(self):
  32. """For utils.selfupdate()"""
  33. class X:
  34. a = 1
  35. def __init__(s, a, b):
  36. c = 3
  37. selfupdate()
  38. x = X(2,4)
  39. self.assertEqual(x.a,2)
  40. self.assertEqual(x.b,4)
  41. self.assertEqual(x.c,3)
  42.  
  43.  
  44. def update(instance, variables, exclude=['self']):
  45. """Update instance attributes
  46.  
  47. For example, C{update(self, locals())},
  48. which is less magical than L{selfupdate}.
  49.  
  50. @param instance: Instance to update via setattr()
  51. @param variables: Dictionary of variables
  52. @param exclude: Variables to exclude, defaults to ['self']
  53. """
  54. for k, v in variables.iteritems():
  55. if k not in exclude:
  56. setattr(instance, k, v)

Report this snippet  

You need to login to post a comment.