Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. import ast
  2.  
  3. class AnyOf(list):
  4. pass
  5.  
  6. class ObjectSchema(dict):
  7. pass
  8.  
  9. def is_valid(schema, obj):
  10. if isinstance(schema, ObjectSchema):
  11. if not isinstance(obj, schema.get("type", object)):
  12. return False
  13. for key, value in schema.items():
  14. if key == "type": continue
  15. if not (hasattr(obj, key) and is_valid(value, getattr(obj, key))):
  16. return False
  17. return True
  18. elif isinstance(schema, AnyOf):
  19. return any(is_valid(item, obj) for item in schema)
  20. elif isinstance(schema, list):
  21. return isinstance(obj, list) and (is_valid(item_schema, item) for item_schema, item in zip(schema, obj))
  22. elif isinstance(schema, str):
  23. return schema == obj
  24. else:
  25. raise Exception(f"Not implemented yet for schema {repr(schema)} of type {type(schema)}")
  26.  
  27. valid_values = [
  28. "df.isna()",
  29. "df.notna()",
  30. "df.str.contains(ANY_STRING_LITERAL, na=False)"
  31. ]
  32.  
  33. schema = ObjectSchema(
  34. type=ast.Expression,
  35. body=ObjectSchema(
  36. type=ast.Call,
  37. args = [],
  38. keywords = [],
  39. func = ObjectSchema(
  40. type=ast.Attribute,
  41. value = ObjectSchema(
  42. type=ast.Name,
  43. id="df"
  44. ),
  45. attr=AnyOf(["isna", "notna"])
  46. )
  47. )
  48. )
  49.  
  50. test_cases = [
  51. "df.isna()",
  52. "df.notna()",
  53. "df.str.contains(ANY_STRING_LITERAL, na=False)"
  54. ]
  55.  
  56. for i, s in enumerate(test_cases, 1):
  57. print(f"Test case {i}: {repr(s)}")
  58. node = ast.parse(s, mode="eval")
  59. print(f" valid: {is_valid(schema, node)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement