> built 2026-10-13 15:45 UTC from 902b466 (master) · ju 0.1.41. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# ju

JSON schema Utils

To install:	`pip install ju`

[Documentation](https://i2mint.github.io/ju/)

# Examples

## JSON Schema

You have tools to extract JSON schema information from python objects, as well as
to create python objects from them.

```none
>>> from ju import signature_to_json_schema, json_schema_to_signature
>>>
>>>
>>> def earth(north: str, south: bool, east: int = 1, west: float = 2.0):
...     """Earth docs"""
...     return f'{north=}, {south=}, {east=}, {west=}'
...
>>> schema = signature_to_json_schema(earth)
>>> assert schema == {
...     'description': 'Earth docs',
...     'title': 'earth',
...     'type': 'object',
...     'properties': {
...         'north': {'type': 'string'},
...         'south': {'type': 'boolean'},
...         'east': {'type': 'integer', 'default': 1},
...         'west': {'type': 'number', 'default': 2.0},
...     },
...     'required': ['north', 'south'],
... }
>>>
>>> sig = json_schema_to_signature(schema)
>>> sig
<Sig (north: str, south: bool, east: int = 1, west: float = 2.0)>
>>> sig.name
'earth'
>>> sig.docs
'Earth docs'
```

## React JSON Schema Form (rjsf)

You can get a [react-jsonschema-form (rjsf)](https://github.com/rjsf-team/react-jsonschema-form)
specification
(see the [rjsf playground](https://rjsf-team.github.io/react-jsonschema-form/))
from a python function.

```none
>>> def foo(
    ...     a_bool: bool,
    ...     a_float=3.14,
    ...     an_int=2,
    ...     a_str: str = 'hello',
    ...     something_else=None
    ... ):
    ...     '''A Foo function'''
    >>>
    >>> form_spec = func_to_form_spec(foo)
    >>> assert form_spec == {
    ...     'rjsf': {
    ...         'schema': {
    ...             'title': 'foo',
    ...             'type': 'object',
    ...             'properties': {
    ...                 'a_bool': {'type': 'boolean'},
    ...                 'a_float': {'type': 'number', 'default': 3.14},
    ...                 'an_int': {'type': 'integer', 'default': 2},
    ...                 'a_str': {'type': 'string', 'default': 'hello'},
    ...                 'something_else': {'type': 'string', 'default': None}
    ...             },
    ...             'required': ['a_bool'],
    ...             'description': 'A Foo function'
    ...         },
    ...         'uiSchema': {
    ...             'ui:submitButtonOptions': {
    ...                 'submitText': 'Run'
    ...             },
    ...             'a_bool': {'ui:autofocus': True}
    ...         },
    ...         'liveValidate': False,
    ...         'disabled': False,
    ...         'readonly': False,
    ...         'omitExtraData': False,
    ...         'liveOmit': False,
    ...         'noValidate': False,
    ...         'noHtml5Validate': False,
    ...         'focusOnFirstError': False,
    ...         'showErrorList': 'top'
    ...     }
    ... }
```

## OpenAPI Routes

Represents a collection of routes in an OpenAPI specification.

Each instance of this class contains a list of `Route` objects, which can be accessed and manipulated as needed.

```none
>>> from yaml import safe_load
>>> spec_yaml = '''
... openapi: 3.0.3
... paths:
...   /items:
...     get:
...       summary: List items
...       responses:
...         '200':
...           description: An array of items
...     post:
...       summary: Create item
...       responses:
...         '201':
...           description: Item created
... '''
>>> spec = safe_load(spec_yaml)
>>> routes = Routes(spec)
>>> len(routes)
2
>>> list(routes)
[('get', '/items'), ('post', '/items')]
>>> r = routes['get', '/items']
>>> r
Route(method='get', endpoint='/items')
>>> r.method_data
{'summary': 'List items', 'responses': {'200': {'description': 'An array of items'}}}
```

## pydantic utils

The `ju.pydantic_util` module provides comprehensive tools for working with Pydantic models and JSON schemas.

### Creating Models from Data and Schemas

Generate Pydantic models dynamically from data or JSON schemas:

```python
from ju.pydantic_util import data_to_pydantic_model, schema_to_pydantic_model

# Create model from data dictionary
data = {"name": "Alice", "age": 30, "address": {"city": "NYC", "zip": "10001"}}
UserModel = data_to_pydantic_model(data, "User")

# Create model from JSON schema
schema = {
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "price": {"type": "number"}
    }
}
ProductModel = schema_to_pydantic_model(schema)
```

### Model Validation and Selection

Check data validity and find matching models:

```python
from ju.pydantic_util import is_valid_wrt_model, valid_models

# Check if data is valid for a specific model
is_valid = is_valid_wrt_model({"name": "Bob", "age": 25}, UserModel)

# Find all models that validate given data
models = [UserModel, ProductModel, AdminModel]
matching = list(valid_models(data, models))
```

### Code Generation with Transformations

Convert models and schemas to Python code with optional transformations:

```python
from ju.pydantic_util import pydantic_model_to_code

# Generate code from model
code = pydantic_model_to_code(UserModel)

# Apply transformations during generation
def fix_field_names(schema):
    # Transform problematic field names
    if 'properties' in schema:
        for old_name, new_name in [('class_', 'class_name'), ('type_', 'type_name')]:
            if old_name in schema['properties']:
                schema['properties'][new_name] = schema['properties'].pop(old_name)
    return schema

code = pydantic_model_to_code(
    source_schema, 
    ingress_transform=fix_field_names,
    egress_transform=lambda code: f"# Auto-generated\n{code}"
)
```

### Model Introspection and Data Extraction

Extract structured information about models and use them as data extraction templates:

```python
from ju.pydantic_util import (
    field_paths_and_annotations, 
    model_field_descriptions,
    ModelExtractor
)

# Get flattened field paths and types
paths = field_paths_and_annotations(UserModel)
# {'name': str, 'age': int, 'address.city': str, 'address.zip': str}

# Extract field descriptions
descriptions = model_field_descriptions(UserModel)

# Use models as data extraction templates
extractor = ModelExtractor([UserModel, AdminModel])
data_reader = extractor(json_data)  # Returns mapping with model-based paths
values = data_reader['address.city']  # Extract nested values easily
```

The module handles complex scenarios like nested models, generic types, collections, and provides flexible validation and transformation capabilities.

<p class="epythet-aggregates">This documentation as a single file: <a href="ju.md">ju.md</a> (Markdown, for agents).</p>


# _autosummary/ju.html.md

# ju

JSON schema Utils

### Modules

| [`json_schema`](_autosummary/ju.json_schema.html.md#module-ju.json_schema)       | This module provides tools to transform Python functions to JSON schemas.   |
|------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`oas`](_autosummary/ju.oas.html.md#module-ju.oas)                       | OpenAPI specification tools.                                                |
| [`pydantic_util`](_autosummary/ju.pydantic_util.html.md#module-ju.pydantic_util)   | Tools for working with Pydantic models.                                     |
| [`rjsf`](_autosummary/ju.rjsf.html.md#module-ju.rjsf)                     | Tools for React-JSONSchema-Form (RJSF)                                      |
| [`traitlets_util`](_autosummary/ju.traitlets_util.html.md#module-ju.traitlets_util) | Utils for traitlets                                                         |
| [`util`](_autosummary/ju.util.html.md#module-ju.util)                     | Ju base utils.                                                              |
| [`viz`](_autosummary/ju.viz.html.md#module-ju.viz)                       | Visualization functions for Ju.                                             |


# _autosummary/ju.json_schema.html.md

# ju.json_schema

This module provides tools to transform Python functions to JSON schemas.

The main function in this module is `signature_to_json_schema`, which takes a
Python function as input and returns a JSON schema that can be used to generate
a form in a React application.

Example usage:

```pycon
>>> def mercury(sweet: float, sour=True):
...     '''Near the sun'''
...     return sweet * sour
>>>
>>> assert signature_to_json_schema(mercury) == {
...         'title': 'mercury',
...         'type': 'object',
...         'properties': {
...             'sweet': {'type': 'number'},
...             'sour': {'type': 'boolean', 'default': True}},
...          'required': ['sweet'],
...          'description': 'Near the sun'
... }
```

### Module Attributes

| [`OAS_NAME_KEY`](_autosummary/ju.json_schema.html.md#ju.json_schema.OAS_NAME_KEY)   | Keys of a `properties` entry that stand for an OpenAPI parameter or body property whose own name was taken by another (`id` in the query and in a header): the entry is keyed by a distinct name, and these record the spec's name and place.   |
|-----------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### Functions

| [`function_to_json_schema`](_autosummary/ju.json_schema.html.md#ju.json_schema.function_to_json_schema)(func, \*[, doc, ...])    | Transforms a Python function to a JSON schema.                                                                                                                                                                          |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`get_properties`](_autosummary/ju.json_schema.html.md#ju.json_schema.get_properties)(parameters, \*[, ...])            | Returns the properties dict for the JSON schema.                                                                                                                                                                        |
| `get_required`(properties)                                                                        |                                                                                                                                                                                                                         |
| [`json_schema_to_signature`](_autosummary/ju.json_schema.html.md#ju.json_schema.json_schema_to_signature)(json_schema, \*[, ...]) | Transforms a JSON schema or OpenAPI parameters list to a Python function signature.                                                                                                                                     |
| [`merge_with_defaults`](_autosummary/ju.json_schema.html.md#ju.json_schema.merge_with_defaults)(defaults, overwrites)        | Returns a new dictionary that combines two dictionaries by using the keys and order from the first dictionary (defaults) and overwriting its values with those from the second dictionary (overwrites) when they exist. |
| `parametrized_param_to_type`(param, \*[, ...])                                                    |                                                                                                                                                                                                                         |
| `print_dict`(d)                                                                                   |                                                                                                                                                                                                                         |
| `print_schema`([func_key, store])                                                                 |                                                                                                                                                                                                                         |
| `pydantic_model_to_type_mapping`(pydantic_model)                                                  |                                                                                                                                                                                                                         |
| [`pyname_to_title`](_autosummary/ju.json_schema.html.md#ju.json_schema.pyname_to_title)(pyname)                          | Converts a Python name to a title.                                                                                                                                                                                      |
| [`schema_param_names`](_autosummary/ju.json_schema.html.md#ju.json_schema.schema_param_names)(json_schema, \*[, ...])       | Map the Python parameter names `json_schema_to_signature` gives to the original names in the schema (the SSOT for the renaming, so callers can build requests with the original names).                                 |
| [`signature_to_json_schema`](_autosummary/ju.json_schema.html.md#ju.json_schema.signature_to_json_schema)(func, \*[, doc, ...])   | Transforms a Python function to a JSON schema.                                                                                                                                                                          |
| [`title_to_pyname`](_autosummary/ju.json_schema.html.md#ju.json_schema.title_to_pyname)(title)                           | Converts a title to a Python name.                                                                                                                                                                                      |
| `wrap_schema_in_opus_spec`(schema)                                                                |                                                                                                                                                                                                                         |

### ju.json_schema.OAS_NAME_KEY *= 'x-oas-name'*

Keys of a `properties` entry that stand for an OpenAPI parameter or body property
whose own name was taken by another (`id` in the query and in a header): the
entry is keyed by a distinct name, and these record the spec’s name and place.

### ju.json_schema.function_to_json_schema(func, \*, doc=True, name_of_obj=functools.partial(<function name_of_obj>, default_factory=<function <lambda>>), pyname_to_title=<function asis>, param_to_prop_type=functools.partial(<function parametrized_param_to_type>, type_mapping=((<class 'str'>, 'string'), (<class 'bool'>, 'boolean'), (<class 'int'>, 'integer'), (<class 'float'>, 'number'), (<class 'collections.abc.Mapping'>, 'object'), (collections.abc.Sequence[str], 'array'), (<class 'bytes'>, 'string'), (<class 'bytearray'>, 'string'), (<class 'memoryview'>, 'string'), (<class 'collections.UserString'>, 'string'), (<class 'collections.abc.Sequence'>, 'array'))))

Transforms a Python function to a JSON schema.

param func: The function to transform
return: The JSON schema (as a dict) for the function

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

```pycon
>>> def mercury(sweet: float, sour=True):
...     '''Near the sun'''
...     return sweet * sour
>>>
>>> assert signature_to_json_schema(mercury) == {
...         'title': 'mercury',
...         'type': 'object',
...         'properties': {
...             'sweet': {'type': 'number'},
...             'sour': {'type': 'boolean', 'default': True}},
...          'required': ['sweet'],
...          'description': 'Near the sun'
... }
```

See [https://github.com/i2mint/i2//blob/f547257c272433b7651d09276afdfb1bb7b2f67b/misc/i2.routing.ipynb#L17](https://github.com/i2mint/i2//blob/f547257c272433b7651d09276afdfb1bb7b2f67b/misc/i2.routing.ipynb#L17).

### ju.json_schema.get_properties(parameters, \*, param_to_prop_type=functools.partial(<function parametrized_param_to_type>, type_mapping=((<class 'str'>, 'string'), (<class 'bool'>, 'boolean'), (<class 'int'>, 'integer'), (<class 'float'>, 'number'), (<class 'collections.abc.Mapping'>, 'object'), (collections.abc.Sequence[str], 'array'), (<class 'bytes'>, 'string'), (<class 'bytearray'>, 'string'), (<class 'memoryview'>, 'string'), (<class 'collections.UserString'>, 'string'), (<class 'collections.abc.Sequence'>, 'array'))))

Returns the properties dict for the JSON schema.

```pycon
>>> def foo(
...     a_bool: bool,
...     a_float=3.14,
...     an_int=2,
...     a_str: str = 'hello',
...     something_else=None
... ):
...     '''A Foo function'''
>>>
>>> from ju.json_schema import DFLT_PARAM_TO_TYPE
>>> parameters = inspect.signature(foo).parameters
>>> assert (
...     get_properties(parameters, param_to_prop_type=DFLT_PARAM_TO_TYPE)
...     == {
...         'a_bool': {'type': 'boolean'},
...         'a_float': {'type': 'number', 'default': 3.14},
...         'an_int': {'type': 'integer', 'default': 2},
...         'a_str': {'type': 'string', 'default': 'hello'},
...         'something_else': {'type': 'string', 'default': None}
...     }
... )
```

### ju.json_schema.json_schema_to_signature(json_schema, \*, type_mapper=(('string', <class 'str'>), ('boolean', <class 'bool'>), ('integer', <class 'int'>), ('number', <class 'float'>), ('object', <class 'collections.abc.Mapping'>), ('array', collections.abc.Sequence[str])), default_default=None, title_to_pyname=<function title_to_pyname>, default_annotation, default_description='')

Transforms a JSON schema or OpenAPI parameters list to a Python function signature.
Supports both JSON schema ‘properties’ and OpenAPI ‘parameters’.

Parameters named in the schema’s `required` list (or marked `required: true`,
for OpenAPI parameters) have no default. All others get their schema `default`
if they have one, else `default_default` (`None` unless you say otherwise;
pass `Parameter.empty` to make them required anyway). Required parameters come
first, optional ones after, each group keeping the schema’s order, so positional
calls bind required parameters in schema order.

A ‘properties’ schema with no `required` key at all keeps the legacy behavior
(only properties with their own `default` are optional, `default_default` is
not applied), so positional callers of such schemas are not re-bound. Say
`'required': []` to make everything optional. A malformed `required`
(not a list) raises `ValueError`.

```pycon
>>> schema = {'title': 'earth',
...  'type': 'object',
...  'properties': {'north': {'type': 'string'},
...   'south': {'type': 'boolean'},
...   'east': {'type': 'integer', 'default': 1},
...   'west': {'type': 'number', 'default': 2.0}},
...  'required': ['north', 'south'],
...  'description': 'Earth docs'}
>>> sig = json_schema_to_signature(schema)
>>> sig
<Sig (north: str, south: bool, east: int = 1, west: float = 2.0)>
>>> sig.name
'earth'
>>> sig.docs
'Earth docs'
```

# — OpenAPI parameters support —

```pycon
>>> openapi_params = {
...     'title': 'get_thing',
...     'parameters': [
...         {'name': 'thing_id', 'in': 'path', 'required': True, 'schema': {'type': 'string'}},
...         {'name': 'detail', 'in': 'query', 'required': False, 'schema': {'type': 'boolean', 'default': False}},
...         {'name': 'count', 'in': 'query', 'schema': {'type': 'integer', 'default': 1}},
...     ],
...     'description': 'Get a thing by ID.'
... }
>>> sig2 = json_schema_to_signature(openapi_params)
>>> sig2
<Sig (thing_id: str, detail: bool = False, count: int = 1)>
>>> sig2.name
'get_thing'
>>> sig2.docs
'Get a thing by ID.'
```

Properties not in `required` are optional (`default_default`, i.e. `None`,
unless they have their own default):

```pycon
>>> optional = {'properties': {'a': {'type': 'string'}, 'b': {'type': 'integer'}},
...             'required': ['b']}
>>> json_schema_to_signature(optional)
<Sig (b: int, a: str = None)>
>>> json_schema_to_signature(optional, default_default='')
<Sig (b: int, a: str = '')>
```

### ju.json_schema.merge_with_defaults(defaults, overwrites)

Returns a new dictionary that combines two dictionaries by using the keys
and order from the first dictionary (defaults) and overwriting its values
with those from the second dictionary (overwrites) when they exist.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### Parameters

- defaults (dict): The base dictionary containing default key-value pairs.
- overwrites (dict): The dictionary containing values to overwrite those in defaults.

### Returns

- dict: A merged dictionary with values from `overwrites` applied to `defaults`.

### Example

```pycon
>>> defaults = {'a': 1, 'b': 2, 'c': 3}
>>> overwrites = {'b': 4, 'c': 5, 'd': 6}  # note the extra key 'd', not in defaults
>>> merge_with_defaults(defaults, overwrites)
{'a': 1, 'b': 4, 'c': 5}
```

### ju.json_schema.pyname_to_title(pyname)

Converts a Python name to a title.

It does this by replacing underscores with spaces and capitalizing the first
letter of each word.
If the name contains camel case, it will be split into words.

A sort of (imperfect) inverse of `title_to_pyname`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### Example

```pycon
>>> pyname_to_title('hello_world')
'Hello World'
>>> pyname_to_title('helloWorld')
'Hello World'
```

### ju.json_schema.schema_param_names(json_schema, \*, title_to_pyname=<function title_to_pyname>)

Map the Python parameter names `json_schema_to_signature` gives to the original
names in the schema (the SSOT for the renaming, so callers can build requests
with the original names).

OpenAPI `parameters` names that already are valid identifiers are kept as is;
others (e.g. `X-MS-API-ROLE`) are sanitised with `title_to_pyname`. Names of
`properties` are always passed through `title_to_pyname`. Clashes get a
numeric suffix. A `properties` entry carrying `x-oas-name` (see `Route.params`)
maps to that name, not to its key.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

```pycon
>>> schema = {'parameters': [
...     {'name': 'X-MS-API-ROLE', 'in': 'header', 'schema': {'type': 'string'}},
...     {'name': 'thingId', 'in': 'path', 'required': True},
...     {'name': 'x_ms_api_role', 'in': 'query'}]}
>>> schema_param_names(schema)
{'x_ms_api_role': 'X-MS-API-ROLE', 'thingId': 'thingId', 'x_ms_api_role_2': 'x_ms_api_role'}
```

```pycon
>>> schema = {'properties': {'id': {}, 'id_header': {'x-oas-name': 'id'}}}
>>> schema_param_names(schema)
{'id': 'id', 'id_header': 'id'}
```

### ju.json_schema.signature_to_json_schema(func, \*, doc=True, name_of_obj=functools.partial(<function name_of_obj>, default_factory=<function <lambda>>), pyname_to_title=<function asis>, param_to_prop_type=functools.partial(<function parametrized_param_to_type>, type_mapping=((<class 'str'>, 'string'), (<class 'bool'>, 'boolean'), (<class 'int'>, 'integer'), (<class 'float'>, 'number'), (<class 'collections.abc.Mapping'>, 'object'), (collections.abc.Sequence[str], 'array'), (<class 'bytes'>, 'string'), (<class 'bytearray'>, 'string'), (<class 'memoryview'>, 'string'), (<class 'collections.UserString'>, 'string'), (<class 'collections.abc.Sequence'>, 'array'))))

Transforms a Python function to a JSON schema.

param func: The function to transform
return: The JSON schema (as a dict) for the function

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

```pycon
>>> def mercury(sweet: float, sour=True):
...     '''Near the sun'''
...     return sweet * sour
>>>
>>> assert signature_to_json_schema(mercury) == {
...         'title': 'mercury',
...         'type': 'object',
...         'properties': {
...             'sweet': {'type': 'number'},
...             'sour': {'type': 'boolean', 'default': True}},
...          'required': ['sweet'],
...          'description': 'Near the sun'
... }
```

See [https://github.com/i2mint/i2//blob/f547257c272433b7651d09276afdfb1bb7b2f67b/misc/i2.routing.ipynb#L17](https://github.com/i2mint/i2//blob/f547257c272433b7651d09276afdfb1bb7b2f67b/misc/i2.routing.ipynb#L17).

### ju.json_schema.title_to_pyname(title)

Converts a title to a Python name.

A sort of (imperfect) inverse of `pyname_to_title`.

It does this by replacing spaces with underscores and lowercasing the first
letter of each word.
If the title contains camel case, it will be split into words.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### Example

```pycon
>>> title_to_pyname('Hello World')
'hello_world'
>>> title_to_pyname('HelloWorld')
'hello_world'
>>> title_to_pyname('3: Hello World')
'_3_hello_world'
>>> title_to_pyname('   heL----lO  \n\t;; wo__rld')
'_he_l_l_o_wo__rld'
```


# _autosummary/ju.oas.html.md

# ju.oas

OpenAPI specification tools.

### Module Attributes

| [`BODY_MEDIA_TYPES`](_autosummary/ju.oas.html.md#ju.oas.BODY_MEDIA_TYPES)   | Non-JSON request body media types `Route.params` reads, in order of preference.    |
|---------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`BODY_IN`](_autosummary/ju.oas.html.md#ju.oas.BODY_IN)            | The `OAS_IN_KEY` of a property that comes from the request body.                   |
| [`PARAM_IN`](_autosummary/ju.oas.html.md#ju.oas.PARAM_IN)           | The `OAS_IN_KEY` of a parameter that does not say where it goes (invalid OpenAPI). |

### Functions

| [`add_property`](_autosummary/ju.oas.html.md#ju.oas.add_property)(schema, sent_as, spec_names, ...)   | Add the parameter or body property `name`, sent in `place`, to the object `schema`, keyed by its name; when that is taken (the same name in another place -- `id` in the query and in a header, a query `name` and a body `name`), by a distinct key.                                                                                                                                                                               |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `compare_modules_to_missing_funcs`()                                                              |                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `compare_modules_to_operationids`()                                                               |                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| [`default_func_namer`](_autosummary/ju.oas.html.md#ju.oas.default_func_namer)(method, path[, details, ...]) | Default function name generator for OpenAPI routes.                                                                                                                                                                                                                                                                                                                                                                                 |
| `default_get_response`(method, url, \*\*kwargs)                                                   |                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `default_response_egress`(method, uri)                                                            |                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| [`ensure_openapi_dict`](_autosummary/ju.oas.html.md#ju.oas.ensure_openapi_dict)(spec)                        | Ensure that the OpenAPI specification is a dictionary.                                                                                                                                                                                                                                                                                                                                                                              |
| [`generate_and_import_openapi_client`](_autosummary/ju.oas.html.md#ju.oas.generate_and_import_openapi_client)(openapi_spec) | openapi_spec: dict, or str (path to YAML/JSON file) output_dir: where to generate the client (default: temp dir) file_format: 'yaml' or 'json' (used if openapi_spec is a dict)                                                                                                                                                                                                                                                     |
| [`generate_openapi_client`](_autosummary/ju.oas.html.md#ju.oas.generate_openapi_client)(openapi_spec[, ...])     | openapi_spec: dict, or str (path to YAML/JSON file) output_dir: where to generate the client (default: temp dir) file_format: 'yaml' or 'json' (used if openapi_spec is a dict)                                                                                                                                                                                                                                                     |
| [`get_routes`](_autosummary/ju.oas.html.md#ju.oas.get_routes)(d[, include_methods])                 | Takes OpenAPI specification dict 'd' and returns the key-paths to all the endpoints.                                                                                                                                                                                                                                                                                                                                                |
| [`merge_parameters`](_autosummary/ju.oas.html.md#ju.oas.merge_parameters)(path_item_params, ...)          | The parameters of an operation: those its path item declares for all its operations, overridden (same name and `in`) or extended by its own.                                                                                                                                                                                                                                                                                        |
| [`merge_request_body_json_schema`](_autosummary/ju.oas.html.md#ju.oas.merge_request_body_json_schema)(details, ...)     | If the operation has a requestBody with a JSON schema, merge its properties and required fields into param_schema.                                                                                                                                                                                                                                                                                                                  |
| [`openapi_to_funcs`](_autosummary/ju.oas.html.md#ju.oas.openapi_to_funcs)(spec, \*[, base_url, ...])      | spec: dict or str (YAML/JSON string or file path) base_url: override the spec's server URL default_servers_url: default URL to use if no servers are specified in the spec get_response: function to get the response object (default: requests.request) response_egress: function (method, uri) -> callable to extract result from response Returns a generator yielding OpenApiFunc instances for each route in the OpenAPI spec. |
| [`openapi_to_generated_funcs`](_autosummary/ju.oas.html.md#ju.oas.openapi_to_generated_funcs)(spec, \*[, ...])      | Like openapi_to_funcs, but yields OpenApiFunc objects for each route, using the generated client for requests.                                                                                                                                                                                                                                                                                                                      |
| `print_generated_modules`()                                                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| [`properties_of_schema`](_autosummary/ju.oas.html.md#ju.oas.properties_of_schema)(schema)                     | Returns the properties of the given schema, encapsulating in ArrayOf to indicate that the schema is for an array of objects, and not just a single object.                                                                                                                                                                                                                                                                          |
| [`resolve_refs`](_autosummary/ju.oas.html.md#ju.oas.resolve_refs)(open_api_spec, d)                   | Recursively resolves all references in 'd' using 'open_api_spec'.                                                                                                                                                                                                                                                                                                                                                                   |
| `return_empty_dict_on_error`(e)                                                                   |                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| [`validate_openapi_to_generated_funcs_alignment`](_autosummary/ju.oas.html.md#ju.oas.validate_openapi_to_generated_funcs_alignment)()  | Example usage of openapi_to_generated_funcs.                                                                                                                                                                                                                                                                                                                                                                                        |

### Classes

| [`ArrayOf`](_autosummary/ju.oas.html.md#ju.oas.ArrayOf)                                            | A class that is simply meant to mark the fact that some properties dict really represents an array of objects, and not just a single object.   |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------|
| [`OpenApiFunc`](_autosummary/ju.oas.html.md#ju.oas.OpenApiFunc)(\*, method, uri, base_url, ...[, ...]) | Callable class for OpenAPI route functions, supporting introspection and pickling.                                                             |
| [`Route`](_autosummary/ju.oas.html.md#ju.oas.Route)(method, endpoint, spec[, type_mapping])      | Represents a route in an OpenAPI specification.                                                                                                |
| [`Routes`](_autosummary/ju.oas.html.md#ju.oas.Routes)(spec, \*[, type_mapping])                   | Represents a collection of routes in an OpenAPI specification.                                                                                 |

### *class* ju.oas.ArrayOf

Bases: [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

A class that is simply meant to mark the fact that some properties dict really
represents an array of objects, and not just a single object.

### ju.oas.BODY_IN *= 'body'*

The `OAS_IN_KEY` of a property that comes from the request body.

### ju.oas.BODY_MEDIA_TYPES *= ('application/x-www-form-urlencoded', 'multipart/form-data')*

Non-JSON request body media types `Route.params` reads, in order of preference.

### *class* ju.oas.OpenApiFunc(\*, method, uri, base_url, param_schema, get_response=<function default_get_response>, response_egress=None, name=None, qualname=None, doc=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Callable class for OpenAPI route functions, supporting introspection and pickling.

### ju.oas.PARAM_IN *= 'param'*

The `OAS_IN_KEY` of a parameter that does not say where it goes (invalid OpenAPI).

### *class* ju.oas.Route(method, endpoint, spec, type_mapping=(('array', <class 'list'>), ('integer', <class 'int'>), ('object', <class 'dict'>), ('string', <class 'str'>), ('boolean', <class 'bool'>), ('number', <class 'float'>)))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Represents a route in an OpenAPI specification.

Each route has a method (e.g., ‘get’, ‘post’), an endpoint (e.g., ‘/items’), and a spec, which is a dictionary
containing the details of the route as specified in the OpenAPI document.

The `type_mapping` attribute is a dictionary that maps OpenAPI types to corresponding Python types.

```pycon
>>> from yaml import safe_load
>>> spec_yaml = '''
... openapi: 3.0.3
... paths:
...   /items:
...     get:
...       summary: List items
...       parameters:
...         - in: query
...           name: type
...           schema:
...             type: string
...           required: true
...           description: Type of items to list
...       responses:
...         '200':
...           description: An array of items
... '''
>>> spec = safe_load(spec_yaml)
>>> route_get = Route('get', '/items', spec)
>>> route_get.method
'get'
>>> route_get.endpoint
'/items'
>>> route_get.method_data['summary']
'List items'
>>> route_get.params
{'type': 'object', 'properties': {'type': {'type': 'string'}}, 'required': ['type']}
```

#### *property* body_content_type

The media type of the request body `params` reads, or None for no body.

JSON is preferred; then form-urlencoded, then multipart.

```pycon
>>> from yaml import safe_load
>>> spec = safe_load('''
... paths:
...   /f:
...     post:
...       requestBody:
...         content:
...           multipart/form-data: {schema: {properties: {a: {type: string}}}}
... ''')
>>> route = Route('post', '/f', spec)
>>> route.body_content_type, list(route.params['properties'])
('multipart/form-data', ['a'])
```

#### *property* output_properties

Returns the schema for the response with the given status code.

#### *property* params

Combined parameters from parameters and requestBody
(it should usually just be one or the other, not both).
We’re calling this ‘params’ because that’s what FastAPI calls it.

### *class* ju.oas.Routes(spec, \*, type_mapping=(('array', <class 'list'>), ('integer', <class 'int'>), ('object', <class 'dict'>), ('string', <class 'str'>), ('boolean', <class 'bool'>), ('number', <class 'float'>)))

Bases: `Store`

Represents a collection of routes in an OpenAPI specification.

Each instance of this class contains a list of `Route` objects, which can be accessed and manipulated as needed.

```pycon
>>> from yaml import safe_load
>>> spec_yaml = '''
... openapi: 3.0.3
... paths:
...   /items:
...     get:
...       summary: List items
...       responses:
...         '200':
...           description: An array of items
...     post:
...       summary: Create item
...       responses:
...         '201':
...           description: Item created
... '''
>>> spec = safe_load(spec_yaml)
>>> routes = Routes(spec)
>>> len(routes)
2
>>> list(routes)
[('get', '/items'), ('post', '/items')]
>>> r = routes['get', '/items']
>>> r
Route(method='get', endpoint='/items')
>>> r.method_data
{'summary': 'List items', 'responses': {'200': {'description': 'An array of items'}}}
```

#### update(\*\*F) → None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does:     for k in E.keys(): D[k] = E[k]
If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v

#### update_keys_cache(keys)

Updates the \_keys_cache by deleting the attribute

### ju.oas.add_property(schema, sent_as, spec_names, name, place, prop_schema, required)

Add the parameter or body property `name`, sent in `place`, to the object
`schema`, keyed by its name; when that is taken (the same name in another
place – `id` in the query and in a header, a query `name` and a body
`name`), by a distinct key. Both then record the spec’s name and place
(OAS_NAME_KEY, OAS_IN_KEY), so a consumer can tell which is which. No distinct
key is a name in `spec_names`. `sent_as` (key -> (name, place)) is the state
to carry between calls.

```pycon
>>> schema, sent_as = {'properties': {}, 'required': []}, {}
>>> add_property(schema, sent_as, {'id'}, 'id', 'query', {'type': 'string'}, True)
>>> add_property(schema, sent_as, {'id'}, 'id', 'header', {'type': 'integer'}, False)
>>> sorted(schema['properties'])
['id', 'id_header']
>>> schema['properties']['id_header']['x-oas-in'], schema['required']
('header', ['id'])
```

### ju.oas.default_func_namer(method, path, details=None, , favor_operation_id=False)

Default function name generator for OpenAPI routes.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

```pycon
>>> default_func_namer('get', '/stores/{store_name}/{key}')
'get_stores__store_name__key'
```

### ju.oas.ensure_openapi_dict(spec)

Ensure that the OpenAPI specification is a dictionary.

It will handle:

- JSON strings
- YAML strings
- File paths to JSON or YAML files
- URLs pointing to OpenAPI specs
- Direct dictionaries

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### ju.oas.generate_and_import_openapi_client(openapi_spec, output_dir=None, , file_format='json')

openapi_spec: dict, or str (path to YAML/JSON file)
output_dir: where to generate the client (default: temp dir)
file_format: ‘yaml’ or ‘json’ (used if openapi_spec is a dict)

* **Returns:**
  imported client module

### ju.oas.generate_openapi_client(openapi_spec, output_dir=None, , file_format='json')

openapi_spec: dict, or str (path to YAML/JSON file)
output_dir: where to generate the client (default: temp dir)
file_format: ‘yaml’ or ‘json’ (used if openapi_spec is a dict)

* **Returns:**
  imported client module

### ju.oas.get_routes(d, include_methods=('get', 'put', 'post', 'patch', 'head', 'options', 'delete'))

Takes OpenAPI specification dict ‘d’ and returns the key-paths to all the endpoints.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### ju.oas.merge_parameters(path_item_params, operation_params)

The parameters of an operation: those its path item declares for all its
operations, overridden (same name and `in`) or extended by its own.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

```pycon
>>> merge_parameters(
...     [{'name': 'id', 'in': 'path'}, {'name': 'q', 'in': 'query', 'x': 1}],
...     [{'name': 'q', 'in': 'query', 'x': 2}, {'name': 'q', 'in': 'header'}],
... )
[{'name': 'id', 'in': 'path'}, {'name': 'q', 'in': 'query', 'x': 2}, {'name': 'q', 'in': 'header'}]
```

### ju.oas.merge_request_body_json_schema(details, param_schema)

If the operation has a requestBody with a JSON schema, merge its properties and required fields into param_schema.

### ju.oas.openapi_to_funcs(spec, \*, base_url=None, default_servers_url='http://localhost:8000', func_namer=<function default_func_namer>, get_response=<function default_get_response>, response_egress=None, use_default_func_namer_when_name_is_none=True)

spec: dict or str (YAML/JSON string or file path)
base_url: override the spec’s server URL
default_servers_url: default URL to use if no servers are specified in the spec
get_response: function to get the response object (default: requests.request)
response_egress: function (method, uri) -> callable to extract result from response
Returns a generator yielding OpenApiFunc instances for each route in the OpenAPI spec.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`OpenApiFunc`](_autosummary/ju.oas.html.md#ju.oas.OpenApiFunc)]

### ju.oas.openapi_to_generated_funcs(spec, \*, base_url=None, default_servers_url='http://localhost:8000', output_dir=None, file_format='json', func_namer=<function default_func_namer>, get_response=<function default_get_response>, response_egress=None)

Like openapi_to_funcs, but yields OpenApiFunc objects for each route, using the generated client for requests.
Uses func_namer for naming, and parameter schema from the OpenAPI spec.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`OpenApiFunc`](_autosummary/ju.oas.html.md#ju.oas.OpenApiFunc)]

### ju.oas.properties_of_schema(schema)

Returns the properties of the given schema, encapsulating in ArrayOf to indicate
that the schema is for an array of objects, and not just a single object.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### ju.oas.resolve_refs(open_api_spec, d)

Recursively resolves all references in ‘d’ using ‘open_api_spec’.

* **Parameters:**
  * **open_api_spec** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – The complete OpenAPI specification as a dictionary.
  * **d** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – The dictionary in which references need to be resolved.
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)
* **Returns:**
  The dictionary with all references resolved.

### ju.oas.validate_openapi_to_generated_funcs_alignment()

Example usage of openapi_to_generated_funcs.
This function is just for demonstration and should be removed in production code.


# _autosummary/ju.pydantic_util.html.md

# ju.pydantic_util

Tools for working with Pydantic models.

This module provides comprehensive utilities for creating, validating, transforming,
and extracting information from Pydantic models and JSON schemas.

### Key Functionality

### Model Creation and Validation

- `mk_pydantic_model`: Create Pydantic model instances with customizable validation
- `mk_pydantic_models`: Batch version for multiple models
- `is_valid_wrt_model`: Check if data is valid against a model
- `valid_models`: Find all models that validate given data
- `data_to_pydantic_model`: Dynamically create models from data dictionaries

### Schema and Code Generation

- `pydantic_model_to_code`: Convert schemas/models to Pydantic code with transforms
- `schema_to_pydantic_model_simple/advanced`: Convert JSON schemas to Pydantic models

### Model Introspection and Analysis

- `model_field_descriptions`: Extract field descriptions from models
- `field_paths_and_annotations`: Get flattened field paths and types
- `match_typevars_to_args`: Resolve generic type variables
- `is_a_basemodel`: Check if object is a Pydantic BaseModel

### Data Extraction

- `ModelExtractor`: Extract data using model schemas as templates
- Supports nested models and collection types with path notation (e.g., ‘items.\*.ref’)

### Type Classification

- `is_pydantic_model`: Detect Pydantic model classes
- `is_typing_type`: Detect typing module types
- `is_type_hint`: Combined type hint detection

### Error Handling

- `extract_friendly_errors`: Convert ValidationError to user-friendly messages

### Schema Transformations

The `pydantic_model_to_code` function supports:

- `ingress_transform`: Transform schemas before code generation
- `egress_transform`: Transform generated code
- Multiple source types: dicts, models, JSON strings, JSON files

### Examples

```python
# Create models from data
model = data_to_pydantic_model({"name": "John", "age": 30}, "User")

# Generate code with transformations
def fix_field_names(schema):
    # Transform problematic field names
    return schema

code = pydantic_model_to_code(model, ingress_transform=fix_field_names)

# Extract data using model schemas
extractor = ModelExtractor([UserModel, AdminModel])
data_reader = extractor(json_data)  # Returns KeysReader with model-based paths

# Validate data against multiple models
valid_model_list = list(valid_models(data, [Model1, Model2, Model3]))
```

### Functions

| [`PydanticModelFactory`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.PydanticModelFactory)(schema[, model_name])         | Converts a JSON schema (with 'properties') to a Pydantic model.                                             |
|-----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|
| [`data_to_pydantic_model`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.data_to_pydantic_model)(data[, name, ...])          | Generate a dynamic Pydantic model, optionally creating nested models for nested dictionaries.               |
| [`extract_friendly_errors`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.extract_friendly_errors)(e)                         | Extracts a generator of user-friendly error messages from a Pydantic ValidationError.                       |
| [`field_paths_and_annotations`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.field_paths_and_annotations)(data_model)            | Get flattened field paths and their corresponding annotations from a Pydantic model.                        |
| [`fix_generated_code_transform`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.fix_generated_code_transform)(code)                 | Fix common issues in generated code.                                                                        |
| [`infer_json_friendly_type`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.infer_json_friendly_type)(value)                    | Infers the type of the value for Pydantic model field.                                                      |
| [`is_a_basemodel`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.is_a_basemodel)(obj)                                | Check if an object is a Pydantic BaseModel.                                                                 |
| [`is_pydantic_model`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.is_pydantic_model)(obj)                             | Returns True if the object is a Pydantic model (subclass of BaseModel).                                     |
| [`is_type_hint`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.is_type_hint)(obj)                                  | Returns True if the object is a Pydantic model or a typing type.                                            |
| [`is_typing_type`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.is_typing_type)(obj)                                | Returns True if the object is a typing type (e.g., List, Literal, etc.).                                    |
| [`is_valid_wrt_model`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.is_valid_wrt_model)(data, model, \*[, factory])     | Check if a json object is valid wrt to a pydantic model.                                                    |
| [`jsonschema_to_openapi_transform`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.jsonschema_to_openapi_transform)(schema)            | Transform JSON Schema to OpenAPI-compatible schema.                                                         |
| [`match_typevars_to_args`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.match_typevars_to_args)(generic_model)              | Given a Pydantic generic model, returns a mapping of type variables to their concrete types.                |
| [`mk_pydantic_model`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.mk_pydantic_model)(data, model, \*[, factory, ...]) | Make a Pydantic model instance from data, parametrizing constructor and error handling.                     |
| [`mk_pydantic_models`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.mk_pydantic_models)(data, models, \*[, ...])        | The iterable-of-models version of `mk_pydantic_model`.                                                      |
| [`model_field_descriptions`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.model_field_descriptions)(model[, ...])             | Extracts a dictionary of field paths and their descriptions from a Pydantic model, including nested models. |
| [`pydantic_model_to_code`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.pydantic_model_to_code)(source, \*[, ...])          | Convert a model source (json string, dict, or pydantic model) to pydantic code.                             |
| [`schema_to_pydantic_model`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.schema_to_pydantic_model)(schema[, model_name])     | Converts a JSON schema (with 'properties') to a Pydantic model.                                             |
| [`schema_to_pydantic_model_simple`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.schema_to_pydantic_model_simple)(schema[, ...])     | Converts a JSON schema (with 'properties') to a Pydantic model.                                             |
| [`valid_models`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.valid_models)(json_obj, models, \*[, factory])      | A generator that yields the models that json_obj is valid with respect to.                                  |

### Classes

| [`ModelExtractor`](_autosummary/ju.pydantic_util.html.md#ju.pydantic_util.ModelExtractor)(models, \*[, getter])   | Extracts key paths and corresponding values from data based on matching Pydantic models.   |
|-----------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|

### *class* ju.pydantic_util.ModelExtractor(models, \*, getter=<function glom>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Extracts key paths and corresponding values from data based on matching Pydantic models.

`ModelExtractor` takes a collection of models and extracts all valid key paths from
their (nested) schemas. When called on data, it identifies the first model that
matches the structure of the data and returns a `KeysReader`, which is a mapping
of key paths to the corresponding values in the data.

A `KeysReader` instance is a mapping that gives you lazy-evaluated access to values.
With such an instance, you can list the keys (paths) that are valid according to
the schema of the matched model, and extract the corresponding values from the data
at the moment you need them.

* **Parameters:**
  * **models** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), `BaseModel`] | [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`BaseModel`]) – A dictionary mapping model names to models, or an iterable of models.
    If an iterable is provided, it will be converted to a dictionary using
    the model names.
  * **getter** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – A function used to extract values from the data based on the identified
    paths. Defaults to `glom.glom`, a tool for nested data extraction.
* **Raises:**
  [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the provided models do not have unique names, either as an iterable or
      in the dictionary keys.

### Example

```pycon
>>> from typing import List
>>> from pydantic import BaseModel
>>>
>>> class Item(BaseModel):
...     ref: int
>>> class Playlist(BaseModel):
...     name: str
...     items: List[Item]
>>> class User(BaseModel):
...     name: str
...     age: int
>>>
>>> models = [Playlist, User]
>>> extractors = ModelExtractor(models)
>>> data = {"name": "Digital Reveries", "items": [{"ref": 6}, {"ref": 42}]}
>>> d = extractors(data)
>>> list(d)
['name', 'items.*.ref']
>>> d['name']
'Digital Reveries'
>>> d['items.*.ref']
[6, 42]
```

The example shows how the `ModelExtractor` class automatically detects the model
(in this case, `Playlist`), retrieves the paths defined by the model schema
(e.g., ‘name’ and ‘items.\*.ref’), and extracts the corresponding values from the data.

#### getter(spec, \*\*kwargs)

Access or construct a value from a given *target* based on the
specification declared by *spec*.

Accessing nested data, aka deep-get:

```pycon
>>> target = {'a': {'b': 'c'}}
>>> glom(target, 'a.b')
'c'
```

Here the *spec* was just a string denoting a path,
`'a.b'`. As simple as it should be. You can also use
[`glob`](https://docs.python.org/3/library/glob.html#module-glob)-like wildcard selectors:

```pycon
>>> target = {'a': [{'k': 'v1'}, {'k': 'v2'}]}
>>> glom(target, 'a.*.k')
['v1', 'v2']
```

In addition to `*`, you can also use `**` for recursive access:

```pycon
>>> target = {'a': [{'k': 'v3'}, {'k': 'v4'}], 'k': 'v0'}
>>> glom(target, '**.k')
['v0', 'v3', 'v4']
```

The next example shows how to use nested data to
access many fields at once, and make a new nested structure.

Constructing, or restructuring more-complicated nested data:

```pycon
>>> target = {'a': {'b': 'c', 'd': 'e'}, 'f': 'g', 'h': [0, 1, 2]}
>>> spec = {'a': 'a.b', 'd': 'a.d', 'h': ('h', [lambda x: x * 2])}
>>> output = glom(target, spec)
>>> pprint(output)
{'a': 'c', 'd': 'e', 'h': [0, 2, 4]}
```

`glom` also takes a keyword-argument, *default*. When set,
if a `glom` operation fails with a `GlomError`, the
*default* will be returned, very much like
[`dict.get()`](https://docs.python.org/3/builtins/stdtypes.html#dict.get):

```pycon
>>> glom(target, 'a.xx', default='nada')
'nada'
```

The *skip_exc* keyword argument controls which errors should
be ignored.

```pycon
>>> glom({}, lambda x: 100.0 / len(x), default=0.0, skip_exc=ZeroDivisionError)
0.0
```

* **Parameters:**
  * **target** ([*object*](https://docs.python.org/3/builtins/functions.html#object)) – the object on which the glom will operate.
  * **spec** ([*object*](https://docs.python.org/3/builtins/functions.html#object)) – Specification of the output object in the form
    of a dict, list, tuple, string, other glom construct, or
    any composition of these.
  * **default** ([*object*](https://docs.python.org/3/builtins/functions.html#object)) – An optional default to return in the case
    an exception, specified by *skip_exc*, is raised.
  * **skip_exc** ([*Exception*](https://docs.python.org/3/builtins/exceptions.html#Exception)) – An optional exception or tuple of
    exceptions to ignore and return *default* (None if
    omitted). If *skip_exc* and *default* are both not set,
    glom raises errors through.
  * **scope** ([*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)) – Additional data that can be accessed
    via S inside the glom-spec. Read more: scope.

It’s a small API with big functionality, and glom’s power is
only surpassed by its intuitiveness. Give it a whirl!

### ju.pydantic_util.PydanticModelFactory(schema, model_name='AutoModel')

Converts a JSON schema (with ‘properties’) to a Pydantic model.
Only supports basic types and required fields for demonstration.

* **Return type:**
  [`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]

```pycon
>>> schema_simple = {
...     "type": "object",
...     "properties": {
...         "name": {"type": "string"},
...         "age": {"type": "integer"},
...         "city": {"type": "string", "default": "New York"}
...     },
...     "required": ["name"]
... }
>>> model = schema_to_pydantic_model_simple(schema_simple, "User")
>>> model.__name__
'User'
>>> model.model_json_schema()['properties']['name']
{'title': 'Name', 'type': 'string'}
>>> age_schema = model.model_json_schema()['properties']['age']
>>> assert age_schema['title'] == 'Age'
>>> # Ensure both integer and null are allowed (order-independent)
>>> assert {'type': 'integer'} in age_schema.get('anyOf', []) and {'type': 'null'} in age_schema.get('anyOf', [])
>>> city_schema = model.model_json_schema()['properties']['city']
>>> assert city_schema['title'] == 'City' and city_schema['default'] == 'New York' and city_schema['type'] == 'string'
>>> model.model_json_schema()['required']
['name']
```

### ju.pydantic_util.data_to_pydantic_model(data, name='DataBasedModel', , defaults=None, create_nested_models=True, mk_nested_name=None)

Generate a dynamic Pydantic model, optionally creating nested models for nested dictionaries.

* **Parameters:**
  * **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Name of the Pydantic model to create.
  * **data** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – A dictionary representing the structure of the model.
  * **defaults** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – A dictionary specifying default values for certain fields.
  * **create_nested_models** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create nested models for nested dictionaries.
* **Returns:**
  A dynamically created Pydantic model, with nested models if applicable.

```pycon
>>> json_data = {
...     "name": "John", "age": 30, "address": {"city": "New York", "zipcode": "10001"}
... }
>>> defaults = {"age": 18}
>>>
>>> M = data_to_pydantic_model(json_data, "M", defaults=defaults)
>>>
>>> model_instance_custom = M(
... name="John", age=25, address={"city": "Mountain View", "zipcode": "94043"}
... )
>>> model_instance_custom.model_dump()
{'name': 'John', 'age': 25, 'address': {'city': 'Mountain View', 'zipcode': '94043'}}
>>> model_instance_with_defaults = M(
...     name="Jane", address={"city": "Los Angeles", "zipcode": "90001"}
... )
>>> model_instance_with_defaults.model_dump()
{'name': 'Jane', 'age': 18, 'address': {'city': 'Los Angeles', 'zipcode': '90001'}}
```

And note that the nested model is also created:

```pycon
>>> M.Address(city="New York", zipcode="10001")
Address(city='New York', zipcode='10001')
```

### ju.pydantic_util.extract_friendly_errors(e)

Extracts a generator of user-friendly error messages from a Pydantic ValidationError.

### ju.pydantic_util.field_paths_and_annotations(data_model)

Get flattened field paths and their corresponding annotations from a Pydantic model.

Generates a dictionary of dot-separated paths and their corresponding types
from the fields of a given Pydantic BaseModel and any nested BaseModels within it.

The function recursively traverses the fields of the BaseModel and its nested models,
including fields that are lists, sets, tuples, or iterables containing BaseModels.
If the field is a collection containing a BaseModel, the path is marked with a ‘\*’.

This structure is compatible with the `glom` library, allowing extraction of values
from a dictionary that matches the BaseModel structure.

* **Parameters:**
  **data_model** ([`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]) – The Pydantic BaseModel to extract field paths and annotations from.
* **Returns:**
  A dictionary where the keys are the dot-separated paths to fields
  : and the values are their corresponding types.
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`type`](https://docs.python.org/3/builtins/functions.html#type)[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### Example

```pycon
>>> from pydantic import BaseModel
>>> from typing import List
```

```pycon
>>> class BItem(BaseModel):
...     c: int
```

```pycon
>>> class A(BaseModel):
...     b: List[BItem]
...     d: str
```

```pycon
>>> class Model(BaseModel):
...     a: A
```

```pycon
>>> paths = field_paths_and_annotations(Model)
>>> expected_paths = {'a.b.*.c': int, 'a.d': str}
>>> assert paths == expected_paths, f"Expected: {expected_paths}, but got: {paths}"
```

See that it works with generics:

```pycon
>>> from typing import TypeVar, List, Generic
>>> T = TypeVar('T')
>>> class A_with_Generic(BaseModel, Generic[T]):
...     b: List[T]
...     d: str
>>> class Model_with_Generic(BaseModel):
...     a: A_with_Generic[BItem]
>>>
>>> field_paths_and_annotations(Model_with_Generic)
{'a.b.*.c': <class 'int'>, 'a.d': <class 'str'>}
```

### ju.pydantic_util.fix_generated_code_transform(code)

Fix common issues in generated code.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ju.pydantic_util.infer_json_friendly_type(value)

Infers the type of the value for Pydantic model field.

```pycon
>>> infer_json_friendly_type(42)
<class 'int'>
>>> infer_json_friendly_type("Hello, World!")
<class 'str'>
>>> infer_json_friendly_type({"key": "value"})
<class 'dict'>
```

### ju.pydantic_util.is_a_basemodel(obj)

Check if an object is a Pydantic BaseModel.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

```pycon
>>> from typing import List
>>> class MyModel(BaseModel):
...     '''Some model'''
>>> list(map(is_a_basemodel, [BaseModel, MyModel, 3.14, int, List[MyModel]]))
[True, True, False, False, False]
```

### ju.pydantic_util.is_pydantic_model(obj)

Returns True if the object is a Pydantic model (subclass of BaseModel).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### ju.pydantic_util.is_type_hint(obj)

Returns True if the object is a Pydantic model or a typing type.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### ju.pydantic_util.is_typing_type(obj)

Returns True if the object is a typing type (e.g., List, Literal, etc.).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### ju.pydantic_util.is_valid_wrt_model(data, model, \*, factory=<function \_model_validate>)

Check if a json object is valid wrt to a pydantic model.

### ju.pydantic_util.jsonschema_to_openapi_transform(schema)

Transform JSON Schema to OpenAPI-compatible schema.
This handles $ref resolution and other incompatibilities.

Uses jsonschema2pydantic library approach.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### ju.pydantic_util.match_typevars_to_args(generic_model)

Given a Pydantic generic model, returns a mapping of type variables to their
concrete types.

* **Parameters:**
  **generic_model** ([`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]) – A generic Pydantic model (e.g., Pair[int, str]).
* **Returns:**
  A dictionary mapping type variables (e.g., T and U)
  to their concrete types (e.g., int and str).
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`TypeVar`, bound= <attribute ‘_\_bound_\_’ of ‘typing.TypeVar’ objects>, covariant=<member ‘_\_covariant_\_’ of ‘typing.TypeVar’ objects>, contravariant=<member ‘_\_contravariant_\_’ of ‘typing.TypeVar’ objects>), [`type`](https://docs.python.org/3/builtins/functions.html#type)[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

```pycon
>>> from typing import TypeVar, Generic, List
```

```pycon
>>> T = TypeVar('T')
>>> U = TypeVar('U')
```

```pycon
>>> class Pair(Generic[T, U]):
...     first: T
...     second: U
```

```pycon
>>> X = Pair[int, str]
```

```pycon
>>> match_typevars_to_args(X)
{~T: <class 'int'>, ~U: <class 'str'>}
```

### ju.pydantic_util.mk_pydantic_model(data, model, \*, factory=<function \_model_validate>, error_callback=<function \_raise_error>)

Make a Pydantic model instance from data, parametrizing constructor and error handling.

By default, it uses the `model.model_validate` method, but you can pass a custom
constructor function and error handling callback.

* **Parameters:**
  * **data** ([`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`Data`, bound= [`Any`](https://docs.python.org/3/library/typing.html#typing.Any))) – A dictionary representing the data to be validated.
  * **model** ([`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]) – A Pydantic model class.
  * **factory** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`], [`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`Data`, bound= [`Any`](https://docs.python.org/3/library/typing.html#typing.Any))], `BaseModel`]) – A callable used to construct the model instance.
    Defaults to `model.model_validate`.
  * **error_callback** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – A callback to handle validation errors.
* **Return type:**
  `BaseModel`
* **Returns:**
  A Pydantic model instance.

### Example

```pycon
>>> from pydantic import BaseModel
>>> class User(BaseModel):
...     name: str
...     code: int
...
>>> data = {"name": "John", "code": 30}
>>> user = mk_pydantic_model(data, User)
>>> user
User(name='John', code=30)
```

Example with custom constructor:

```pycon
>>> user = mk_pydantic_model(data, User, factory=lambda model, data: model.model_construct(**data))
>>> user
User(name='John', code=30)
```

### ju.pydantic_util.mk_pydantic_models(data, models, \*, factory=<function \_model_validate>, error_callback=<function \_raise_error>)

The iterable-of-models version of `mk_pydantic_model`.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`BaseModel`]

### ju.pydantic_util.model_field_descriptions(model, default_description='No description provided', , prefix='')

Extracts a dictionary of field paths and their descriptions from a Pydantic model,
including nested models.

* **Parameters:**
  * **model** ([`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]) – A Pydantic model class.
  * **prefix** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – A prefix for nested fields (used internally during recursion).
* **Returns:**
  A dictionary of field paths and descriptions.
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### Example

```pycon
>>> from pydantic import BaseModel, Field
>>> class Address(BaseModel):
...     city: str = Field(..., description="City name")
...     zipcode: str = Field(..., description="ZIP code")
>>> class User(BaseModel):
...     name: str = Field(..., description="The name of the user")
...     address: Address
>>> model_field_descriptions(User)
{'name': 'The name of the user',
 'address.city': 'City name',
 'address.zipcode': 'ZIP code'}
```

### ju.pydantic_util.pydantic_model_to_code(source, , ingress_transform=None, egress_transform=None, \*\*extra_json_schema_parser_kwargs)

Convert a model source (json string, dict, or pydantic model) to pydantic code.

Requires having datamodel-code-generator installed (pip install datamodel-code-generator)

Code was based on: [https://koxudaxi.github.io/datamodel-code-generator/using_as_module/](https://koxudaxi.github.io/datamodel-code-generator/using_as_module/)

See also this free online converter: [https://jsontopydantic.com/](https://jsontopydantic.com/)

* **Parameters:**
  * **ingress_transform** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Function to transform schema before generation
  * **egress_transform** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Function to transform generated code
* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

```pycon
>>> json_schema: str = '''{
...     "type": "object",
...     "properties": {
...         "number": {"type": "number"},
...         "street_name": {"type": "string"},
...         "street_type": {"type": "string",
...                         "enum": ["Street", "Avenue", "Boulevard"]
...                         }
...     }
... }'''
>>> print(pydantic_model_to_code(json_schema))
from __future__ import annotations

from enum import Enum
from typing import Optional

from pydantic import BaseModel


class StreetType(Enum):
    Street = 'Street'
    Avenue = 'Avenue'
    Boulevard = 'Boulevard'


class Model(BaseModel):
    number: Optional[float] = None
    street_name: Optional[str] = None
    street_type: Optional[StreetType] = None
```

This means you can get some model code from an example data dict,
using pydantic_model_to_code

```pycon
>>> M = data_to_pydantic_model({"name": "John", "age": 30}, "Simple")
>>> print(pydantic_model_to_code(M))
from __future__ import annotations

from pydantic import BaseModel, Field


class Simple(BaseModel):
    name: str = Field(..., title='Name')
    age: int = Field(..., title='Age')
```

### ju.pydantic_util.schema_to_pydantic_model(schema, model_name='AutoModel')

Converts a JSON schema (with ‘properties’) to a Pydantic model.
Only supports basic types and required fields for demonstration.

* **Return type:**
  [`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]

```pycon
>>> schema_simple = {
...     "type": "object",
...     "properties": {
...         "name": {"type": "string"},
...         "age": {"type": "integer"},
...         "city": {"type": "string", "default": "New York"}
...     },
...     "required": ["name"]
... }
>>> model = schema_to_pydantic_model_simple(schema_simple, "User")
>>> model.__name__
'User'
>>> model.model_json_schema()['properties']['name']
{'title': 'Name', 'type': 'string'}
>>> age_schema = model.model_json_schema()['properties']['age']
>>> assert age_schema['title'] == 'Age'
>>> # Ensure both integer and null are allowed (order-independent)
>>> assert {'type': 'integer'} in age_schema.get('anyOf', []) and {'type': 'null'} in age_schema.get('anyOf', [])
>>> city_schema = model.model_json_schema()['properties']['city']
>>> assert city_schema['title'] == 'City' and city_schema['default'] == 'New York' and city_schema['type'] == 'string'
>>> model.model_json_schema()['required']
['name']
```

### ju.pydantic_util.schema_to_pydantic_model_simple(schema, model_name='AutoModel')

Converts a JSON schema (with ‘properties’) to a Pydantic model.
Only supports basic types and required fields for demonstration.

* **Return type:**
  [`type`](https://docs.python.org/3/builtins/functions.html#type)[`BaseModel`]

```pycon
>>> schema_simple = {
...     "type": "object",
...     "properties": {
...         "name": {"type": "string"},
...         "age": {"type": "integer"},
...         "city": {"type": "string", "default": "New York"}
...     },
...     "required": ["name"]
... }
>>> model = schema_to_pydantic_model_simple(schema_simple, "User")
>>> model.__name__
'User'
>>> model.model_json_schema()['properties']['name']
{'title': 'Name', 'type': 'string'}
>>> age_schema = model.model_json_schema()['properties']['age']
>>> assert age_schema['title'] == 'Age'
>>> # Ensure both integer and null are allowed (order-independent)
>>> assert {'type': 'integer'} in age_schema.get('anyOf', []) and {'type': 'null'} in age_schema.get('anyOf', [])
>>> city_schema = model.model_json_schema()['properties']['city']
>>> assert city_schema['title'] == 'City' and city_schema['default'] == 'New York' and city_schema['type'] == 'string'
>>> model.model_json_schema()['required']
['name']
```

### ju.pydantic_util.valid_models(json_obj, models, \*, factory=<function \_model_validate>)

A generator that yields the models that json_obj is valid with respect to.

```pycon
>>> from pydantic import BaseModel
>>> class User(BaseModel):
...     name: str
...     code: int
...
>>> class Admin(User):
...     pwd: str
...
>>> json_obj = {"name": "John", "code": 30}
>>> models = [User, Admin]
>>> [x.__name__ for x in valid_models(json_obj, models)]
['User']
>>> json_obj = {"name": "Thor", "code": 3, "pwd": "1234"}
>>> [x.__name__ for x in valid_models(json_obj, models)]
['User', 'Admin']
```

Note that valid_models is a generator, it doesn’t return a list.

Tip, to get the first model that is valid, or None if no model is valid:

```pycon
>>> get_name = lambda o: getattr(o, '__name__', 'None')
>>> first_valid_model_name = (
...     lambda o, models: get_name(next(valid_models(o, models), None))
... )
>>> first_valid_model_name({"name": "John", "code": 30}, models)
'User'
>>> first_valid_model_name({"something": "else"}, models)
'None'
```


# _autosummary/ju.rjsf.html.md

# ju.rjsf

Tools for React-JSONSchema-Form (RJSF)

### Functions

| [`DFLT_RJSF_VIEWER_ON_SUBMIT`](_autosummary/ju.rjsf.html.md#ju.rjsf.DFLT_RJSF_VIEWER_ON_SUBMIT)(form_data, \*[, ...])   | Prints form_data in a nicely formatted way.                                                                                                               |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`create_rjsf_viewer`](_autosummary/ju.rjsf.html.md#ju.rjsf.create_rjsf_viewer)(rjsf_spec, \*[, ...])           | Factory function to create and display an RJSF viewer.                                                                                                    |
| [`display_form_data`](_autosummary/ju.rjsf.html.md#ju.rjsf.display_form_data)(form_data, \*[, indent, ...])    | Prints form_data in a nicely formatted way.                                                                                                               |
| [`display_in_notebook`](_autosummary/ju.rjsf.html.md#ju.rjsf.display_in_notebook)(string)                        | Display a string in a Jupyter notebook cell.                                                                                                              |
| [`func_to_form_spec`](_autosummary/ju.rjsf.html.md#ju.rjsf.func_to_form_spec)(func, \*[, doc, ...])            | Returns a JSON object that can be used as a form specification, along with the function, to generate a FuncCaller React component in a React application. |

### Classes

| [`FormConfig`](_autosummary/ju.rjsf.html.md#ju.rjsf.FormConfig)([submit_text, show_labels, ...])       | Configuration for form rendering behavior.      |
|----------------------------------------------------------------------------------------------------|-------------------------------------------------|
| [`RJSFViewer`](_autosummary/ju.rjsf.html.md#ju.rjsf.RJSFViewer)(rjsf_spec, \*[, on_submit, name, ...]) | Renders RJSF specifications as Jupyter widgets. |

### ju.rjsf.DFLT_RJSF_VIEWER_ON_SUBMIT(form_data, , indent=2, ensure_ascii=False, prefix='\*\*Submitted data:\*\*\\\\n\\\\n')

Prints form_data in a nicely formatted way.

* **Parameters:**
  **form_data** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – The collected form data
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### *class* ju.rjsf.FormConfig(submit_text='Submit', show_labels=True, layout_width='400px', autofocus_first=True)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Configuration for form rendering behavior.

### *class* ju.rjsf.RJSFViewer(rjsf_spec, \*, on_submit=<function display_form_data>, name=None, unpack_form_data=None, config=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Renders RJSF specifications as Jupyter widgets.

Provides a bridge between RJSF form specifications and ipywidgets,
allowing interactive form viewing and data collection in notebooks.

### Example

```pycon
>>> rjsf_dict = {'rjsf': {'schema': {...}, 'uiSchema': {...}}}
>>> viewer = RJSFViewer(rjsf_dict)
>>> viewer.display()
```

#### display()

Display the form in the notebook.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### get_form_data()

Extract current form data from widgets.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Dictionary of form field values

#### set_form_data(data)

Set form data programmatically.

* **Parameters:**
  **data** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary of field values to set
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### *property* widget *: Widget*

Access the underlying widget for custom layouts.

### ju.rjsf.create_rjsf_viewer(rjsf_spec, \*, on_submit=<function display_form_data>, name=None, unpack_form_data=None, config=None, display=False)

Factory function to create and display an RJSF viewer.

* **Parameters:**
  * **rjsf_spec** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – The RJSF specification
  * **on_submit** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – Optional submission callback
  * **config** ([`FormConfig`](_autosummary/ju.rjsf.html.md#ju.rjsf.FormConfig) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional form configuration
* **Return type:**
  [`RJSFViewer`](_autosummary/ju.rjsf.html.md#ju.rjsf.RJSFViewer)
* **Returns:**
  Configured RJSFViewer instance

### Example

```pycon
>>> def handle_data(data):
...     print(f"Received: {data}")
>>> viewer = create_rjsf_viewer(rjsf_dict, on_submit=handle_data)
>>> viewer.display()
```

### ju.rjsf.display_form_data(form_data, , indent=2, ensure_ascii=False, prefix='\*\*Submitted data:\*\*\\\\n\\\\n')

Prints form_data in a nicely formatted way.

* **Parameters:**
  **form_data** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – The collected form data
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### ju.rjsf.display_in_notebook(string)

Display a string in a Jupyter notebook cell.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### ju.rjsf.func_to_form_spec(func, \*, doc=True, param_to_prop_type=functools.partial(<function parametrized_param_to_type>, type_mapping=((<class 'str'>, 'string'), (<class 'bool'>, 'boolean'), (<class 'int'>, 'integer'), (<class 'float'>, 'number'), (<class 'collections.abc.Mapping'>, 'object'), (collections.abc.Sequence[str], 'array'), (<class 'bytes'>, 'string'), (<class 'bytearray'>, 'string'), (<class 'memoryview'>, 'string'), (<class 'collections.UserString'>, 'string'), (<class 'collections.abc.Sequence'>, 'array'))), nest_under_field='rjsf', base_rjsf_spec={'disabled': False, 'focusOnFirstError': False, 'liveOmit': False, 'liveValidate': False, 'noHtml5Validate': False, 'noValidate': False, 'omitExtraData': False, 'readonly': False, 'schema': {'properties': {}, 'required': [], 'title': '', 'type': 'object'}, 'showErrorList': 'top', 'uiSchema': {'ui:submitButtonOptions': {'submitText': 'Run'}}}, pyname_to_title=<function asis>)

Returns a JSON object that can be used as a form specification, along with the
function, to generate a FuncCaller React component in a React application.

param func: The function to transform
return: The form specification for the function

```pycon
>>> def foo(
...     a_bool: bool,
...     a_float=3.14,
...     an_int=2,
...     a_str: str = 'hello',
...     something_else=None
... ):
...     '''A Foo function'''
>>>
>>> form_spec = func_to_form_spec(foo)
>>> assert form_spec == {
...     'rjsf': {
...         'schema': {
...             'title': 'foo',
...             'type': 'object',
...             'properties': {
...                 'a_bool': {'type': 'boolean'},
...                 'a_float': {'type': 'number', 'default': 3.14},
...                 'an_int': {'type': 'integer', 'default': 2},
...                 'a_str': {'type': 'string', 'default': 'hello'},
...                 'something_else': {'type': 'string', 'default': None}
...             },
...             'required': ['a_bool'],
...             'description': 'A Foo function'
...         },
...         'uiSchema': {
...             'ui:submitButtonOptions': {
...                 'submitText': 'Run'
...             },
...             'a_bool': {'ui:autofocus': True}
...         },
...         'liveValidate': False,
...         'disabled': False,
...         'readonly': False,
...         'omitExtraData': False,
...         'liveOmit': False,
...         'noValidate': False,
...         'noHtml5Validate': False,
...         'focusOnFirstError': False,
...         'showErrorList': 'top'
...     }
... }
```


# _autosummary/ju.traitlets_util.html.md

# ju.traitlets_util

Utils for traitlets

### Functions

| [`extract_type_params`](_autosummary/ju.traitlets_util.html.md#ju.traitlets_util.extract_type_params)(trait_type, trait)   | Extract type parameters for a trait.                                               |
|-------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`trait_to_py`](_autosummary/ju.traitlets_util.html.md#ju.traitlets_util.trait_to_py)(trait)                       | Convert a traitlets trait (instance or type) to a Python object (instance or type) |

### ju.traitlets_util.extract_type_params(trait_type, trait)

Extract type parameters for a trait.

```pycon
>>> extract_type_params(
...     traitlets.Union, traitlets.Union([traitlets.Unicode(), traitlets.Float()])
... )
(<class 'str'>, <class 'float'>)
```

### ju.traitlets_util.trait_to_py(trait)

Convert a traitlets trait (instance or type) to a Python object (instance or type)

* **Return type:**
  [`object`](https://docs.python.org/3/builtins/functions.html#object) | [`type`](https://docs.python.org/3/builtins/functions.html#type)

```pycon
>>> trait_to_py(traitlets.Bool())
<class 'bool'>
>>> trait_to_py(traitlets.Union([traitlets.Unicode(), traitlets.Float()]))
typing.Union[str, float]
```


# _autosummary/ju.util.html.md

# ju.util

Ju base utils.

### Functions

| [`apply`](_autosummary/ju.util.html.md#ju.util.apply)(func, obj)                                  | Calls a function to an object, returing the result                                                                                                                     |
|----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `asis`(obj)                                                                                        |                                                                                                                                                                        |
| `display_dag_of_code`(func, \*args, \*\*kwargs)                                                    |                                                                                                                                                                        |
| [`ensure_callable_mapper`](_autosummary/ju.util.html.md#ju.util.ensure_callable_mapper)(mapper, \*[, default])     | Will return a CallableMapper from the specification of a Mapper, which could be a Mapping itself, a callable, or (key, value) pairs.                                   |
| [`ensure_mapping_mapper`](_autosummary/ju.util.html.md#ju.util.ensure_mapping_mapper)(mapper, \*[, default])      | Will return a MappingMapper (a dict really) from the specification of a Mapper, which could be a Mapping itself, a callable, or (key, value) pairs.                    |
| [`feature_based_search`](_autosummary/ju.util.html.md#ju.util.feature_based_search)(...)                         | Returns a function that searches for a feature in a list of feature_processor_pairs                                                                                    |
| [`feature_similarity_search`](_autosummary/ju.util.html.md#ju.util.feature_similarity_search)(obj, \*, ...[, ...])    | Returns the output of a feature based on a featurizer and a list of feature_output_pairs                                                                               |
| [`feature_switch`](_autosummary/ju.util.html.md#ju.util.feature_switch)(obj, \*, featurizer, ...)          | Returns the output of a feature based on a featurizer and a mapping                                                                                                    |
| `is_jsonable`(x)                                                                                   |                                                                                                                                                                        |
| [`is_type`](_autosummary/ju.util.html.md#ju.util.is_type)(param, type_)                             | Checks if the type of a parameter's default value or its annotation matches a given type.                                                                              |
| `mk_function_returning`(_obj)                                                                      |                                                                                                                                                                        |
| [`resolve_annotations`](_autosummary/ju.util.html.md#ju.util.resolve_annotations)(func, parameters)             | Returns `parameters` (a mapping or iterable of `Parameter`) with the string annotations of `func` evaluated -- all of them under `from __future__ import annotations`. |
| [`switch_case`](_autosummary/ju.util.html.md#ju.util.switch_case)(mapping, default)                     | Returns a function that switches between cases based on a feature                                                                                                      |
| [`truncate_dict_values`](_autosummary/ju.util.html.md#ju.util.truncate_dict_values)(d, \*[, max_list_size, ...]) | Returns a new dictionary with the same nested keys structure, where:                                                                                                   |
| [`unwrap_optional`](_autosummary/ju.util.html.md#ju.util.unwrap_optional)(annotation)                       | Strips `None` out of an `Optional`/union annotation; returns the annotation unchanged if it is not a union, and the single remaining member if there is one.           |

### Classes

| [`GetWithCaller`](_autosummary/ju.util.html.md#ju.util.GetWithCaller)(getter_func[, default, ...])   | Implements the [.] operator with a backend caller.     |
|-----------------------------------------------------------------------------------------------|--------------------------------------------------------|
| [`Gettable`](_autosummary/ju.util.html.md#ju.util.Gettable)(\*args, \*\*kwargs)                 | The missing type for objects that can be fetched from. |

### *class* ju.util.GetWithCaller(getter_func, default=Sentinel('NotSpecified'), handle_exceptions=(<class 'KeyError'>, ))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Implements the [.] operator with a backend caller.

```pycon
>>> g = GetWithCaller(lambda x: x + 1)
>>> g[4]
5
```

### *class* ju.util.Gettable(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

The missing type for objects that can be fetched from.
The contract is that we can fetch an element from `obj` with brackets: `obj[k]`.
That is, `obj` has a `__getitem__` method.

```pycon
>>> isinstance(3, Gettable)  # 3 is not Gettable (can't do 3[...])
False
```

But `dict`, `list`, and `str` are Gettable:

```pycon
>>> isinstance([1, 2, 3], Gettable)
True
>>> isinstance({'foo': 'bar'}, Gettable)
True
>>> isinstance('foo', Gettable)
True
```

Note that so are their types:

```pycon
>>> all(isinstance(c, Gettable) for c in (list, dict, str))
True
```

### ju.util.apply(func, obj)

Calls a function to an object, returing the result

### ju.util.ensure_callable_mapper(mapper, , default=Sentinel('NotSpecified'))

Will return a CallableMapper from the specification of a Mapper,
which could be a Mapping itself, a callable, or (key, value) pairs.

Further, if default is specified, the mapper will return that default if the
requested key is not found.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`KT`)], [`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`VT`)]

```pycon
>>> mapping = {'a': 1, 'b': 2}
>>> func = ensure_callable_mapper(mapping, default=3)
>>> func('a')
1
>>> func('c')
3
>>> items = [('a', 1), ('b', 2)]
>>> func = ensure_callable_mapper(items, default=3)
>>> func('a')
1
>>> func('c')
3
```

### ju.util.ensure_mapping_mapper(mapper, , default=Sentinel('NotSpecified'))

Will return a MappingMapper (a dict really) from the specification of a Mapper,
which could be a Mapping itself, a callable, or (key, value) pairs.

Further, if default is specified, the mapper will return that default if the
requested key is not found.

* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`KT`), [`TypeVar`](https://docs.python.org/3/library/typing.html#typing.TypeVar)(`VT`)]

```pycon
>>> func = lambda k: {'a': 1, 'b': 2}[k]
>>> d = ensure_mapping_mapper(func, default=3)
>>> d['a']
1
>>> d['c']
3
>>> items = [('a', 1), ('b', 2)]
>>> d = ensure_mapping_mapper(items, default=3)
>>> d['a']
1
>>> d['c']
3
```

### ju.util.feature_based_search(feature_processor_pairs, feature_similarity, default)

Returns a function that searches for a feature in a list of feature_processor_pairs

### ju.util.feature_similarity_search(obj, \*, featurizer, feature_based_search, feature_output_pairs, feature_similarity, similarity_base_match=<function <lambda>>)

Returns the output of a feature based on a featurizer and a list of feature_output_pairs

### ju.util.feature_switch(obj, , featurizer, feature_to_output_mapping, default)

Returns the output of a feature based on a featurizer and a mapping

### ju.util.is_type(param, type_)

Checks if the type of a parameter’s default value or its annotation matches a
given type.

This function handles both regular types and subscripted generics.

* **Parameters:**
  * **param** ([`Parameter`](https://docs.python.org/3/library/inspect.html#inspect.Parameter)) – The parameter to check.
  * **type_** (`Union`[[`type`](https://docs.python.org/3/builtins/functions.html#type), [`GenericAlias`](https://docs.python.org/3/library/types.html#types.GenericAlias), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – The type to check against.
* **Returns:**
  True if the parameter’s type matches the given type, False otherwise.
* **Return type:**
  [*bool*](https://docs.python.org/3/builtins/functions.html#bool)

Doctests:

```pycon
>>> from inspect import Parameter
>>> param = Parameter('p', Parameter.KEYWORD_ONLY, default=3.14)
>>> is_type(param, float)
True
>>> is_type(param, int)
False
>>> param = Parameter('p', Parameter.KEYWORD_ONLY, default=[1, 2, 3])
>>> is_type(param, list)
True
>>> from typing import List, Union
>>> is_type(param, List[int])
True
>>> is_type(param, List[str])
False
>>> is_type(param, Union[int, List[int]])
True
```

A parameterized generic built from an `collections.abc` type (e.g.
`Sequence[str]`) is itself an instance of `type` – unlike `typing`
generics such as `List[str]` – so it must still fall through to the
`__origin__`-based branch below rather than being handed to
`isinstance(param.default, type_)`, which raises `TypeError` for a
parameterized generic:

```pycon
>>> from collections.abc import Sequence
>>> is_type(param, Sequence[int])
True
>>> is_type(param, Sequence[str])
False
```

An annotation alone is enough, bare or subscripted, optional or not – it matches
`type_` or any subclass of it:

```pycon
>>> annotated = Parameter('p', Parameter.KEYWORD_ONLY, annotation=list[int])
>>> is_type(annotated, Sequence)
True
>>> is_type(annotated, list)
True
>>> is_type(annotated, List[int])
True
>>> is_type(annotated, List[str])
False
>>> is_type(annotated, str)
False
>>> optional = Parameter('p', Parameter.KEYWORD_ONLY, annotation=list | None)
>>> is_type(optional, Sequence)
True
```

### ju.util.resolve_annotations(func, parameters)

Returns `parameters` (a mapping or iterable of `Parameter`) with the string
annotations of `func` evaluated – all of them under
`from __future__ import annotations`. An annotation that can’t be resolved
(e.g. a name only imported under `TYPE_CHECKING`) is left as it was.

```pycon
>>> def f(a: "int", b: "list[float]" = None, c: "Nope" = 1): ...
>>> sig = inspect.signature(f)
>>> [(n, p.annotation) for n, p in resolve_annotations(f, sig.parameters).items()]
[('a', <class 'int'>), ('b', list[float]), ('c', 'Nope')]
```

### ju.util.switch_case(mapping, default)

Returns a function that switches between cases based on a feature

### ju.util.truncate_dict_values(d, , max_list_size=2, max_string_size=66, middle_marker='...')

Returns a new dictionary with the same nested keys structure, where:

- List values are reduced to a maximum size of max_list_size.
- String values longer than max_string_size are truncated in the middle.

### Parameters

d (dict): The input dictionary.
max_list_size (int, optional): Maximum size for lists. Defaults to 2.
max_string_size (int, optional): Maximum length for strings. Defaults to None (no truncation).
middle_marker (str, optional): String to insert in the middle of truncated strings. Defaults to ‘…’.

### Returns

dict: A new dictionary with truncated lists and strings.

This can be useful when you have a large dictionary that you want to investigate,
but printing/logging it takes too much space.

### Example

```pycon
>>> large_dict = {'a': [1, 2, 3, 4, 5], 'b': {'c': [6, 7, 8, 9], 'd': 'A string like this that is too long'}, 'e': [10, 11]}
>>> truncate_dict_values(large_dict, max_list_size=3, max_string_size=20)
{'a': [1, 2, 3], 'b': {'c': [6, 7, 8], 'd': 'A string...too long'}, 'e': [10, 11]}
```

You can use `None` to indicate “no max”:

```pycon
>>> assert (
...     truncate_dict_values(large_dict, max_list_size=None, max_string_size=None)
...     == large_dict
... )
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### ju.util.unwrap_optional(annotation)

Strips `None` out of an `Optional`/union annotation; returns the annotation
unchanged if it is not a union, and the single remaining member if there is one.
`Annotated` and `NewType` wrappers are peeled off too (also on the members).

```pycon
>>> from typing import Optional, Annotated, NewType
>>> unwrap_optional(Optional[list[int]])
list[int]
>>> unwrap_optional(int | None)
<class 'int'>
>>> unwrap_optional(int | str | None)
typing.Union[int, str]
>>> unwrap_optional(list[int])
list[int]
>>> unwrap_optional(Annotated[Optional[list[int]], "meta"])
list[int]
>>> unwrap_optional(Optional[NewType("UserId", int)])
<class 'int'>
```


# _autosummary/ju.viz.html.md

# ju.viz

Visualization functions for Ju.

### Functions

| [`model_digraph`](_autosummary/ju.viz.html.md#ju.viz.model_digraph)(model, \*[, dot, parent])   | Visualize Pydantic models using Graphviz, showing the relationship between models and their fields.   |
|--------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|

### ju.viz.model_digraph(model, , dot=None, parent=None)

Visualize Pydantic models using Graphviz, showing the relationship between models
and their fields.

This function creates a diagram where model nodes are represented as rectangles,
and field nodes are represented as ellipses. Relationships between models and
fields, including nested models, are illustrated with directed edges.

### Parameters

- model: The Pydantic model or an Iterable of Pydantic models to visualize.
- dot: An optional existing Graphviz Digraph object. If not provided, a new one will be created.
- parent: The parent node to which the current model node will be connected.

### Returns

- dot: The Graphviz Digraph object representing the model structure.

Example usage:

(See: [https://github.com/i2mint/ju/discussions/4#discussioncomment-10530803](https://github.com/i2mint/ju/discussions/4#discussioncomment-10530803))

```pycon
>>> from pydantic import BaseModel
>>> from typing import List, Optional
```

```pycon
>>> class Address(BaseModel):
...     street: str
...     city: str
...     state: str
```

```pycon
>>> class User(BaseModel):
...     name: str
...     email: str
...     age: Optional[int] = None
...     addresses: List[Address]
```

```pycon
>>> dot = model_digraph(User)
>>> dot.source
'// Pydantic Model Diagram\ndigraph {\n\tUser [label=User...Address -> Address\n}\n'
```

To save to a file and get the filepath it was saved to:

```pycon
>>> dot.render(f"User_model_graph", format="png", cleanup=True)
'User_model_graph.png'
```

See also the online tool: [https://navneethg.github.io/jsonschemaviewer/](https://navneethg.github.io/jsonschemaviewer/)


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-10-13 15:45 UTC** from commit <a href="https://github.com/i2mint/ju/commit/902b4662ff0d6d173032c3c9be6a54436fb55462"><code>902b466</code></a> on branch <code>master</code>, for **ju 0.1.41** (from <code>setup.cfg</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                  |
|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/i2mint/ju/commit/902b4662ff0d6d173032c3c9be6a54436fb55462"><code>902b4662ff0d6d173032c3c9be6a54436fb55462</code></a> |
| Branch              | <code>master</code>                                                                                                                              |
| Tags at this commit | <code>0.1.41</code>                                                                                                                              |
| Working tree        | clean                                                                                                                                            |
| Remote              | <code>https://github.com/i2mint/ju</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>i2mint/ju</code>                                                                     |
| Run          | <a href="https://github.com/i2mint/ju/actions/runs/38424550537">38424550537</a>            |
| Ref          | <code>refs/heads/master</code>                                                             |
| Event commit | <code>78b8a1696c85d7c8ab30e10ce6c9c8e4ae70103e</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.16  |
| Sphinx   | 9.1.0   |
| docutils | 0.22.4  |
| Python   | 3.12.15 |

## Configuration as resolved

|               |                                                                  |
|---------------|------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>furo</code>)               |
| accent        | <code>#5a479a</code>                                             |
| api_generator | <code>autosummary</code>                                         |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code> |
| agent_outputs | <code>true</code>                                                |
| aggregates    | <code>md</code>                                                  |
| ai_artifacts  | <code>true</code>                                                |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/ju/0.1.41/">0.1.41</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/i2mint/ju && cd ju
git checkout 902b4662ff0d6d173032c3c9be6a54436fb55462
pip install "epythet==0.2.16"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# api.html.md

# API reference

| [`ju`](_autosummary/ju.html.md#module-ju)   | JSON schema Utils   |
|-----------------------------------------------------------------|---------------------|


