Skip to content

Commit 89bfdc8

Browse files
basic type annotation support
1 parent 412708e commit 89bfdc8

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

elasticsearch_dsl/document_base.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@
1515
# specific language governing permissions and limitations
1616
# under the License.
1717

18+
from datetime import date, datetime
1819
from fnmatch import fnmatch
1920

2021
from .exceptions import ValidationException
21-
from .field import Field
22+
from .field import Field, Integer, Float, Boolean, Text, Binary, Date
2223
from .mapping import Mapping
2324
from .utils import DOC_META_FIELDS, ObjectBase
2425

@@ -36,12 +37,30 @@ def __new__(cls, name, bases, attrs):
3637

3738

3839
class DocumentOptions:
40+
type_annotation_map = {
41+
int: (Integer, {}),
42+
float: (Float, {}),
43+
bool: (Boolean, {}),
44+
str: (Text, {}),
45+
bytes: (Binary, {}),
46+
datetime: (Date, {}),
47+
date: (Date, {"format": "yyyy-MM-dd"}),
48+
}
49+
3950
def __init__(self, name, bases, attrs):
4051
meta = attrs.pop("Meta", None)
4152

4253
# create the mapping instance
4354
self.mapping = getattr(meta, "mapping", Mapping())
4455

56+
for name, type_ in attrs.get('__annotations__', {}).items():
57+
if name not in attrs:
58+
if type_ in self.type_annotation_map:
59+
field, field_args = self.type_annotation_map[type_]
60+
self.mapping.field(name, field(**field_args))
61+
elif issubclass(type_, Field):
62+
self.mapping.field(name, type_())
63+
4564
# register all declared fields into the mapping
4665
for name, value in list(attrs.items()):
4766
if isinstance(value, Field):

0 commit comments

Comments
 (0)