code_junkie

Python dictionary from an object's fields

Nov 10th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. >>> class Foo:
  2. ... bar = 'hello'
  3. ... baz = 'world'
  4. ...
  5. >>> f = Foo()
  6. >>> props(f)
  7. { 'bar' : 'hello', 'baz' : 'world' }
  8.  
  9. __dict__
  10.  
  11. dir
  12.  
  13. dir
  14.  
  15. >>> class Foo(object):
  16. ... bar = 'hello'
  17. ... baz = 'world'
  18. ...
  19. >>> f = Foo()
  20. >>> [name for name in dir(f) if not name.startswith('__')]
  21. [ 'bar', 'baz' ]
  22. >>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
  23. { 'bar': 'hello', 'baz': 'world' }
  24.  
  25. import inspect
  26.  
  27. def props(obj):
  28. pr = {}
  29. for name in dir(obj):
  30. value = getattr(obj, name)
  31. if not.name.startswith('__') and not inspect.ismethod(value):
  32. pr[name] = value
  33. return pr
  34.  
  35. dict((key, value) for key, value in f.__dict__.iteritems()
  36. if not callable(value) and not key.startswith('__'))
  37.  
  38. class c(object):
  39. x = 3
  40. a = c()
Add Comment
Please, Sign In to add comment