Skip to content

Commit

Permalink
Do not map ClassVar attributes (#1936)
Browse files Browse the repository at this point in the history
* Do not map ClassVar attributes

Fixes #1927

* document ClassVar usage

(cherry picked from commit 47a7a06)
  • Loading branch information
miguelgrinberg authored and github-actions[bot] committed Nov 6, 2024
1 parent 93656d0 commit 913e8aa
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 4 deletions.
12 changes: 12 additions & 0 deletions docs/persistence.rst
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,18 @@ field needs to be referenced, such as when specifying sort options in a
When specifying sorting order, the ``+`` and ``-`` unary operators can be used
on the class field attributes to indicate ascending and descending order.

Finally, the ``ClassVar`` annotation can be used to define a regular class
attribute that should not be mapped to the Elasticsearch index::

.. code:: python
from typing import ClassVar
class MyDoc(Document):
title: M[str]
created_at: M[datetime] = mapped_field(default_factory=datetime.now)
my_var: ClassVar[str] # regular class variable, ignored by Elasticsearch
Note on dates
~~~~~~~~~~~~~

Expand Down
15 changes: 13 additions & 2 deletions elasticsearch_dsl/document_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generic,
List,
Expand Down Expand Up @@ -159,7 +160,10 @@ def __init__(self, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any]):
# field8: M[str] = mapped_field(MyCustomText(), default="foo")
#
# # legacy format without Python typing
# field8 = Text()
# field9 = Text()
#
# # ignore attributes
# field10: ClassVar[string] = "a regular class variable"
annotations = attrs.get("__annotations__", {})
fields = set([n for n in attrs if isinstance(attrs[n], Field)])
fields.update(annotations.keys())
Expand All @@ -172,10 +176,14 @@ def __init__(self, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any]):
# the field has a type annotation, so next we try to figure out
# what field type we can use
type_ = annotations[name]
skip = False
required = True
multi = False
while hasattr(type_, "__origin__"):
if type_.__origin__ == Mapped:
if type_.__origin__ == ClassVar:
skip = True
break
elif type_.__origin__ == Mapped:
# M[type] -> extract the wrapped type
type_ = type_.__args__[0]
elif type_.__origin__ == Union:
Expand All @@ -192,6 +200,9 @@ def __init__(self, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any]):
type_ = type_.__args__[0]
else:
break
if skip or type_ == ClassVar:
# skip ClassVar attributes
continue
field = None
field_args: List[Any] = []
field_kwargs: Dict[str, Any] = {}
Expand Down
10 changes: 9 additions & 1 deletion tests/_async/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import pickle
from datetime import datetime
from hashlib import md5
from typing import Any, Dict, List, Optional
from typing import Any, ClassVar, Dict, List, Optional

import pytest
from pytest import raises
Expand Down Expand Up @@ -675,6 +675,8 @@ class TypedDoc(AsyncDocument):
s4: M[Optional[Secret]] = mapped_field(
SecretField(), default_factory=lambda: "foo"
)
i1: ClassVar
i2: ClassVar[int]

props = TypedDoc._doc_type.mapping.to_dict()["properties"]
assert props == {
Expand Down Expand Up @@ -708,6 +710,9 @@ class TypedDoc(AsyncDocument):
"s4": {"type": "text"},
}

TypedDoc.i1 = "foo"
TypedDoc.i2 = 123

doc = TypedDoc()
assert doc.k3 == "foo"
assert doc.s4 == "foo"
Expand All @@ -723,6 +728,9 @@ class TypedDoc(AsyncDocument):
"s3",
}

assert TypedDoc.i1 == "foo"
assert TypedDoc.i2 == 123

doc.st = "s"
doc.li = [1, 2, 3]
doc.k1 = "k1"
Expand Down
10 changes: 9 additions & 1 deletion tests/_sync/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import pickle
from datetime import datetime
from hashlib import md5
from typing import Any, Dict, List, Optional
from typing import Any, ClassVar, Dict, List, Optional

import pytest
from pytest import raises
Expand Down Expand Up @@ -675,6 +675,8 @@ class TypedDoc(Document):
s4: M[Optional[Secret]] = mapped_field(
SecretField(), default_factory=lambda: "foo"
)
i1: ClassVar
i2: ClassVar[int]

props = TypedDoc._doc_type.mapping.to_dict()["properties"]
assert props == {
Expand Down Expand Up @@ -708,6 +710,9 @@ class TypedDoc(Document):
"s4": {"type": "text"},
}

TypedDoc.i1 = "foo"
TypedDoc.i2 = 123

doc = TypedDoc()
assert doc.k3 == "foo"
assert doc.s4 == "foo"
Expand All @@ -723,6 +728,9 @@ class TypedDoc(Document):
"s3",
}

assert TypedDoc.i1 == "foo"
assert TypedDoc.i2 == 123

doc.st = "s"
doc.li = [1, 2, 3]
doc.k1 = "k1"
Expand Down

0 comments on commit 913e8aa

Please sign in to comment.