-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsimple.py
More file actions
83 lines (67 loc) · 2.36 KB
/
simple.py
File metadata and controls
83 lines (67 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Convert simple type from dictionary to the column equivalent."""
import datetime
from ... import exceptions
from ... import types as oa_types
from ...helpers import peek, custom_python_types
from .. import types
def convert(
value: types.TOptSimpleDict, *, schema: oa_types.Schema
) -> types.TOptSimpleCol:
"""
Convert simple value from a dictionary to the column equivalent.
Raises InvalidInstanceError if the value is not of the type implied by the schema.
Args:
value: The value to convert.
schema: The schema for the value.
Returns:
The value converted for a column.
"""
type_ = peek.type_(schema=schema, schemas={})
if value is None:
return None
if type_ == "integer":
if not isinstance(value, int):
raise exceptions.InvalidInstanceError(
"Integer type columns must have int values."
)
return value
if type_ == "number":
if not isinstance(value, (float, int)):
raise exceptions.InvalidInstanceError(
"Number type columns must have float values."
)
return value
if type_ == "string":
return _handle_string(value, schema=schema)
if type_ == "boolean":
if not isinstance(value, bool):
raise exceptions.InvalidInstanceError(
"Boolean type columns must have bool values."
)
return value
raise exceptions.FeatureNotImplementedError(f"Type {type_} is not supported.")
def _handle_string(
value: types.TSimpleDict, *, schema: oa_types.Schema
) -> types.TStringCol:
"""
Convert string type value to column type.
Raises InvalidInstanceError if the value is not of the type implied by the schema.
Args:
value: The value to convert.
Returns:
The converted value.
"""
if not isinstance(value, str):
raise exceptions.InvalidInstanceError(
"String type columns must have str values."
)
format_ = peek.format_(schema=schema, schemas={})
if format_ == "date":
return datetime.date.fromisoformat(value)
if format_ == "date-time":
return datetime.datetime.fromisoformat(value)
if format_ == "duration":
return custom_python_types.duration.fromisoformat(value)
if format_ == "binary":
return value.encode()
return value