code_junkie

List all the classes that currently exist

Nov 13th, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. {
  2. "type": "Person",
  3. "firstName": "John",
  4. "lastName": "Smith",
  5. "address": {
  6. "streetAddress": "21 2nd Street",
  7. "city": "New York",
  8. "state": "NY",
  9. "postalCode": 10021
  10. },
  11. "phoneNumbers": [
  12. "212 555-1234",
  13. "646 555-4567"
  14. ]
  15. }
  16.  
  17. if not json_object.has_key('type'):
  18. raise TypeError('JSON stream is missing a "type" attribute.')
  19.  
  20. ##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY ####
  21. # create a type definition and add attributes to it
  22. definition = type(json_object['type'], (object,), {})
  23. for key in json_object.keys():
  24. setattr(definition, key, None)
  25.  
  26. # instantiate and populate a test object
  27. tester = definition()
  28. for key, value in json_object.iteritems():
  29. setattr(tester, key, value)
  30.  
  31. import types
  32. listOfClasses = [cls for cls in globals().values() if type(cls) == types.ClassType]
  33.  
  34. json_types = {}
  35. def get_json_type(name):
  36. try:
  37. return json_types[name]
  38. except KeyError:
  39. json_types[name] = t = type(json_object['type'], (object,), {})
  40. # any further initialization of t here
  41. return t
  42.  
  43. definition = get_json_type(json_object['type'])
  44. tester = definition()
  45. # or: tester = get_json_type(json_object['type'])()
  46.  
  47. json_types = globals()
  48.  
  49. Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17)
  50. [GCC 4.3.2] on linux2
  51. Type "help", "copyright", "credits" or "license" for more information.
  52. >>> dir()
  53. ['__builtins__', '__doc__', '__name__']
  54. >>> class Foo:
  55. ... pass
  56. ...
  57. >>> dir()
  58. ['Foo', '__builtins__', '__doc__', '__name__']
  59. >>> type(eval('Foo'))
  60. <type 'classobj'>
Add Comment
Please, Sign In to add comment