# coding: utf-8

"""
    Kubernetes

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: release-1.37
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from collections.abc import Mapping as _Mapping
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.client.models.v1_container_port import V1ContainerPort
from kubernetes.client.models.v1_container_resize_policy import V1ContainerResizePolicy
from kubernetes.client.models.v1_container_restart_rule import V1ContainerRestartRule
from kubernetes.client.models.v1_env_from_source import V1EnvFromSource
from kubernetes.client.models.v1_env_var import V1EnvVar
from kubernetes.client.models.v1_lifecycle import V1Lifecycle
from kubernetes.client.models.v1_probe import V1Probe
from kubernetes.client.models.v1_resource_requirements import V1ResourceRequirements
from kubernetes.client.models.v1_security_context import V1SecurityContext
from kubernetes.client.models.v1_volume_device import V1VolumeDevice
from kubernetes.client.models.v1_volume_mount import V1VolumeMount
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python


_OPENAPI_GENERATOR_TO_DICT = "_openapi_generator_to_dict"


def _get_openapi_to_dict(value: Any) -> Any:
    # Reciprocal function references preserve inherited generated methods
    # without reserving model member names. Checking both directions also
    # rejects overrides whose decorators copy function attributes.
    to_dict = getattr(value, "to_dict", None)
    type_to_dict = getattr(type(value), "to_dict", None)
    if (
        not callable(to_dict)
        or getattr(to_dict, "__func__", None) is not type_to_dict
    ):
        return None

    openapi_to_dict = getattr(
        type_to_dict, _OPENAPI_GENERATOR_TO_DICT, None
    )
    if (
        not callable(openapi_to_dict)
        or getattr(
            openapi_to_dict,
            _OPENAPI_GENERATOR_TO_DICT,
            None,
        ) is not type_to_dict
    ):
        return None
    return openapi_to_dict


def _to_legacy_item(value: Any, serialize: bool) -> Any:
    to_dict = getattr(value, "to_dict", None)
    if _get_openapi_to_dict(value) is not None and callable(to_dict):
        return to_dict(serialize=serialize)
    if callable(to_dict):
        return to_dict()
    return value


def _to_legacy_value(value: Any, serialize: bool) -> Any:
    # python-legacy converted only immediate list elements or dictionary values:
    # https://github.com/OpenAPITools/openapi-generator/blob/c84b949df1a9ec04ba75989cb49b45c940c2f694/modules/openapi-generator/src/main/resources/python-legacy/model.mustache#L203-L231
    if isinstance(value, list):
        return [_to_legacy_item(item, serialize) for item in value]
    if isinstance(value, dict):
        return {
            key: _to_legacy_item(item, serialize)
            for key, item in value.items()
        }
    return _to_legacy_item(value, serialize)


def _to_openapi_value(value: Any) -> Any:
    if isinstance(value, list):
        return [_to_openapi_value(item) for item in value]
    if isinstance(value, dict):
        return {key: _to_openapi_value(item) for key, item in value.items()}

    to_openapi_dict = _get_openapi_to_dict(value)
    if to_openapi_dict is not None:
        return to_openapi_dict(value)

    to_dict = getattr(value, "to_dict", None)
    if callable(to_dict):
        return to_dict()
    return value


class V1EphemeralContainer(BaseModel):
    """
    An EphemeralContainer is a temporary container that you may add to an existing Pod for user-initiated activities such as debugging. Ephemeral containers have no resource or scheduling guarantees, and they will not be restarted when they exit or when a Pod is removed or restarted. The kubelet may evict a Pod if an ephemeral container causes the Pod to exceed its resource allocation.  To add an ephemeral container, use the ephemeralcontainers subresource of an existing Pod. Ephemeral containers may not be removed or restarted.

    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """ # noqa: E501
    args: Optional[List[StrictStr]] = Field(default=None, description="Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell")
    command: Optional[List[StrictStr]] = Field(default=None, description="Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell")
    env: Optional[List[V1EnvVar]] = Field(default=None, description="List of environment variables to set in the container. Cannot be updated.")
    env_from: Optional[List[V1EnvFromSource]] = Field(default=None, validation_alias=AliasChoices("envFrom", "env_from"), serialization_alias="envFrom", description="List of sources to populate environment variables in the container. The keys defined within a source may consist of any printable ASCII characters except '='. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.")
    image: Optional[StrictStr] = Field(default=None, description="Container image name. More info: https://kubernetes.io/docs/concepts/containers/images")
    image_pull_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("imagePullPolicy", "image_pull_policy"), serialization_alias="imagePullPolicy", description="Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images")
    lifecycle: Optional[V1Lifecycle] = None
    liveness_probe: Optional[V1Probe] = Field(default=None, validation_alias=AliasChoices("livenessProbe", "liveness_probe"), serialization_alias="livenessProbe")
    name: StrictStr = Field(description="Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.")
    ports: Optional[List[V1ContainerPort]] = Field(default=None, description="Ports are not allowed for ephemeral containers.")
    readiness_probe: Optional[V1Probe] = Field(default=None, validation_alias=AliasChoices("readinessProbe", "readiness_probe"), serialization_alias="readinessProbe")
    resize_policy: Optional[List[V1ContainerResizePolicy]] = Field(default=None, validation_alias=AliasChoices("resizePolicy", "resize_policy"), serialization_alias="resizePolicy", description="Resources resize policy for the container.")
    resources: Optional[V1ResourceRequirements] = None
    restart_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("restartPolicy", "restart_policy"), serialization_alias="restartPolicy", description="Restart policy for the container to manage the restart behavior of each container within a pod. You cannot set this field on ephemeral containers.")
    restart_policy_rules: Optional[List[V1ContainerRestartRule]] = Field(default=None, validation_alias=AliasChoices("restartPolicyRules", "restart_policy_rules"), serialization_alias="restartPolicyRules", description="Represents a list of rules to be checked to determine if the container should be restarted on exit. You cannot set this field on ephemeral containers.")
    security_context: Optional[V1SecurityContext] = Field(default=None, validation_alias=AliasChoices("securityContext", "security_context"), serialization_alias="securityContext")
    startup_probe: Optional[V1Probe] = Field(default=None, validation_alias=AliasChoices("startupProbe", "startup_probe"), serialization_alias="startupProbe")
    stdin: Optional[StrictBool] = Field(default=None, description="Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.")
    stdin_once: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("stdinOnce", "stdin_once"), serialization_alias="stdinOnce", description="Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false")
    target_container_name: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("targetContainerName", "target_container_name"), serialization_alias="targetContainerName", description="If set, the name of the container from PodSpec that this ephemeral container targets. The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. If not set then the ephemeral container uses the namespaces configured in the Pod spec.  The container runtime must implement support for this feature. If the runtime does not support namespace targeting then the result of setting this field is undefined.")
    termination_message_path: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("terminationMessagePath", "termination_message_path"), serialization_alias="terminationMessagePath", description="Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.")
    termination_message_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("terminationMessagePolicy", "termination_message_policy"), serialization_alias="terminationMessagePolicy", description="Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.")
    tty: Optional[StrictBool] = Field(default=None, description="Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.")
    volume_devices: Optional[List[V1VolumeDevice]] = Field(default=None, validation_alias=AliasChoices("volumeDevices", "volume_devices"), serialization_alias="volumeDevices", description="volumeDevices is the list of block devices to be used by the container.")
    volume_mounts: Optional[List[V1VolumeMount]] = Field(default=None, validation_alias=AliasChoices("volumeMounts", "volume_mounts"), serialization_alias="volumeMounts", description="Pod volumes to mount into the container's filesystem. Subpath mounts are not allowed for ephemeral containers. Cannot be updated.")
    working_dir: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("workingDir", "working_dir"), serialization_alias="workingDir", description="Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "args": "List[str]",
        "command": "List[str]",
        "env": "List[V1EnvVar]",
        "env_from": "List[V1EnvFromSource]",
        "image": "str",
        "image_pull_policy": "str",
        "lifecycle": "V1Lifecycle",
        "liveness_probe": "V1Probe",
        "name": "str",
        "ports": "List[V1ContainerPort]",
        "readiness_probe": "V1Probe",
        "resize_policy": "List[V1ContainerResizePolicy]",
        "resources": "V1ResourceRequirements",
        "restart_policy": "str",
        "restart_policy_rules": "List[V1ContainerRestartRule]",
        "security_context": "V1SecurityContext",
        "startup_probe": "V1Probe",
        "stdin": "bool",
        "stdin_once": "bool",
        "target_container_name": "str",
        "termination_message_path": "str",
        "termination_message_policy": "str",
        "tty": "bool",
        "volume_devices": "List[V1VolumeDevice]",
        "volume_mounts": "List[V1VolumeMount]",
        "working_dir": "str"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "args": "args",
        "command": "command",
        "env": "env",
        "env_from": "envFrom",
        "image": "image",
        "image_pull_policy": "imagePullPolicy",
        "lifecycle": "lifecycle",
        "liveness_probe": "livenessProbe",
        "name": "name",
        "ports": "ports",
        "readiness_probe": "readinessProbe",
        "resize_policy": "resizePolicy",
        "resources": "resources",
        "restart_policy": "restartPolicy",
        "restart_policy_rules": "restartPolicyRules",
        "security_context": "securityContext",
        "startup_probe": "startupProbe",
        "stdin": "stdin",
        "stdin_once": "stdinOnce",
        "target_container_name": "targetContainerName",
        "termination_message_path": "terminationMessagePath",
        "termination_message_policy": "terminationMessagePolicy",
        "tty": "tty",
        "volume_devices": "volumeDevices",
        "volume_mounts": "volumeMounts",
        "working_dir": "workingDir"
    }
    __properties: ClassVar[List[str]] = ["args", "command", "env", "envFrom", "image", "imagePullPolicy", "lifecycle", "livenessProbe", "name", "ports", "readinessProbe", "resizePolicy", "resources", "restartPolicy", "restartPolicyRules", "securityContext", "startupProbe", "stdin", "stdinOnce", "targetContainerName", "terminationMessagePath", "terminationMessagePolicy", "tty", "volumeDevices", "volumeMounts", "workingDir"]

    @classmethod
    def __preprocess_input_names(
        cls,
        obj: Any,
        remove_hidden_storage_names: bool = True,
    ) -> Any:
        if not isinstance(obj, _Mapping):
            return obj
        obj = dict(obj)
        if "envFrom" not in obj and "env_from" in obj:
            obj["envFrom"] = obj["env_from"]
        obj.pop("env_from", None)
        if "imagePullPolicy" not in obj and "image_pull_policy" in obj:
            obj["imagePullPolicy"] = obj["image_pull_policy"]
        obj.pop("image_pull_policy", None)
        if "livenessProbe" not in obj and "liveness_probe" in obj:
            obj["livenessProbe"] = obj["liveness_probe"]
        obj.pop("liveness_probe", None)
        if "readinessProbe" not in obj and "readiness_probe" in obj:
            obj["readinessProbe"] = obj["readiness_probe"]
        obj.pop("readiness_probe", None)
        if "resizePolicy" not in obj and "resize_policy" in obj:
            obj["resizePolicy"] = obj["resize_policy"]
        obj.pop("resize_policy", None)
        if "restartPolicy" not in obj and "restart_policy" in obj:
            obj["restartPolicy"] = obj["restart_policy"]
        obj.pop("restart_policy", None)
        if "restartPolicyRules" not in obj and "restart_policy_rules" in obj:
            obj["restartPolicyRules"] = obj["restart_policy_rules"]
        obj.pop("restart_policy_rules", None)
        if "securityContext" not in obj and "security_context" in obj:
            obj["securityContext"] = obj["security_context"]
        obj.pop("security_context", None)
        if "startupProbe" not in obj and "startup_probe" in obj:
            obj["startupProbe"] = obj["startup_probe"]
        obj.pop("startup_probe", None)
        if "stdinOnce" not in obj and "stdin_once" in obj:
            obj["stdinOnce"] = obj["stdin_once"]
        obj.pop("stdin_once", None)
        if "targetContainerName" not in obj and "target_container_name" in obj:
            obj["targetContainerName"] = obj["target_container_name"]
        obj.pop("target_container_name", None)
        if "terminationMessagePath" not in obj and "termination_message_path" in obj:
            obj["terminationMessagePath"] = obj["termination_message_path"]
        obj.pop("termination_message_path", None)
        if "terminationMessagePolicy" not in obj and "termination_message_policy" in obj:
            obj["terminationMessagePolicy"] = obj["termination_message_policy"]
        obj.pop("termination_message_policy", None)
        if "volumeDevices" not in obj and "volume_devices" in obj:
            obj["volumeDevices"] = obj["volume_devices"]
        obj.pop("volume_devices", None)
        if "volumeMounts" not in obj and "volume_mounts" in obj:
            obj["volumeMounts"] = obj["volume_mounts"]
        obj.pop("volume_mounts", None)
        if "workingDir" not in obj and "working_dir" in obj:
            obj["workingDir"] = obj["working_dir"]
        obj.pop("working_dir", None)
        return obj

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=True,
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self) -> str:
        """For print and pprint"""
        return self.to_str()

    def __eq__(self, other: object) -> bool:
        """Returns true if both objects are equal"""
        if not isinstance(other, V1EphemeralContainer):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other: object) -> bool:
        """Returns true if both objects are not equal"""
        if not isinstance(other, V1EphemeralContainer):
            return True

        return not (self == other)


    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        to_openapi_dict = _get_openapi_to_dict(self)
        if to_openapi_dict is not None:
            return json.dumps(to_jsonable_python(to_openapi_dict(self)))
        return json.dumps(to_jsonable_python(self.to_dict()))

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of V1EphemeralContainer from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self, serialize: bool = False) -> Dict[str, Any]:
        """Return all declared model fields using public or wire names."""
        return {
            ("args" if serialize else "args"): _to_legacy_value(getattr(self, "args", None), serialize),
            ("command" if serialize else "command"): _to_legacy_value(getattr(self, "command", None), serialize),
            ("env" if serialize else "env"): _to_legacy_value(getattr(self, "env", None), serialize),
            ("envFrom" if serialize else "env_from"): _to_legacy_value(getattr(self, "env_from", None), serialize),
            ("image" if serialize else "image"): _to_legacy_value(getattr(self, "image", None), serialize),
            ("imagePullPolicy" if serialize else "image_pull_policy"): _to_legacy_value(getattr(self, "image_pull_policy", None), serialize),
            ("lifecycle" if serialize else "lifecycle"): _to_legacy_value(getattr(self, "lifecycle", None), serialize),
            ("livenessProbe" if serialize else "liveness_probe"): _to_legacy_value(getattr(self, "liveness_probe", None), serialize),
            ("name" if serialize else "name"): _to_legacy_value(getattr(self, "name", None), serialize),
            ("ports" if serialize else "ports"): _to_legacy_value(getattr(self, "ports", None), serialize),
            ("readinessProbe" if serialize else "readiness_probe"): _to_legacy_value(getattr(self, "readiness_probe", None), serialize),
            ("resizePolicy" if serialize else "resize_policy"): _to_legacy_value(getattr(self, "resize_policy", None), serialize),
            ("resources" if serialize else "resources"): _to_legacy_value(getattr(self, "resources", None), serialize),
            ("restartPolicy" if serialize else "restart_policy"): _to_legacy_value(getattr(self, "restart_policy", None), serialize),
            ("restartPolicyRules" if serialize else "restart_policy_rules"): _to_legacy_value(getattr(self, "restart_policy_rules", None), serialize),
            ("securityContext" if serialize else "security_context"): _to_legacy_value(getattr(self, "security_context", None), serialize),
            ("startupProbe" if serialize else "startup_probe"): _to_legacy_value(getattr(self, "startup_probe", None), serialize),
            ("stdin" if serialize else "stdin"): _to_legacy_value(getattr(self, "stdin", None), serialize),
            ("stdinOnce" if serialize else "stdin_once"): _to_legacy_value(getattr(self, "stdin_once", None), serialize),
            ("targetContainerName" if serialize else "target_container_name"): _to_legacy_value(getattr(self, "target_container_name", None), serialize),
            ("terminationMessagePath" if serialize else "termination_message_path"): _to_legacy_value(getattr(self, "termination_message_path", None), serialize),
            ("terminationMessagePolicy" if serialize else "termination_message_policy"): _to_legacy_value(getattr(self, "termination_message_policy", None), serialize),
            ("tty" if serialize else "tty"): _to_legacy_value(getattr(self, "tty", None), serialize),
            ("volumeDevices" if serialize else "volume_devices"): _to_legacy_value(getattr(self, "volume_devices", None), serialize),
            ("volumeMounts" if serialize else "volume_mounts"): _to_legacy_value(getattr(self, "volume_mounts", None), serialize),
            ("workingDir" if serialize else "working_dir"): _to_legacy_value(getattr(self, "working_dir", None), serialize),
        }

    def __openapi_generator_modern_projection(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in env (list)
        _items = []
        if self.env:
            for _item_env in self.env:
                _items.append(_to_openapi_value(_item_env) if _item_env is not None else None)
            _dict['env'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in env_from (list)
        _items = []
        if self.env_from:
            for _item_env_from in self.env_from:
                _items.append(_to_openapi_value(_item_env_from) if _item_env_from is not None else None)
            _dict['envFrom'] = _items
        # override the default output from pydantic by calling `to_dict()` of lifecycle
        if self.lifecycle:
            _dict['lifecycle'] = _to_openapi_value(self.lifecycle)
        # override the default output from pydantic by calling `to_dict()` of liveness_probe
        if self.liveness_probe:
            _dict['livenessProbe'] = _to_openapi_value(self.liveness_probe)
        # override the default output from pydantic by calling `to_dict()` of each item in ports (list)
        _items = []
        if self.ports:
            for _item_ports in self.ports:
                _items.append(_to_openapi_value(_item_ports) if _item_ports is not None else None)
            _dict['ports'] = _items
        # override the default output from pydantic by calling `to_dict()` of readiness_probe
        if self.readiness_probe:
            _dict['readinessProbe'] = _to_openapi_value(self.readiness_probe)
        # override the default output from pydantic by calling `to_dict()` of each item in resize_policy (list)
        _items = []
        if self.resize_policy:
            for _item_resize_policy in self.resize_policy:
                _items.append(_to_openapi_value(_item_resize_policy) if _item_resize_policy is not None else None)
            _dict['resizePolicy'] = _items
        # override the default output from pydantic by calling `to_dict()` of resources
        if self.resources:
            _dict['resources'] = _to_openapi_value(self.resources)
        # override the default output from pydantic by calling `to_dict()` of each item in restart_policy_rules (list)
        _items = []
        if self.restart_policy_rules:
            for _item_restart_policy_rules in self.restart_policy_rules:
                _items.append(_to_openapi_value(_item_restart_policy_rules) if _item_restart_policy_rules is not None else None)
            _dict['restartPolicyRules'] = _items
        # override the default output from pydantic by calling `to_dict()` of security_context
        if self.security_context:
            _dict['securityContext'] = _to_openapi_value(self.security_context)
        # override the default output from pydantic by calling `to_dict()` of startup_probe
        if self.startup_probe:
            _dict['startupProbe'] = _to_openapi_value(self.startup_probe)
        # override the default output from pydantic by calling `to_dict()` of each item in volume_devices (list)
        _items = []
        if self.volume_devices:
            for _item_volume_devices in self.volume_devices:
                _items.append(_to_openapi_value(_item_volume_devices) if _item_volume_devices is not None else None)
            _dict['volumeDevices'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in volume_mounts (list)
        _items = []
        if self.volume_mounts:
            for _item_volume_mounts in self.volume_mounts:
                _items.append(_to_openapi_value(_item_volume_mounts) if _item_volume_mounts is not None else None)
            _dict['volumeMounts'] = _items
        return _dict

    setattr(
        to_dict,
        _OPENAPI_GENERATOR_TO_DICT,
        __openapi_generator_modern_projection,
    )
    setattr(
        __openapi_generator_modern_projection,
        _OPENAPI_GENERATOR_TO_DICT,
        to_dict,
    )
    del __openapi_generator_modern_projection

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of V1EphemeralContainer from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        obj = _cast(
            Dict[str, Any],
            cls.__preprocess_input_names(
                obj,
                remove_hidden_storage_names=True,
            ),
        )

        _obj = cls.model_validate({
            "args": obj.get("args"),
            "command": obj.get("command"),
            "env": [V1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None,
            "envFrom": [V1EnvFromSource.from_dict(_item) for _item in obj["envFrom"]] if obj.get("envFrom") is not None else None,
            "image": obj.get("image"),
            "imagePullPolicy": obj.get("imagePullPolicy"),
            "lifecycle": V1Lifecycle.from_dict(obj["lifecycle"]) if obj.get("lifecycle") is not None else None,
            "livenessProbe": V1Probe.from_dict(obj["livenessProbe"]) if obj.get("livenessProbe") is not None else None,
            "name": obj.get("name"),
            "ports": [V1ContainerPort.from_dict(_item) for _item in obj["ports"]] if obj.get("ports") is not None else None,
            "readinessProbe": V1Probe.from_dict(obj["readinessProbe"]) if obj.get("readinessProbe") is not None else None,
            "resizePolicy": [V1ContainerResizePolicy.from_dict(_item) for _item in obj["resizePolicy"]] if obj.get("resizePolicy") is not None else None,
            "resources": V1ResourceRequirements.from_dict(obj["resources"]) if obj.get("resources") is not None else None,
            "restartPolicy": obj.get("restartPolicy"),
            "restartPolicyRules": [V1ContainerRestartRule.from_dict(_item) for _item in obj["restartPolicyRules"]] if obj.get("restartPolicyRules") is not None else None,
            "securityContext": V1SecurityContext.from_dict(obj["securityContext"]) if obj.get("securityContext") is not None else None,
            "startupProbe": V1Probe.from_dict(obj["startupProbe"]) if obj.get("startupProbe") is not None else None,
            "stdin": obj.get("stdin"),
            "stdinOnce": obj.get("stdinOnce"),
            "targetContainerName": obj.get("targetContainerName"),
            "terminationMessagePath": obj.get("terminationMessagePath"),
            "terminationMessagePolicy": obj.get("terminationMessagePolicy"),
            "tty": obj.get("tty"),
            "volumeDevices": [V1VolumeDevice.from_dict(_item) for _item in obj["volumeDevices"]] if obj.get("volumeDevices") is not None else None,
            "volumeMounts": [V1VolumeMount.from_dict(_item) for _item in obj["volumeMounts"]] if obj.get("volumeMounts") is not None else None,
            "workingDir": obj.get("workingDir")
        })
        return _obj
