At the time I'm posting this answer, the stable release of Pydantic is version 2.7.x
The PrivateAttr class in Pydantic 2.x provides a solution. You can mark one or more fields in your model class as private by prefixing each field name with an underscore and assigning that field to PrivateAttr. Here is an example:
class ExampleModelClassAlpha(BaseModel):
name: str
power_animal: Optional[str] = None
_private: str = PrivateAttr(default=None)
Here is a simple Pytest that demonstrates how it works:
import logging
import pytest
from typing import Optional
from pydantic import BaseModel, PrivateAttr
logger = logging.getLogger(__name__)
class ExampleModelClassAlpha(BaseModel):
name: str
power_animal: Optional[str] = None
_private: str = PrivateAttr(default=None)
# -------------------------------------------------------------------------------------------------
# noinspection PyArgumentList
@pytest.mark.unit
class TestSummaOpenapiModel:
# ---------------------------------------------------------------------------------------------
def test_x(self):
emc_alpha: ExampleModelClassAlpha = ExampleModelClassAlpha(
name='John Smith',
_private='this is a private field that I want to exclude from the JSON'
)
the_json_string: str = emc_alpha.model_dump_json(indent=4, exclude_none=True)
logger.info("\n%s", the_json_string)
assert 'power_animal' not in the_json_string
assert 'this is a private field' not in the_json_string
The test should pass, and the output should look like this:
{
"name": "John Smith"
}
__get_pydantic_json_schema__
which isn't too hard but does require about 3 different imports from the bowels of Pydantic. https://docs.pydantic.dev/latest/usage/json_schema/#modifying-the-schema – Wilkietyping.ClassVar
so that "Attributes annotated withtyping.ClassVar
are properly treated by Pydantic as class variables, and will not become fields on model instances". So just wrap the field type withClassVar
e.g. instead offoo: int = 1
usefoo: ClassVar[int] = 1
. So this excludes fields from the model, and the schema, but it also removes the field from instances, which may not be what you want. – Wilkie