Skip to content

Commit

Permalink
fix formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Kamil Rybacki committed Jul 15, 2024
1 parent 5903cc8 commit d94d0cf
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 91 deletions.
1 change: 1 addition & 0 deletions src/components/markdown/CodeSnippet.astro
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ const preProcessedRawCode = preProcessCode(code);
if (index === codeLines.length - 1) {
line.classList.add('opacity-25')
}
line.classList.add(...['lg:text-sm', 'text-xs']);
foundLinesIndex++;
});

Expand Down
182 changes: 91 additions & 91 deletions src/content/articles/reflections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -760,28 +760,28 @@ clean model instances.

<CodeSnippet
code={`
class Manager:
_schemas: dict[str, SchemaInstancesFactory] = {}
__instance: typing.ClassVar[Manager | None] = None
class Manager:
_schemas: dict[str, SchemaInstancesFactory] = {}
__instance: typing.ClassVar[Manager | None] = None
def validate(self, data: dict, schema: str) -> ValidationResults:
return self.get_factory(schema).validate(data)
def validate(self, data: dict, schema: str) -> ValidationResults:
return self.get_factory(schema).validate(data)
@classmethod
def start(cls) -> Manager:
# Discover and save the available schemas in the class attribute (_schemas)
# IMPORTANT: Initialize the Manager and keep its instance in the class attribute (__instance)
# This will let us use the Manager as a singleton
@classmethod
def start(cls) -> Manager:
# Discover and save the available schemas in the class attribute (_schemas)
# IMPORTANT: Initialize the Manager and keep its instance in the class attribute (__instance)
# This will let us use the Manager as a singleton
def get_factory(self, name: str) -> SchemaInstancesFactory:
# Return the transpiled model from _schemas cache
def get_factory(self, name: str) -> SchemaInstancesFactory:
# Return the transpiled model from _schemas cache
def get_available_schemas(self, path: str = '') -> dict[str, SchemaInstancesFactory]:
# Check out the directory containing the schemas, transpile each one
# and return the dictionary of the transpiled models
def get_available_schemas(self, path: str = '') -> dict[str, SchemaInstancesFactory]:
# Check out the directory containing the schemas, transpile each one
# and return the dictionary of the transpiled models
def load_schema(self, schema: SchemaInputFile) -> str:
# A way to manually shove the schema into the manager via YAML input file
def load_schema(self, schema: SchemaInputFile) -> str:
# A way to manually shove the schema into the manager via YAML input file
`}
language="python"
filename="manager.py"
Expand Down Expand Up @@ -849,82 +849,82 @@ arguments that can be passed to the `create_model` function from Pydantic API.

<CodeSnippet
code={`
class TranspiledSchema(pydantic.BaseModel):
transpilation_name: typing.ClassVar[str] = ''
global_validator: typing.ClassVar[
typing.Callable[[TranspiledSchema, typing.Any], None] | None
] = None
context: typing.ClassVar[
dict[str, typing.Any]
] = {}
_validation_errors: typing.ClassVar[
list[FieldValidationErrorInfo]
] = []
parent: typing.ClassVar[type[TranspiledSchema]]
@property
def validation_errors(self) -> list[FieldValidationErrorInfo]:
return self.parent._validation_errors
@classmethod
def compile(cls, model_data: TranspiledModelData) -> type[TranspiledSchema]:
if not model_data.get('parent'):
cls._validation_errors = []
schema: type[TranspiledSchema] = pydantic.create_model( # type: ignore
model_data['name'],
__base__=TranspiledSchema,
__validators__={
validator['name']: validator['method']
for validator in model_data['validators']
if validator
},
**model_data['properties']
)
schema.parent = model_data.get('parent') or copy.deepcopy(cls)
cls._rename_schema(schema, model_data['name'])
schema.context = model_data.get('context', {}) # type: ignore
schema.global_validator = model_data.get('global_validator')
return schema
@classmethod
def _rename_schema(cls, schema: type[TranspiledSchema], name: str) -> None:
for field in ['__name__', '__qualname__', 'transpilation_name']:
if hasattr(schema, field):
setattr(schema, field, name)
def __init__(self, **data: typing.Any) -> None: # type: ignore
__tracebackhide__ = True
if self.parent.transpilation_name == self.transpilation_name:
self.parent._validation_errors = []
collected_errors: list[FieldValidationErrorInfo] = []
try:
if self.global_validator:
self.global_validator(data) # type: ignore
except Exception as validator_exception: # pylint: disable=broad-except
collected_errors.append(
FieldValidationErrorInfo(
name=self.__class__.__name__,
message=str(validator_exception)
)
class TranspiledSchema(pydantic.BaseModel):
transpilation_name: typing.ClassVar[str] = ''
global_validator: typing.ClassVar[
typing.Callable[[TranspiledSchema, typing.Any], None] | None
] = None
context: typing.ClassVar[
dict[str, typing.Any]
] = {}
_validation_errors: typing.ClassVar[
list[FieldValidationErrorInfo]
] = []
parent: typing.ClassVar[type[TranspiledSchema]]
@property
def validation_errors(self) -> list[FieldValidationErrorInfo]:
return self.parent._validation_errors
@classmethod
def compile(cls, model_data: TranspiledModelData) -> type[TranspiledSchema]:
if not model_data.get('parent'):
cls._validation_errors = []
schema: type[TranspiledSchema] = pydantic.create_model( # type: ignore
model_data['name'],
__base__=TranspiledSchema,
__validators__={
validator['name']: validator['method']
for validator in model_data['validators']
if validator
},
**model_data['properties']
)
schema.parent = model_data.get('parent') or copy.deepcopy(cls)
cls._rename_schema(schema, model_data['name'])
schema.context = model_data.get('context', {}) # type: ignore
schema.global_validator = model_data.get('global_validator')
return schema
@classmethod
def _rename_schema(cls, schema: type[TranspiledSchema], name: str) -> None:
for field in ['__name__', '__qualname__', 'transpilation_name']:
if hasattr(schema, field):
setattr(schema, field, name)
def __init__(self, **data: typing.Any) -> None: # type: ignore
__tracebackhide__ = True
if self.parent.transpilation_name == self.transpilation_name:
self.parent._validation_errors = []
collected_errors: list[FieldValidationErrorInfo] = []
try:
if self.global_validator:
self.global_validator(data) # type: ignore
except Exception as validator_exception: # pylint: disable=broad-except
collected_errors.append(
FieldValidationErrorInfo(
name=self.__class__.__name__,
message=str(validator_exception)
)
try:
self.__pydantic_validator__.validate_python(
data,
self_instance=self,
context=self.context
)
try:
self.__pydantic_validator__.validate_python(
data,
self_instance=self,
context=self.context
)
except pydantic.ValidationError as validation_error:
collected_errors.extend([
FieldValidationErrorInfo(
name=str(error['loc'][0]) if error['loc'] else validation_error.title,
message=error['msg']
)
except pydantic.ValidationError as validation_error:
collected_errors.extend([
FieldValidationErrorInfo(
name=str(error['loc'][0]) if error['loc'] else validation_error.title,
message=error['msg']
)
for error in validation_error.errors()
])
self.parent._validation_errors += self._validation_errors + collected_errors
for error in validation_error.errors()
])
self.parent._validation_errors += self._validation_errors + collected_errors
`}
language="python"
filename="schema.py"
Expand Down

0 comments on commit d94d0cf

Please sign in to comment.