We Recommend

Learning Python Learning Python
The authors of Learning Python show you enough essentials of the Python scripting language to enable you to begin solving problems right away, then reveal more powerful aspects of the language one at a time. This approach is sure to appeal to programmers and system administrators who have urgent problems and a preference for learning by semi-guided experimentation.


Posted By

Twain on 10/28/07


Tagged


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

arcturus


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.