Guest User

type generation

a guest
Feb 14th, 2012
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.36 KB | None | 0 0
  1.  
  2. # This implements new type generation facilities
  3. # For instance, we can do Array(Int, Int, Int), immediately creating a type that consists of length 3 lists of int
  4. # This can then inherit additional functionalities:
  5.  
  6. # class WithFunctionalities(Array(Int,Int,Int)):
  7. # def extra_func(self,...):
  8. # pass
  9.  
  10. # In addition, it automatically acquires a __init__ function, that ensures type conversions.
  11.  
  12. # In fact, we can also do Array(f1,f2,f3), which gives a class as well, but that is callable
  13. # Array(f1,f2,f3)([arg1,arg2,arg3]) gives [f1(arg1),f2(arg2),f3(arg3)]
  14. # This is useful for type conversions on whole json records
  15.  
  16. # Similar functionalities exist for Dict, and can be combined recursively.
  17.  
  18. # author: Paul-Olivier Dehaye
  19.  
  20. def ImmutableExtensionFactory(t, t_name):
  21. # I will need to add other methods to int, str and float, so I need to have a way to subclass them.
  22. # Have already used that for testing.
  23. class ImmutableExtensionClass(t):
  24. @staticmethod
  25. def __new__(cls, x):
  26. return super(ImmutableExtensionClass, cls).__new__(cls, x)
  27.  
  28. return ImmutableExtensionClass
  29.  
  30. Int = ImmutableExtensionFactory(int, "Int")
  31. Str = String = ImmutableExtensionFactory(str, "Str")
  32. Float = ImmutableExtensionFactory(float, "Float")
  33.  
  34. Anything = lambda x: x
  35.  
  36. id = lambda x: x
  37.  
  38. def Array(*f, **kwargs):
  39. # Cases:
  40. # Array(f, n=3)
  41. # Array(f)
  42. # Array(id, n=3)
  43.  
  44. # Use initOneFunction
  45. # Cases:
  46. # Array(f1,f2,f3)
  47. # Redundant: Array(f1,f2,f3,n=3)
  48. # Bad: Array(f1,f2,f3, n = 4)
  49.  
  50. # Use initMultipleFunctions
  51. class SmartArray(list):
  52. pass
  53.  
  54. def initOneFunction(self, x, n = kwargs.get("n")):
  55. tmp = (map(f[0], x[:n]))
  56. list.__init__(self, tmp)
  57.  
  58. def initMultipleFunctions(self, x):
  59. tmp = map(lambda ff,xx:ff(xx), f, x)
  60. list.__init__(self, tmp)
  61.  
  62. if len(f) == 1:
  63. setattr(SmartArray, "__init__", (initOneFunction))
  64. else:
  65. try:
  66. n = kwargs.get("n")
  67. assert len(f) == n or n == None
  68. setattr(SmartArray, "__init__", (initMultipleFunctions))
  69.  
  70. except AssertionError:
  71. raise Exception("Bad definition of a fixed length array")
  72. return SmartArray
  73.  
  74. def Dict(*f, **kwargs):
  75. # Cases:
  76. # Dict(f) Not allowed (or syntax would be confusing)
  77. # Use instead Dict(Str, g)
  78. # Not valid JSON, but should be handled: Dict(f,g)
  79.  
  80. # Use ConstantValueTypes
  81.  
  82. # Cases:
  83. # Dict({key1 : f1, key2 : f2, ...})
  84.  
  85. # Use VariableValueTypes
  86.  
  87. class SmartDict(dict):
  88. pass
  89.  
  90. def initConstantValueTypes(self, x):
  91. tmp = dict([((f[0])(k), (f[1])(v)) for (k,v) in x.items()])
  92. dict.__init__(self, tmp)
  93.  
  94. def initVariableValueTypes(self, x):
  95. tmp = dict([(k,(f[0][k])(v)) for (k,v) in x.items()])
  96. dict.__init__(self, tmp)
  97.  
  98. if len(f) == 2:
  99. setattr(SmartDict, "__init__", initConstantValueTypes)
  100. elif len(f) == 1:
  101. assert isinstance(f[0], dict)
  102. setattr(SmartDict, "__init__", initVariableValueTypes)
  103. else:
  104. raise Exception("Bad definition of a SmartDict")
  105. return SmartDict
  106.  
  107. def ExecDict(d):
  108. return d.__get_item_
Advertisement
Add Comment
Please, Sign In to add comment