Guest User

Untitled

a guest
Mar 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # What we know *can* work potentially
  4. POSSIBLE_COERCIONS = {"int" : ("float", "complex", "str"),
  5. "float" : ("complex", "str"),
  6. "complex" : ("str"),
  7. "str" : ("int", "float", "complex"),
  8. }
  9.  
  10. CAST_MAP = {"int" : int, "float" : float, "complex" : complex, "str" : str}
  11.  
  12.  
  13. def acceptable_types(var):
  14. """
  15. Given a varaiable:
  16.  
  17. - Return None if type is not a simple primitive as defined above, OR
  18. - Return acceptable tuple of simple types valid for this var.
  19. """
  20.  
  21. vtype = type(var).__name__
  22. # Everything can be coerced to itself.
  23. valid_coercions = [vtype]
  24. coercion_details = [" ({}) '{}'".format(vtype, var)]
  25.  
  26. coercions = POSSIBLE_COERCIONS.get(vtype, None)
  27. if coercions:
  28. # We have a valid primitive
  29. for coercion in coercions:
  30. # Test each one to see if it's possible.
  31. try:
  32. newvar = CAST_MAP[coercion](var)
  33. coercion_details.append(" ({}) '{}'".format(coercion, newvar))
  34. valid_coercions.append(coercion)
  35. except (ValueError, TypeError):
  36. # That cast/coercion failed, move along.
  37. pass
  38.  
  39. return valid_coercions, coercion_details
  40.  
  41. # If we get here, it was not a primitive.
  42. return None, []
  43.  
  44.  
  45. def suss_out_strings(string, coercions):
  46. """
  47. Given a string, do a few tests to see if it's a numeric type really.
  48. Return "most likely" type"
  49. """
  50. if type(string).__name__ != "str":
  51. return None
  52. # It's _already_ a string, so we don't need to test that.
  53. coercions.remove("str")
  54.  
  55. for coercion in coercions:
  56. if str(CAST_MAP[coercion](string)) == string:
  57. return coercion
  58.  
  59. # If we fall through it's likely it's just a string
  60. return "str"
  61.  
  62.  
  63.  
  64.  
  65. def main():
  66. test_cases = ["1", "4.5", "0", "k", "3j", "000345000", 3, 5, 60.7, { "i" : "j" }]
  67. for var in test_cases:
  68. tlist, details = acceptable_types(var)
  69. likely = suss_out_strings(var, tlist)
  70. if likely:
  71. print("{} => LIKELY {} {}".format(var, likely, tlist))
  72. else:
  73. print("{} => {}".format(var, tlist))
  74. print("\n".join(details))
  75.  
  76.  
  77. if __name__ == "__main__":
  78. main()
Add Comment
Please, Sign In to add comment