prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Importing code generator changes behavior of pyyaml
  When importing ``datamodel_code_generator``, the behaviour of ``pyyaml`` is changed after the import, datetime objects suddenly are deserialized from yaml as `str` whereas before they were deserialized as `datetime` objects.
  
  ## Steps to reproduce:
  ### create clean venv
  ```bash
  python3 -m venv blub
  blub/bin/pip install datamodel-code-generator pyyaml
  ```
  
  ### Run this reproducer with the interpreter from the venv
  ```python
  import yaml
  import tempfile
  import datetime
  
  tmp=tempfile.NamedTemporaryFile(mode='w')
  
  def write_read():
      tmp=tempfile.NamedTemporaryFile(mode='w')
      yaml.safe_dump({"datetime": datetime.datetime.now()}, tmp)
      dumped_reloaded = yaml.safe_load(open(tmp.name,"r"))
      print(dumped_reloaded)
  
  print("before importing datamodel-code-generator:")
  write_read()
  
  import datamodel_code_generator
  print("\nafter importing datamodel-code-generator:")
  write_read()
  ```
  
  **Actual output:** (time string + object may change depending on run time)
  ```
  before importing datamodel-code-generator:
  {'datetime': datetime.datetime(2024, 1, 30, 9, 51, 19, 612368)}
  
  after importing datamodel-code-generator:
  {'datetime': '2024-01-30 09:51:20.019991'}
  ```
  
  **Expected output:**  (time string + object may change depending on run time):
  ```
  before importing datamodel-code-generator:
  {'datetime': datetime.datetime(2024, 1, 30, 9, 51, 19, 612368)}
  
  after importing datamodel-code-generator:
  {'datetime': datetime.datetime(2024, 1, 30, 9, 51, 20, 019991)}
  ```
  
  The reason seems to be that the SafeLoader of ``yaml`` is modified globally by ``datamodel-code-generator``
  https://github.com/koxudaxi/datamodel-code-generator/blob/acc6bf604b13626f22fc123d72ae08ff0a114155/datamodel_code_generator/util.py#L72
  
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `datamodel_code_generator/util.py`
  Content:
  ```
  1 from __future__ import annotations
  2 
  3 from pathlib import Path
  4 from typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar
  5 
  6 import pydantic
  7 from packaging import version
  8 from pydantic import BaseModel as _BaseModel
  9 
  10 PYDANTIC_VERSION = version.parse(
  11     pydantic.VERSION if isinstance(pydantic.VERSION, str) else str(pydantic.VERSION)
  12 )
  13 
  14 PYDANTIC_V2: bool = PYDANTIC_VERSION >= version.parse('2.0b3')
  15 
  16 if TYPE_CHECKING:
  17     cached_property = property
  18     from yaml import SafeLoader
  19 
  20     Protocol = object
  21     runtime_checkable: Callable[..., Any]
  22 
  23     from typing_extensions import Literal
  24 
  25     def load_toml(path: Path) -> Dict[str, Any]:
  26         ...
  27 
  28 else:
  29     try:
  30         from typing import Protocol
  31     except ImportError:
  32         from typing_extensions import Protocol  # noqa
  33     try:
  34         from typing import runtime_checkable
  35     except ImportError:
  36         from typing_extensions import runtime_checkable  # noqa
  37     try:
  38         from yaml import CSafeLoader as SafeLoader
  39     except ImportError:  # pragma: no cover
  40         from yaml import SafeLoader
  41 
  42     try:
  43         from functools import cached_property
  44     except ImportError:
  45         _NOT_FOUND = object()
  46 
  47         class cached_property:
  48             def __init__(self, func: Callable) -> None:
  49                 self.func: Callable = func
  50                 self.__doc__: Any = func.__doc__
  51 
  52             def __get__(self, instance: Any, owner: Any = None) -> Any:
  53                 value = instance.__dict__.get(self.func.__name__, _NOT_FOUND)
  54                 if value is _NOT_FOUND:  # pragma: no cover
  55                     value = instance.__dict__[self.func.__name__] = self.func(instance)
  56                 return value
  57 
  58     try:
  59         import tomllib
  60 
  61         def load_toml(path: Path) -> Dict[str, Any]:
  62             with path.open('rb') as f:
  63                 return tomllib.load(f)
  64 
  65     except ImportError:
  66         import toml
  67 
  68         def load_toml(path: Path) -> Dict[str, Any]:
  69             return toml.load(path)
  70 
  71 
  72 SafeLoader.yaml_constructors[
  73     'tag:yaml.org,2002:timestamp'
  74 ] = SafeLoader.yaml_constructors['tag:yaml.org,2002:str']
  75 
  76 Model = TypeVar('Model', bound=_BaseModel)
  77 
  78 
  79 def model_validator(
  80     mode: Literal['before', 'after'] = 'after',
  81 ) -> Callable[[Callable[[Model, Any], Any]], Callable[[Model, Any], Any]]:
  82     def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:
  83         if PYDANTIC_V2:
  84             from pydantic import model_validator as model_validator_v2
  85 
  86             return model_validator_v2(mode=mode)(method)  # type: ignore
  87         else:
  88             from pydantic import root_validator
  89 
  90             return root_validator(method, pre=mode == 'before')  # type: ignore
  91 
  92     return inner
  93 
  94 
  95 def field_validator(
  96     field_name: str,
  97     *fields: str,
  98     mode: Literal['before', 'after'] = 'after',
  99 ) -> Callable[[Any], Callable[[Model, Any], Any]]:
  100     def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:
  101         if PYDANTIC_V2:
  102             from pydantic import field_validator as field_validator_v2
  103 
  104             return field_validator_v2(field_name, *fields, mode=mode)(method)  # type: ignore
  105         else:
  106             from pydantic import validator
  107 
  108             return validator(field_name, *fields, pre=mode == 'before')(method)  # type: ignore
  109 
  110     return inner
  111 
  112 
  113 if PYDANTIC_V2:
  114     from pydantic import ConfigDict as ConfigDict
  115 else:
  116     ConfigDict = dict  # type: ignore
  117 
  118 
  119 class BaseModel(_BaseModel):
  120     if PYDANTIC_V2:
  121         model_config = ConfigDict(strict=False)
  122
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/datamodel_code_generator/util.py b/datamodel_code_generator/util.py
  --- a/datamodel_code_generator/util.py
  +++ b/datamodel_code_generator/util.py
  @@ -1,5 +1,6 @@
   from __future__ import annotations
   
  +import copy
   from pathlib import Path
   from typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar
   
  @@ -69,9 +70,13 @@
               return toml.load(path)
   
   
  -SafeLoader.yaml_constructors[
  -    'tag:yaml.org,2002:timestamp'
  -] = SafeLoader.yaml_constructors['tag:yaml.org,2002:str']
  +SafeLoaderTemp = copy.deepcopy(SafeLoader)
  +SafeLoaderTemp.yaml_constructors = copy.deepcopy(SafeLoader.yaml_constructors)
  +SafeLoaderTemp.add_constructor(
  +    'tag:yaml.org,2002:timestamp',
  +    SafeLoaderTemp.yaml_constructors['tag:yaml.org,2002:str'],
  +)
  +SafeLoader = SafeLoaderTemp
   
   Model = TypeVar('Model', bound=_BaseModel)
  
verification_info: {"golden_diff": "diff --git a/datamodel_code_generator/util.py b/datamodel_code_generator/util.py\n--- a/datamodel_code_generator/util.py\n+++ b/datamodel_code_generator/util.py\n@@ -1,5 +1,6 @@\n from __future__ import annotations\n \n+import copy\n from pathlib import Path\n from typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar\n \n@@ -69,9 +70,13 @@\n             return toml.load(path)\n \n \n-SafeLoader.yaml_constructors[\n-    'tag:yaml.org,2002:timestamp'\n-] = SafeLoader.yaml_constructors['tag:yaml.org,2002:str']\n+SafeLoaderTemp = copy.deepcopy(SafeLoader)\n+SafeLoaderTemp.yaml_constructors = copy.deepcopy(SafeLoader.yaml_constructors)\n+SafeLoaderTemp.add_constructor(\n+    'tag:yaml.org,2002:timestamp',\n+    SafeLoaderTemp.yaml_constructors['tag:yaml.org,2002:str'],\n+)\n+SafeLoader = SafeLoaderTemp\n \n Model = TypeVar('Model', bound=_BaseModel)\n", "issue": "Importing code generator changes behavior of pyyaml\nWhen importing ``datamodel_code_generator``, the behaviour of ``pyyaml`` is changed after the import, datetime objects suddenly are deserialized from yaml as `str` whereas before they were deserialized as `datetime` objects.\r\n\r\n## Steps to reproduce:\r\n### create clean venv\r\n```bash\r\npython3 -m venv blub\r\nblub/bin/pip install datamodel-code-generator pyyaml\r\n```\r\n\r\n### Run this reproducer with the interpreter from the venv\r\n```python\r\nimport yaml\r\nimport tempfile\r\nimport datetime\r\n\r\ntmp=tempfile.NamedTemporaryFile(mode='w')\r\n\r\ndef write_read():\r\n    tmp=tempfile.NamedTemporaryFile(mode='w')\r\n    yaml.safe_dump({\"datetime\": datetime.datetime.now()}, tmp)\r\n    dumped_reloaded = yaml.safe_load(open(tmp.name,\"r\"))\r\n    print(dumped_reloaded)\r\n\r\nprint(\"before importing datamodel-code-generator:\")\r\nwrite_read()\r\n\r\nimport datamodel_code_generator\r\nprint(\"\\nafter importing datamodel-code-generator:\")\r\nwrite_read()\r\n```\r\n\r\n**Actual output:** (time string + object may change depending on run time)\r\n```\r\nbefore importing datamodel-code-generator:\r\n{'datetime': datetime.datetime(2024, 1, 30, 9, 51, 19, 612368)}\r\n\r\nafter importing datamodel-code-generator:\r\n{'datetime': '2024-01-30 09:51:20.019991'}\r\n```\r\n\r\n**Expected output:**  (time string + object may change depending on run time):\r\n```\r\nbefore importing datamodel-code-generator:\r\n{'datetime': datetime.datetime(2024, 1, 30, 9, 51, 19, 612368)}\r\n\r\nafter importing datamodel-code-generator:\r\n{'datetime': datetime.datetime(2024, 1, 30, 9, 51, 20, 019991)}\r\n```\r\n\r\nThe reason seems to be that the SafeLoader of ``yaml`` is modified globally by ``datamodel-code-generator``\r\nhttps://github.com/koxudaxi/datamodel-code-generator/blob/acc6bf604b13626f22fc123d72ae08ff0a114155/datamodel_code_generator/util.py#L72\r\n\r\n\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar\n\nimport pydantic\nfrom packaging import version\nfrom pydantic import BaseModel as _BaseModel\n\nPYDANTIC_VERSION = version.parse(\n    pydantic.VERSION if isinstance(pydantic.VERSION, str) else str(pydantic.VERSION)\n)\n\nPYDANTIC_V2: bool = PYDANTIC_VERSION >= version.parse('2.0b3')\n\nif TYPE_CHECKING:\n    cached_property = property\n    from yaml import SafeLoader\n\n    Protocol = object\n    runtime_checkable: Callable[..., Any]\n\n    from typing_extensions import Literal\n\n    def load_toml(path: Path) -> Dict[str, Any]:\n        ...\n\nelse:\n    try:\n        from typing import Protocol\n    except ImportError:\n        from typing_extensions import Protocol  # noqa\n    try:\n        from typing import runtime_checkable\n    except ImportError:\n        from typing_extensions import runtime_checkable  # noqa\n    try:\n        from yaml import CSafeLoader as SafeLoader\n    except ImportError:  # pragma: no cover\n        from yaml import SafeLoader\n\n    try:\n        from functools import cached_property\n    except ImportError:\n        _NOT_FOUND = object()\n\n        class cached_property:\n            def __init__(self, func: Callable) -> None:\n                self.func: Callable = func\n                self.__doc__: Any = func.__doc__\n\n            def __get__(self, instance: Any, owner: Any = None) -> Any:\n                value = instance.__dict__.get(self.func.__name__, _NOT_FOUND)\n                if value is _NOT_FOUND:  # pragma: no cover\n                    value = instance.__dict__[self.func.__name__] = self.func(instance)\n                return value\n\n    try:\n        import tomllib\n\n        def load_toml(path: Path) -> Dict[str, Any]:\n            with path.open('rb') as f:\n                return tomllib.load(f)\n\n    except ImportError:\n        import toml\n\n        def load_toml(path: Path) -> Dict[str, Any]:\n            return toml.load(path)\n\n\nSafeLoader.yaml_constructors[\n    'tag:yaml.org,2002:timestamp'\n] = SafeLoader.yaml_constructors['tag:yaml.org,2002:str']\n\nModel = TypeVar('Model', bound=_BaseModel)\n\n\ndef model_validator(\n    mode: Literal['before', 'after'] = 'after',\n) -> Callable[[Callable[[Model, Any], Any]], Callable[[Model, Any], Any]]:\n    def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:\n        if PYDANTIC_V2:\n            from pydantic import model_validator as model_validator_v2\n\n            return model_validator_v2(mode=mode)(method)  # type: ignore\n        else:\n            from pydantic import root_validator\n\n            return root_validator(method, pre=mode == 'before')  # type: ignore\n\n    return inner\n\n\ndef field_validator(\n    field_name: str,\n    *fields: str,\n    mode: Literal['before', 'after'] = 'after',\n) -> Callable[[Any], Callable[[Model, Any], Any]]:\n    def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:\n        if PYDANTIC_V2:\n            from pydantic import field_validator as field_validator_v2\n\n            return field_validator_v2(field_name, *fields, mode=mode)(method)  # type: ignore\n        else:\n            from pydantic import validator\n\n            return validator(field_name, *fields, pre=mode == 'before')(method)  # type: ignore\n\n    return inner\n\n\nif PYDANTIC_V2:\n    from pydantic import ConfigDict as ConfigDict\nelse:\n    ConfigDict = dict  # type: ignore\n\n\nclass BaseModel(_BaseModel):\n    if PYDANTIC_V2:\n        model_config = ConfigDict(strict=False)\n", "path": "datamodel_code_generator/util.py"}], "after_files": [{"content": "from __future__ import annotations\n\nimport copy\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar\n\nimport pydantic\nfrom packaging import version\nfrom pydantic import BaseModel as _BaseModel\n\nPYDANTIC_VERSION = version.parse(\n    pydantic.VERSION if isinstance(pydantic.VERSION, str) else str(pydantic.VERSION)\n)\n\nPYDANTIC_V2: bool = PYDANTIC_VERSION >= version.parse('2.0b3')\n\nif TYPE_CHECKING:\n    cached_property = property\n    from yaml import SafeLoader\n\n    Protocol = object\n    runtime_checkable: Callable[..., Any]\n\n    from typing_extensions import Literal\n\n    def load_toml(path: Path) -> Dict[str, Any]:\n        ...\n\nelse:\n    try:\n        from typing import Protocol\n    except ImportError:\n        from typing_extensions import Protocol  # noqa\n    try:\n        from typing import runtime_checkable\n    except ImportError:\n        from typing_extensions import runtime_checkable  # noqa\n    try:\n        from yaml import CSafeLoader as SafeLoader\n    except ImportError:  # pragma: no cover\n        from yaml import SafeLoader\n\n    try:\n        from functools import cached_property\n    except ImportError:\n        _NOT_FOUND = object()\n\n        class cached_property:\n            def __init__(self, func: Callable) -> None:\n                self.func: Callable = func\n                self.__doc__: Any = func.__doc__\n\n            def __get__(self, instance: Any, owner: Any = None) -> Any:\n                value = instance.__dict__.get(self.func.__name__, _NOT_FOUND)\n                if value is _NOT_FOUND:  # pragma: no cover\n                    value = instance.__dict__[self.func.__name__] = self.func(instance)\n                return value\n\n    try:\n        import tomllib\n\n        def load_toml(path: Path) -> Dict[str, Any]:\n            with path.open('rb') as f:\n                return tomllib.load(f)\n\n    except ImportError:\n        import toml\n\n        def load_toml(path: Path) -> Dict[str, Any]:\n            return toml.load(path)\n\n\nSafeLoaderTemp = copy.deepcopy(SafeLoader)\nSafeLoaderTemp.yaml_constructors = copy.deepcopy(SafeLoader.yaml_constructors)\nSafeLoaderTemp.add_constructor(\n    'tag:yaml.org,2002:timestamp',\n    SafeLoaderTemp.yaml_constructors['tag:yaml.org,2002:str'],\n)\nSafeLoader = SafeLoaderTemp\n\nModel = TypeVar('Model', bound=_BaseModel)\n\n\ndef model_validator(\n    mode: Literal['before', 'after'] = 'after',\n) -> Callable[[Callable[[Model, Any], Any]], Callable[[Model, Any], Any]]:\n    def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:\n        if PYDANTIC_V2:\n            from pydantic import model_validator as model_validator_v2\n\n            return model_validator_v2(mode=mode)(method)  # type: ignore\n        else:\n            from pydantic import root_validator\n\n            return root_validator(method, pre=mode == 'before')  # type: ignore\n\n    return inner\n\n\ndef field_validator(\n    field_name: str,\n    *fields: str,\n    mode: Literal['before', 'after'] = 'after',\n) -> Callable[[Any], Callable[[Model, Any], Any]]:\n    def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:\n        if PYDANTIC_V2:\n            from pydantic import field_validator as field_validator_v2\n\n            return field_validator_v2(field_name, *fields, mode=mode)(method)  # type: ignore\n        else:\n            from pydantic import validator\n\n            return validator(field_name, *fields, pre=mode == 'before')(method)  # type: ignore\n\n    return inner\n\n\nif PYDANTIC_V2:\n    from pydantic import ConfigDict as ConfigDict\nelse:\n    ConfigDict = dict  # type: ignore\n\n\nclass BaseModel(_BaseModel):\n    if PYDANTIC_V2:\n        model_config = ConfigDict(strict=False)\n", "path": "datamodel_code_generator/util.py"}]}