Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # What we know *can* work potentially
- POSSIBLE_COERCIONS = {"int" : ("float", "complex", "str"),
- "float" : ("complex", "str"),
- "complex" : ("str"),
- "str" : ("int", "float", "complex"),
- }
- CAST_MAP = {"int" : int, "float" : float, "complex" : complex, "str" : str}
- def acceptable_types(var):
- """
- Given a varaiable:
- - Return None if type is not a simple primitive as defined above, OR
- - Return acceptable tuple of simple types valid for this var.
- """
- vtype = type(var).__name__
- # Everything can be coerced to itself.
- valid_coercions = [vtype]
- coercion_details = [" ({}) '{}'".format(vtype, var)]
- coercions = POSSIBLE_COERCIONS.get(vtype, None)
- if coercions:
- # We have a valid primitive
- for coercion in coercions:
- # Test each one to see if it's possible.
- try:
- newvar = CAST_MAP[coercion](var)
- coercion_details.append(" ({}) '{}'".format(coercion, newvar))
- valid_coercions.append(coercion)
- except (ValueError, TypeError):
- # That cast/coercion failed, move along.
- pass
- return valid_coercions, coercion_details
- # If we get here, it was not a primitive.
- return None, []
- def suss_out_strings(string, coercions):
- """
- Given a string, do a few tests to see if it's a numeric type really.
- Return "most likely" type"
- """
- if type(string).__name__ != "str":
- return None
- # It's _already_ a string, so we don't need to test that.
- coercions.remove("str")
- for coercion in coercions:
- if str(CAST_MAP[coercion](string)) == string:
- return coercion
- # If we fall through it's likely it's just a string
- return "str"
- def main():
- test_cases = ["1", "4.5", "0", "k", "3j", "000345000", 3, 5, 60.7, { "i" : "j" }]
- for var in test_cases:
- tlist, details = acceptable_types(var)
- likely = suss_out_strings(var, tlist)
- if likely:
- print("{} => LIKELY {} {}".format(var, likely, tlist))
- else:
- print("{} => {}".format(var, tlist))
- print("\n".join(details))
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment