Repository: s-knibbs/dataclasses-jsonschema (2019-07-11 ~ 2019-08-05)

problem_statement: Base classes may only be used by one derived class
If I create a base class with some common fields I can create a subclass and it works, but if I create more than one subclass from the same base class the validation fails.

I added `tests/test_inheritance.py`
```
from dataclasses import dataclass
from dataclasses_jsonschema import JsonSchemaMixin


def test_inheritance():
    @dataclass
    class Base(JsonSchemaMixin):
        base: str

    @dataclass
    class Derived1(Base):
        derived1: str

    @dataclass
    class Derived2(Base):
        derived2: str

    data1 = {"derived1": "d", "base": "b"}
    d = Derived1.from_dict(data1)
    assert d.to_dict() == data1

    data2 = {"derived2": "d", "base": "b"}
    d = Derived2.from_dict(data2)
    assert d.to_dict() == data2
```
Expected output: the test should pass.
Actual output:
```
GLOB sdist-make: /Users/duncan.booth/github/dataclasses-jsonschema/setup.py
py37 inst-nodeps: /Users/duncan.booth/github/dataclasses-jsonschema/.tox/.tmp/package/1/dataclasses-jsonschema-2.6.2.dev0+ge79e8e1.d20190712.zip
py37 installed: apispec==2.0.2,apispec-webframeworks==0.4.0,atomicwrites==1.3.0,attrs==19.1.0,Click==7.0,dataclasses-jsonschema==2.6.2.dev0+ge79e8e1.d20190712,entrypoints==0.3,flake8==3.7.8,Flask==1.1.1,importlib-metadata==0.18,itsdangerous==1.1.0,Jinja2==2.10.1,jsonschema==3.0.1,MarkupSafe==1.1.1,mccabe==0.6.1,more-itertools==7.1.0,mypy==0.711,mypy-extensions==0.4.1,packaging==19.0,pluggy==0.12.0,py==1.8.0,pycodestyle==2.5.0,pyflakes==2.1.1,pyparsing==2.4.0,pyrsistent==0.15.3,pytest==5.0.1,pytest-ordering==0.6,python-dateutil==2.8.0,PyYAML==5.1.1,six==1.12.0,typed-ast==1.4.0,typing-extensions==3.7.4,wcwidth==0.1.7,Werkzeug==0.15.4,zipp==0.5.2
py37 run-test-pre: PYTHONHASHSEED='2578755219'
py37 run-test: commands[0] | pytest tests
==================================================================== test session starts =====================================================================
platform darwin -- Python 3.7.2, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
cachedir: .tox/py37/.pytest_cache
rootdir: /Users/duncan.booth/github/dataclasses-jsonschema
plugins: ordering-0.6
collected 28 items                                                                                                                                           

tests/test_core.py ..........................                                                                                                          [ 92%]
tests/test_inheritance.py F                                                                                                                            [ 96%]
tests/test_apispec_plugin.py .                                                                                                                         [100%]

========================================================================== FAILURES ==========================================================================
______________________________________________________________________ test_inheritance ______________________________________________________________________

self = <jsonschema.validators.RefResolver object at 0x107a187b8>
document = {'$schema': 'http://json-schema.org/draft-06/schema#', 'allOf': [{'$ref': '#/definitions/Base'}, {'properties': {'deri...{'type': 'string'}}, 'required': ['derived1'], 'type': 'object'}], 'description': 'Derived1(base: str, derived1: str)'}
fragment = 'definitions/Base'

    def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.
    
        Arguments:
    
            document:
    
                The referent document
    
            fragment (str):
    
                a URI fragment to resolve within it
        """
    
        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []
    
        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")
    
            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
>               document = document[part]
E               KeyError: 'definitions'

.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:776: KeyError

During handling of the above exception, another exception occurred:

    def test_inheritance():
        @dataclass
        class Base(JsonSchemaMixin):
            base: str
    
        @dataclass
        class Derived1(Base):
            derived1: str
    
        @dataclass
        class Derived2(Base):
            derived2: str
    
        data1 = {"derived1": "d", "base": "b"}
        d = Derived1.from_dict(data1)
        assert d.to_dict() == data1
    
        data2 = {"derived2": "d", "base": "b"}
>       d = Derived2.from_dict(data2)

tests/test_inheritance.py:24: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
dataclasses_jsonschema/__init__.py:396: in from_dict
    cls._validate(data)
dataclasses_jsonschema/__init__.py:383: in _validate
    validate_func(data, cls.json_schema())
.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:897: in validate
    error = exceptions.best_match(validator.iter_errors(instance))
.tox/py37/lib/python3.7/site-packages/jsonschema/exceptions.py:293: in best_match
    best = next(errors, None)
.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:323: in iter_errors
    for error in errors:
.tox/py37/lib/python3.7/site-packages/jsonschema/_validators.py:303: in allOf
    for error in validator.descend(instance, subschema, schema_path=index):
.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:339: in descend
    for error in self.iter_errors(instance, schema):
.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:323: in iter_errors
    for error in errors:
.tox/py37/lib/python3.7/site-packages/jsonschema/_validators.py:247: in ref
    scope, resolved = validator.resolver.resolve(ref)
.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:734: in resolve
    return url, self._remote_cache(url)
.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:746: in resolve_from_url
    return self.resolve_fragment(document, fragment)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <jsonschema.validators.RefResolver object at 0x107a187b8>
document = {'$schema': 'http://json-schema.org/draft-06/schema#', 'allOf': [{'$ref': '#/definitions/Base'}, {'properties': {'deri...{'type': 'string'}}, 'required': ['derived1'], 'type': 'object'}], 'description': 'Derived1(base: str, derived1: str)'}
fragment = 'definitions/Base'

    def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.
    
        Arguments:
    
            document:
    
                The referent document
    
            fragment (str):
    
                a URI fragment to resolve within it
        """
    
        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []
    
        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")
    
            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise exceptions.RefResolutionError(
>                   "Unresolvable JSON pointer: %r" % fragment
                )
E               jsonschema.exceptions.RefResolutionError: Unresolvable JSON pointer: 'definitions/Base'

.tox/py37/lib/python3.7/site-packages/jsonschema/validators.py:779: RefResolutionError
====================================================================== warnings summary ======================================================================
.tox/py37/lib/python3.7/site-packages/jinja2/utils.py:485
  /Users/duncan.booth/github/dataclasses-jsonschema/.tox/py37/lib/python3.7/site-packages/jinja2/utils.py:485: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
    from collections import MutableMapping

.tox/py37/lib/python3.7/site-packages/jinja2/runtime.py:318
  /Users/duncan.booth/github/dataclasses-jsonschema/.tox/py37/lib/python3.7/site-packages/jinja2/runtime.py:318: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
    from collections import Mapping

.tox/py37/lib/python3.7/site-packages/_pytest/mark/structures.py:332
  /Users/duncan.booth/github/dataclasses-jsonschema/.tox/py37/lib/python3.7/site-packages/_pytest/mark/structures.py:332: PytestUnknownMarkWarning: Unknown pytest.mark.last - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/latest/mark.html
    PytestUnknownMarkWarning,

-- Docs: https://docs.pytest.org/en/latest/warnings.html
====================================================== 1 failed, 27 passed, 3 warnings in 0.42 seconds =======================================================
ERROR: InvocationError for command /Users/duncan.booth/github/dataclasses-jsonschema/.tox/py37/bin/pytest tests (exited with code 1)
__________________________________________________________________________ summary ___________________________________________________________________________
ERROR:   py37: commands failed
```

The code fails when attempting to do `Derived2.from_dict(...)` but only if we have previously called `Derived1.from_dict(...)`. Whichever order I try to validate the data the first one succeeds and the second one fails.

The problem appears to be that the JsonSchemaMixin fields _schema, _compiled_schema and so on are shared between all classes in the same hierarchy. If I change the code so that `Base` no longer inherits from `JsonSchemaMixin` the two derived classes no longer share the mixin's attributes and everything works.
date: 2019-07-11
patch: diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index 290b1a1..92bbf2e 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -172,13 +172,22 @@ class JsonSchemaMixin:
     }
 
     # Cache of the generated schema
-    _schema: Optional[Dict[SchemaType, JsonDict]] = None
-    _compiled_schema: Optional[Dict[SchemaType, Callable]] = None
-    _definitions: Optional[Dict[SchemaType, JsonDict]] = None
+    _schema: Dict[SchemaType, JsonDict]
+    _compiled_schema: Dict[SchemaType, Callable]
+    _definitions: Dict[SchemaType, JsonDict]
     # Cache of field encode / decode functions
-    _encode_cache: Optional[Dict[Any, _ValueEncoder]] = None
-    _decode_cache: Optional[Dict[Any, _ValueDecoder]] = None
-    _mapped_fields: Optional[List[Tuple[Field, str]]] = None
+    _encode_cache: Dict[Any, _ValueEncoder]
+    _decode_cache: Dict[Any, _ValueDecoder]
+    _mapped_fields: List[Tuple[Field, str]]
+
+    def __init_subclass__(cls):
+        # Initialise caches
+        cls._schema = {}
+        cls._compiled_schema = {}
+        cls._definitions = {}
+        cls._encode_cache = {}
+        cls._decode_cache = {}
+        cls._mapped_fields = []
 
     @classmethod
     def field_mapping(cls) -> Dict[str, str]:
@@ -206,9 +215,6 @@ class JsonSchemaMixin:
         try:
             encoder = cls._encode_cache[field_type]  # type: ignore
         except (KeyError, TypeError):
-            if cls._encode_cache is None:
-                cls._encode_cache = {}
-
             # TODO: Use field_type.__origin__ instead of the type name.
             # This has different behaviour between 3.6 & 3.7 however
             field_type_name = cls._get_field_type_name(field_type)
@@ -283,7 +289,7 @@ class JsonSchemaMixin:
         if not base_fields:
             return _get_fields_uncached()
 
-        if cls._mapped_fields is None:
+        if not cls._mapped_fields:
             cls._mapped_fields = _get_fields_uncached()
         return cls._mapped_fields  # type: ignore
 
@@ -312,8 +318,6 @@ class JsonSchemaMixin:
         try:
             decoder = cls._decode_cache[field_type]  # type: ignore
         except (KeyError, TypeError):
-            if cls._decode_cache is None:
-                cls._decode_cache = {}
             # Note: Only literal types composed of primitive values are currently supported
             if type(value) in JSON_ENCODABLE_TYPES and (field_type in JSON_ENCODABLE_TYPES or is_literal(field_type)):
                 return value
@@ -371,8 +375,6 @@ class JsonSchemaMixin:
     def _validate(cls, data: JsonDict):
         try:
             if fast_validation:
-                if cls._compiled_schema is None:
-                    cls._compiled_schema = {}
                 # TODO: Support validating with other schema types
                 schema_validator = cls._compiled_schema.get(DEFAULT_SCHEMA_TYPE)
                 if schema_validator is None:
@@ -617,9 +619,7 @@ class JsonSchemaMixin:
             return cls.all_json_schemas(schema_type)
 
         definitions: JsonDict = {}
-        if cls._definitions is None:
-            cls._definitions = {schema_type: definitions}
-        elif schema_type not in cls._definitions:
+        if schema_type not in cls._definitions:
             cls._definitions[schema_type] = definitions
         else:
             definitions = cls._definitions[schema_type]
@@ -661,9 +661,6 @@ class JsonSchemaMixin:
             if cls.__doc__:
                 schema['description'] = cls.__doc__
 
-            if cls._schema is None:
-                cls._schema = {}
-
             cls._schema[schema_type] = schema
 
         if embeddable:

test_patch: diff --git a/tests/test_core.py b/tests/test_core.py
index 4e6e817..977660a 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -505,7 +505,12 @@ def test_inherited_schema():
         """A cat"""
         hunting_skill: str
 
-    expected_schema = compose_schema({
+    @dataclass
+    class Dog(Pet):
+        """A dog"""
+        breed: str
+
+    expected_cat_schema = compose_schema({
         "description": "A cat",
         "allOf": [
             {"$ref": "#/definitions/Pet"},
@@ -523,7 +528,26 @@ def test_inherited_schema():
             "required": ["name"]
         }
     })
-    assert Cat.json_schema() == expected_schema
+    expected_dog_schema = compose_schema({
+        "description": "A dog",
+        "allOf": [
+            {"$ref": "#/definitions/Pet"},
+            {
+                "type": "object",
+                "properties": {"breed": {"type": "string"}},
+                "required": ["breed"]
+            },
+        ]
+    }, {
+        "Pet": {
+            "description": "A generic pet",
+            "type": "object",
+            "properties": {"name": {"type": "string"}},
+            "required": ["name"]
+        }
+    })
+    assert Cat.json_schema() == expected_cat_schema
+    assert Dog.json_schema() == expected_dog_schema
 
 
 def test_optional_union():


----

problem_statement: Improve handling of enum fields in `from_object`
We should automatically convert enum fields from the source field by calling the enum constructor.

The enum constructor accepts both enums and enum values.
date: 2019-07-12
patch: diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index 92bbf2e..3c01cc8 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -409,7 +409,7 @@ class JsonSchemaMixin:
         return instance
 
     @classmethod
-    def from_object(cls: Type[T], obj: Any, exclude: FieldExcludeList = tuple()):
+    def from_object(cls: Type[T], obj: Any, exclude: FieldExcludeList = tuple()) -> T:
         """Returns a dataclass instance from another object (typically an ORM model).
         The `exclude` parameter is a tuple of field names or (field.name, nested_exclude)
         to exclude from the conversion. For example `exclude=('artist_name', ('albums', ('tracks',))` will exclude
@@ -434,6 +434,8 @@ class JsonSchemaMixin:
             field_type_name = cls._get_field_type_name(ft)
             if cls._is_json_schema_subclass(ft):
                 values[field.name] = ft.from_object(getattr(obj, field.name), exclude=sub_exclude)
+            elif is_enum(ft):
+                values[field.name] = ft(getattr(obj, field.name))
             elif field_type_name == "List" and cls._is_json_schema_subclass(ft.__args__[0]):
                 values[field.name] = [
                     ft.__args__[0].from_object(v, exclude=sub_exclude) for v in getattr(obj, field.name)

test_patch: diff --git a/tests/test_core.py b/tests/test_core.py
index 977660a..55cd03b 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,5 +1,7 @@
 import datetime
 from _decimal import Decimal
+from enum import Enum
+
 from dataclasses import dataclass, field
 from ipaddress import IPv4Address, IPv6Address
 from typing import List, NewType, Optional, Union
@@ -453,6 +455,11 @@ def test_literal_types():
 
 def test_from_object():
 
+    class Genre(Enum):
+        HORROR = "horror"
+        BIOGRAPHY = "biography"
+        THRILLER = "thriller"
+
     class AuthorModel:
 
         def __init__(self, name, age, books):
@@ -462,15 +469,17 @@ def test_from_object():
 
     class BookModel:
 
-        def __init__(self, name, first_print, publisher):
+        def __init__(self, name, first_print, publisher, genre):
             self.name = name
             self.first_print = first_print
             self.publisher = publisher
+            self.genre = genre
 
     @dataclass
     class Book(JsonSchemaMixin):
         name: str
         publisher: str
+        genre: Genre
         first_print: Optional[datetime.datetime] = None
 
     @dataclass
@@ -479,8 +488,10 @@ def test_from_object():
         age: Optional[int] = None
         books: Optional[List[Book]] = None
 
-    sample_author = AuthorModel("Joe Bloggs", 32, [BookModel("Hello World!", datetime.datetime.utcnow(), "ACME Corp")])
-    expected_author = Author("Joe Bloggs", books=[Book("Hello World!", "ACME Corp")])
+    sample_author = AuthorModel(
+        "Joe Bloggs", 32, [BookModel("Hello World!", datetime.datetime.utcnow(), "ACME Corp", "biography")]
+    )
+    expected_author = Author("Joe Bloggs", books=[Book("Hello World!", "ACME Corp", Genre.BIOGRAPHY)])
     assert Author.from_object(sample_author, exclude=('age', ('books', ('first_print',)))) == expected_author
 
     with pytest.raises(ValueError):


----

problem_statement: Change private fields from _ to __
Hi!
I'm trying to declare a class member with name
_id
as the mongodb index field of the class but the library exclude fields name with _

Would be nice to have an option to change that to another prefix like __
Thanks

Edit:
the private prefix is hardcoded here:
https://github.com/s-knibbs/dataclasses-jsonschema/blob/22aaa09d09e7d6a37e75cccb2100b824dd200bb0/dataclasses_jsonschema/__init__.py#L282
Should be as easy as define a member (_priv_prefix?) for JsonSchemaMixin?
date: 2019-08-05
patch: diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index 3c01cc8..46ea060 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -172,22 +172,22 @@ class JsonSchemaMixin:
     }
 
     # Cache of the generated schema
-    _schema: Dict[SchemaType, JsonDict]
-    _compiled_schema: Dict[SchemaType, Callable]
-    _definitions: Dict[SchemaType, JsonDict]
+    __schema: Dict[SchemaType, JsonDict]
+    __compiled_schema: Dict[SchemaType, Callable]
+    __definitions: Dict[SchemaType, JsonDict]
     # Cache of field encode / decode functions
-    _encode_cache: Dict[Any, _ValueEncoder]
-    _decode_cache: Dict[Any, _ValueDecoder]
-    _mapped_fields: List[Tuple[Field, str]]
+    __encode_cache: Dict[Any, _ValueEncoder]
+    __decode_cache: Dict[Any, _ValueDecoder]
+    __mapped_fields: List[Tuple[Field, str]]
 
     def __init_subclass__(cls):
         # Initialise caches
-        cls._schema = {}
-        cls._compiled_schema = {}
-        cls._definitions = {}
-        cls._encode_cache = {}
-        cls._decode_cache = {}
-        cls._mapped_fields = []
+        cls.__schema = {}
+        cls.__compiled_schema = {}
+        cls.__definitions = {}
+        cls.__encode_cache = {}
+        cls.__decode_cache = {}
+        cls.__mapped_fields = []
 
     @classmethod
     def field_mapping(cls) -> Dict[str, str]:
@@ -213,7 +213,7 @@ class JsonSchemaMixin:
         if value is None or value is NULL:
             return value
         try:
-            encoder = cls._encode_cache[field_type]  # type: ignore
+            encoder = cls.__encode_cache[field_type]  # type: ignore
         except (KeyError, TypeError):
             # TODO: Use field_type.__origin__ instead of the type name.
             # This has different behaviour between 3.6 & 3.7 however
@@ -261,7 +261,7 @@ class JsonSchemaMixin:
                     return cls._encode_field(ft.__supertype__, v, o)
             else:
                 def encoder(_, v, __): return v
-            cls._encode_cache[field_type] = encoder  # type: ignore
+            cls.__encode_cache[field_type] = encoder  # type: ignore
         return encoder(field_type, value, omit_none)
 
     @classmethod
@@ -279,7 +279,7 @@ class JsonSchemaMixin:
             type_hints = get_type_hints(cls)
             for f in fields(cls):
                 # Skip internal fields
-                if f.name.startswith("_") or (not base_fields and f.name in base_field_names):
+                if f.name.startswith("__") or (not base_fields and f.name in base_field_names):
                     continue
                 # Note fields() doesn't resolve forward refs
                 f.type = type_hints[f.name]
@@ -289,9 +289,9 @@ class JsonSchemaMixin:
         if not base_fields:
             return _get_fields_uncached()
 
-        if not cls._mapped_fields:
-            cls._mapped_fields = _get_fields_uncached()
-        return cls._mapped_fields  # type: ignore
+        if not cls.__mapped_fields:
+            cls.__mapped_fields = _get_fields_uncached()
+        return cls.__mapped_fields  # type: ignore
 
     def to_dict(self, omit_none: bool = True, validate: bool = False) -> JsonDict:
         """Converts the dataclass instance to a JSON encodable dict, with optional JSON schema validation.
@@ -316,7 +316,7 @@ class JsonSchemaMixin:
             return NULL if is_nullable(field_type) else None
         decoder = None
         try:
-            decoder = cls._decode_cache[field_type]  # type: ignore
+            decoder = cls.__decode_cache[field_type]  # type: ignore
         except (KeyError, TypeError):
             # Note: Only literal types composed of primitive values are currently supported
             if type(value) in JSON_ENCODABLE_TYPES and (field_type in JSON_ENCODABLE_TYPES or is_literal(field_type)):
@@ -368,7 +368,7 @@ class JsonSchemaMixin:
             if decoder is None:
                 warnings.warn(f"Unable to decode value for '{field}: {field_type_name}'")
                 return value
-            cls._decode_cache[field_type] = decoder
+            cls.__decode_cache[field_type] = decoder
         return decoder(field, field_type, value)
 
     @classmethod
@@ -376,10 +376,10 @@ class JsonSchemaMixin:
         try:
             if fast_validation:
                 # TODO: Support validating with other schema types
-                schema_validator = cls._compiled_schema.get(DEFAULT_SCHEMA_TYPE)
+                schema_validator = cls.__compiled_schema.get(DEFAULT_SCHEMA_TYPE)
                 if schema_validator is None:
                     schema_validator = fastjsonschema.compile(cls.json_schema())
-                    cls._compiled_schema[DEFAULT_SCHEMA_TYPE] = schema_validator
+                    cls.__compiled_schema[DEFAULT_SCHEMA_TYPE] = schema_validator
                 schema_validator(data)
             else:
                 validate_func(data, cls.json_schema())
@@ -621,17 +621,17 @@ class JsonSchemaMixin:
             return cls.all_json_schemas(schema_type)
 
         definitions: JsonDict = {}
-        if schema_type not in cls._definitions:
-            cls._definitions[schema_type] = definitions
+        if schema_type not in cls.__definitions:
+            cls.__definitions[schema_type] = definitions
         else:
-            definitions = cls._definitions[schema_type]
+            definitions = cls.__definitions[schema_type]
 
         if schema_type in (SchemaType.SWAGGER_V3, SchemaType.SWAGGER_V2) and not embeddable:
             schema_type = SchemaType.DRAFT_06
             warnings.warn("'Swagger schema types unsupported when 'embeddable=False', using 'SchemaType.DRAFT_06'")
 
-        if cls._schema is not None and schema_type in cls._schema:
-            schema = cls._schema[schema_type]
+        if cls.__schema is not None and schema_type in cls.__schema:
+            schema = cls.__schema[schema_type]
         else:
             properties = {}
             required = []
@@ -663,7 +663,7 @@ class JsonSchemaMixin:
             if cls.__doc__:
                 schema['description'] = cls.__doc__
 
-            cls._schema[schema_type] = schema
+            cls.__schema[schema_type] = schema
 
         if embeddable:
             return {**definitions, cls.__name__: schema}

test_patch: diff --git a/tests/test_core.py b/tests/test_core.py
index 55cd03b..bad6b27 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -611,3 +611,26 @@ def test_nullable_field():
     expected_dict = {"name": "Joe Bloggs", "manager": None}
     assert Employee.from_dict(expected_dict) == expected_obj
     assert expected_dict == expected_obj.to_dict()
+
+
+def test_underscore_fields():
+    @dataclass
+    class Album(JsonSchemaMixin):
+        """An album"""
+        _id: int
+        name: str
+
+    expected_json_schema = compose_schema({
+        "type": "object",
+        "description": "An album",
+        "properties": {
+            "name": {"type": "string"},
+            "_id": {"type": "integer"}
+        },
+        "required": ["_id", "name"]
+    })
+    assert Album.json_schema() == expected_json_schema
+    expected_data = {"name": "Foo", "_id": 5}
+    expected_obj = Album(_id=5, name="Foo")
+    assert expected_data == expected_obj.to_dict()
+    assert expected_obj == Album.from_dict(expected_data)