Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Enum schema strategy #57

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions genson/schema/strategies/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
)
from .array import List, Tuple
from .object import Object
from .enum import Enum

BASIC_SCHEMA_STRATEGIES = (
Null,
Expand All @@ -33,5 +34,6 @@
'Tuple',
'Object',
'Typeless',
'Enum',
'BASIC_SCHEMA_STRATEGIES'
)
35 changes: 35 additions & 0 deletions genson/schema/strategies/enum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from .base import SchemaStrategy


class Enum(SchemaStrategy):
"""
strategy for 'enum' schemas. Merges the 'enum' types into one set and then
returns a schema with 'enum' set to the corresponding list.
"""
KEYWORDS = ('enum', )

def __init__(self, node_class):
super().__init__(node_class)
# Use set to easily merge 'enum's from different schemas.
self._enum = set()

@staticmethod
def match_schema(schema):
return 'enum' in schema

@classmethod
def match_object(cls, obj):
return False

def add_schema(self, schema):
super().add_schema(schema)
if self._enum == set():
self._enum = set(schema.get('enum'))
elif 'enum' in schema:
self._enum.update(schema['enum'])

def to_schema(self):
schema = super().to_schema()
# Revert set back to list
schema['enum'] = list(self._enum)
return schema