prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Use `Optional` for nullable fields?
  If a field is `nullable` (https://swagger.io/docs/specification/data-models/data-types/#null) use the `Optional` type hint (https://pydantic-docs.helpmanual.io/#pep-484-types)
  
  --- 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/__main__.py`
  Content:
  ```
  1 #! /usr/bin/env python
  2 
  3 """
  4 Main function.
  5 """
  6 
  7 import os
  8 import sys
  9 from argparse import ArgumentParser, FileType
  10 from enum import IntEnum
  11 from typing import Optional, Sequence
  12 
  13 import argcomplete
  14 
  15 from datamodel_code_generator.model import BaseModel, DataModelField
  16 from datamodel_code_generator.parser.openapi import Parser
  17 
  18 
  19 class Exit(IntEnum):
  20     """Exit reasons."""
  21 
  22     OK = 0
  23     ERROR = 1
  24 
  25 
  26 arg_parser = ArgumentParser()
  27 arg_parser.add_argument("--input", help="Open API YAML file")
  28 arg_parser.add_argument("--output", help="Output file", type=FileType("wt"), default=sys.stdout)
  29 
  30 
  31 def main(args: Optional[Sequence[str]] = None) -> Exit:
  32     """Main function."""
  33 
  34     # add cli completion support
  35     argcomplete.autocomplete(arg_parser)
  36 
  37     if args is None:
  38         args = sys.argv[1:]
  39 
  40     args = arg_parser.parse_args(args)
  41 
  42     input_filename = os.path.abspath(os.path.expanduser(args.input))
  43     parser = Parser(BaseModel, DataModelField, filename=input_filename)
  44     with args.output as file:
  45         parser.parse(file)
  46         print(parser.parse(), file=file)
  47 
  48     return Exit.OK
  49 
  50 
  51 if __name__ == "__main__":
  52     sys.exit(main())
  53
  ```
  
  Path: `datamodel_code_generator/parser/openapi.py`
  Content:
  ```
  1 from dataclasses import Field, dataclass
  2 from typing import Dict, List, Optional, Set, Type, Union
  3 
  4 from prance import BaseParser, ResolvingParser
  5 
  6 from ..model import CustomRootType, DataModel, DataModelField
  7 from ..model.base import TemplateBase
  8 
  9 
  10 @dataclass
  11 class DataType:
  12     type_hint: str
  13     format: Optional[str] = None
  14     default: Optional[Field] = None
  15 
  16 
  17 data_types: Dict[str, Dict[str, DataType]] = {
  18     # https://docs.python.org/3.7/library/json.html#encoders-and-decoders
  19     'integer':
  20         {
  21             'int32': DataType(type_hint='int'),
  22             'int64': DataType(type_hint='int')
  23         },
  24     'number':
  25         {
  26             'float': DataType(type_hint='float'),
  27             'double': DataType(type_hint='float')
  28         },
  29     'string':
  30         {'default': DataType(type_hint='str'),
  31          'byte': DataType(type_hint='str'),
  32          'binary': DataType(type_hint='bytes')
  33          },
  34     #               'data': date,}, #As defined by full-date - RFC3339
  35     'boolean': {'default': DataType(type_hint='bool')}
  36 }
  37 
  38 
  39 def get_data_type(_type, format =None) -> DataType:
  40     _format: str = format or 'default'
  41     return data_types[_type][_format]
  42 
  43 
  44 def dump_templates(templates: Union[TemplateBase, List[TemplateBase]]) -> str:
  45     if isinstance(templates, TemplateBase):
  46         templates = [templates]
  47     return '\n\n'.join(str(m) for m in templates)
  48 
  49 
  50 class Parser:
  51     def __init__(self, data_model_type: Type[DataModel], data_model_field_type: Type[DataModelField],
  52                  filename: str = "api.yaml"):
  53         self.base_parser = BaseParser(filename, backend='openapi-spec-validator')
  54         self.resolving_parser = ResolvingParser(filename, backend='openapi-spec-validator')
  55 
  56         self.data_model_type: Type[DataModel] = data_model_type
  57         self.data_model_field_type: Type[DataModelField] = data_model_field_type
  58         self.models = []
  59 
  60     def parse_object(self, name: str, obj: Dict) -> str:
  61         requires: Set[str] = set(obj.get('required', []))
  62         d_list: List[DataModelField] = []
  63         for field_name, filed in obj['properties'].items():
  64             # object
  65             d_list.append(self.data_model_field_type(
  66                 name=field_name, type_hint=get_data_type(filed["type"],
  67                                                          filed.get("format")).type_hint,
  68                 required=field_name in requires))
  69         return dump_templates(self.data_model_type(name, fields=d_list))
  70 
  71     def parse_array(self, name: str, obj: Dict) -> str:
  72         templates: List[TemplateBase] = []
  73         # continue
  74         if '$ref' in obj['items']:
  75             _type: str = f"List[{obj['items']['$ref'].split('/')[-1]}]"
  76             templates.append(CustomRootType(name, _type))
  77         elif 'properties' in obj['items']:
  78             self.parse_object(name[:-1], obj['items'])
  79             templates.append(CustomRootType(name, f'List[{name[:-1]}]'))
  80         return dump_templates(templates)
  81 
  82     def parse(self) -> str:
  83         parsed_objects: List[str] = []
  84         for obj_name, obj in self.base_parser.specification['components']['schemas'].items():
  85             if 'properties' in obj:
  86                 parsed_objects.append(self.parse_object(obj_name, obj))
  87             elif 'items' in obj:
  88                 parsed_objects.append(self.parse_array(obj_name, obj))
  89 
  90         return '\n\n\n'.join(parsed_objects)
  91
  ```
  --- 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/__main__.py b/datamodel_code_generator/__main__.py
  --- a/datamodel_code_generator/__main__.py
  +++ b/datamodel_code_generator/__main__.py
  @@ -7,6 +7,7 @@
   import os
   import sys
   from argparse import ArgumentParser, FileType
  +from datetime import datetime, timezone
   from enum import IntEnum
   from typing import Optional, Sequence
   
  @@ -41,8 +42,20 @@
   
       input_filename = os.path.abspath(os.path.expanduser(args.input))
       parser = Parser(BaseModel, DataModelField, filename=input_filename)
  +    timestamp = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
  +    header = f"""\
  +# generated by datamodel-codegen:
  +#   filename:  {os.path.split(input_filename)[1]}
  +#   timestamp: {timestamp}
  +
  +from typing import List, Optional
  +
  +from pydantic import BaseModel
  +
  +
  +"""
       with args.output as file:
  -        parser.parse(file)
  +        print(header, file=file)
           print(parser.parse(), file=file)
   
       return Exit.OK
  diff --git a/datamodel_code_generator/parser/openapi.py b/datamodel_code_generator/parser/openapi.py
  --- a/datamodel_code_generator/parser/openapi.py
  +++ b/datamodel_code_generator/parser/openapi.py
  @@ -1,6 +1,6 @@
  -from dataclasses import Field, dataclass
   from typing import Dict, List, Optional, Set, Type, Union
   
  +from dataclasses import Field, dataclass
   from prance import BaseParser, ResolvingParser
   
   from ..model import CustomRootType, DataModel, DataModelField
  
verification_info: {"golden_diff": "diff --git a/datamodel_code_generator/__main__.py b/datamodel_code_generator/__main__.py\n--- a/datamodel_code_generator/__main__.py\n+++ b/datamodel_code_generator/__main__.py\n@@ -7,6 +7,7 @@\n import os\n import sys\n from argparse import ArgumentParser, FileType\n+from datetime import datetime, timezone\n from enum import IntEnum\n from typing import Optional, Sequence\n \n@@ -41,8 +42,20 @@\n \n     input_filename = os.path.abspath(os.path.expanduser(args.input))\n     parser = Parser(BaseModel, DataModelField, filename=input_filename)\n+    timestamp = datetime.now(timezone.utc).replace(microsecond=0).isoformat()\n+    header = f\"\"\"\\\n+# generated by datamodel-codegen:\n+#   filename:  {os.path.split(input_filename)[1]}\n+#   timestamp: {timestamp}\n+\n+from typing import List, Optional\n+\n+from pydantic import BaseModel\n+\n+\n+\"\"\"\n     with args.output as file:\n-        parser.parse(file)\n+        print(header, file=file)\n         print(parser.parse(), file=file)\n \n     return Exit.OK\ndiff --git a/datamodel_code_generator/parser/openapi.py b/datamodel_code_generator/parser/openapi.py\n--- a/datamodel_code_generator/parser/openapi.py\n+++ b/datamodel_code_generator/parser/openapi.py\n@@ -1,6 +1,6 @@\n-from dataclasses import Field, dataclass\n from typing import Dict, List, Optional, Set, Type, Union\n \n+from dataclasses import Field, dataclass\n from prance import BaseParser, ResolvingParser\n \n from ..model import CustomRootType, DataModel, DataModelField\n", "issue": "Use `Optional` for nullable fields?\nIf a field is `nullable` (https://swagger.io/docs/specification/data-models/data-types/#null) use the `Optional` type hint (https://pydantic-docs.helpmanual.io/#pep-484-types)\n", "before_files": [{"content": "#! /usr/bin/env python\n\n\"\"\"\nMain function.\n\"\"\"\n\nimport os\nimport sys\nfrom argparse import ArgumentParser, FileType\nfrom enum import IntEnum\nfrom typing import Optional, Sequence\n\nimport argcomplete\n\nfrom datamodel_code_generator.model import BaseModel, DataModelField\nfrom datamodel_code_generator.parser.openapi import Parser\n\n\nclass Exit(IntEnum):\n    \"\"\"Exit reasons.\"\"\"\n\n    OK = 0\n    ERROR = 1\n\n\narg_parser = ArgumentParser()\narg_parser.add_argument(\"--input\", help=\"Open API YAML file\")\narg_parser.add_argument(\"--output\", help=\"Output file\", type=FileType(\"wt\"), default=sys.stdout)\n\n\ndef main(args: Optional[Sequence[str]] = None) -> Exit:\n    \"\"\"Main function.\"\"\"\n\n    # add cli completion support\n    argcomplete.autocomplete(arg_parser)\n\n    if args is None:\n        args = sys.argv[1:]\n\n    args = arg_parser.parse_args(args)\n\n    input_filename = os.path.abspath(os.path.expanduser(args.input))\n    parser = Parser(BaseModel, DataModelField, filename=input_filename)\n    with args.output as file:\n        parser.parse(file)\n        print(parser.parse(), file=file)\n\n    return Exit.OK\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n", "path": "datamodel_code_generator/__main__.py"}, {"content": "from dataclasses import Field, dataclass\nfrom typing import Dict, List, Optional, Set, Type, Union\n\nfrom prance import BaseParser, ResolvingParser\n\nfrom ..model import CustomRootType, DataModel, DataModelField\nfrom ..model.base import TemplateBase\n\n\n@dataclass\nclass DataType:\n    type_hint: str\n    format: Optional[str] = None\n    default: Optional[Field] = None\n\n\ndata_types: Dict[str, Dict[str, DataType]] = {\n    # https://docs.python.org/3.7/library/json.html#encoders-and-decoders\n    'integer':\n        {\n            'int32': DataType(type_hint='int'),\n            'int64': DataType(type_hint='int')\n        },\n    'number':\n        {\n            'float': DataType(type_hint='float'),\n            'double': DataType(type_hint='float')\n        },\n    'string':\n        {'default': DataType(type_hint='str'),\n         'byte': DataType(type_hint='str'),\n         'binary': DataType(type_hint='bytes')\n         },\n    #               'data': date,}, #As defined by full-date - RFC3339\n    'boolean': {'default': DataType(type_hint='bool')}\n}\n\n\ndef get_data_type(_type, format =None) -> DataType:\n    _format: str = format or 'default'\n    return data_types[_type][_format]\n\n\ndef dump_templates(templates: Union[TemplateBase, List[TemplateBase]]) -> str:\n    if isinstance(templates, TemplateBase):\n        templates = [templates]\n    return '\\n\\n'.join(str(m) for m in templates)\n\n\nclass Parser:\n    def __init__(self, data_model_type: Type[DataModel], data_model_field_type: Type[DataModelField],\n                 filename: str = \"api.yaml\"):\n        self.base_parser = BaseParser(filename, backend='openapi-spec-validator')\n        self.resolving_parser = ResolvingParser(filename, backend='openapi-spec-validator')\n\n        self.data_model_type: Type[DataModel] = data_model_type\n        self.data_model_field_type: Type[DataModelField] = data_model_field_type\n        self.models = []\n\n    def parse_object(self, name: str, obj: Dict) -> str:\n        requires: Set[str] = set(obj.get('required', []))\n        d_list: List[DataModelField] = []\n        for field_name, filed in obj['properties'].items():\n            # object\n            d_list.append(self.data_model_field_type(\n                name=field_name, type_hint=get_data_type(filed[\"type\"],\n                                                         filed.get(\"format\")).type_hint,\n                required=field_name in requires))\n        return dump_templates(self.data_model_type(name, fields=d_list))\n\n    def parse_array(self, name: str, obj: Dict) -> str:\n        templates: List[TemplateBase] = []\n        # continue\n        if '$ref' in obj['items']:\n            _type: str = f\"List[{obj['items']['$ref'].split('/')[-1]}]\"\n            templates.append(CustomRootType(name, _type))\n        elif 'properties' in obj['items']:\n            self.parse_object(name[:-1], obj['items'])\n            templates.append(CustomRootType(name, f'List[{name[:-1]}]'))\n        return dump_templates(templates)\n\n    def parse(self) -> str:\n        parsed_objects: List[str] = []\n        for obj_name, obj in self.base_parser.specification['components']['schemas'].items():\n            if 'properties' in obj:\n                parsed_objects.append(self.parse_object(obj_name, obj))\n            elif 'items' in obj:\n                parsed_objects.append(self.parse_array(obj_name, obj))\n\n        return '\\n\\n\\n'.join(parsed_objects)\n", "path": "datamodel_code_generator/parser/openapi.py"}], "after_files": [{"content": "#! /usr/bin/env python\n\n\"\"\"\nMain function.\n\"\"\"\n\nimport os\nimport sys\nfrom argparse import ArgumentParser, FileType\nfrom datetime import datetime, timezone\nfrom enum import IntEnum\nfrom typing import Optional, Sequence\n\nimport argcomplete\n\nfrom datamodel_code_generator.model import BaseModel, DataModelField\nfrom datamodel_code_generator.parser.openapi import Parser\n\n\nclass Exit(IntEnum):\n    \"\"\"Exit reasons.\"\"\"\n\n    OK = 0\n    ERROR = 1\n\n\narg_parser = ArgumentParser()\narg_parser.add_argument(\"--input\", help=\"Open API YAML file\")\narg_parser.add_argument(\"--output\", help=\"Output file\", type=FileType(\"wt\"), default=sys.stdout)\n\n\ndef main(args: Optional[Sequence[str]] = None) -> Exit:\n    \"\"\"Main function.\"\"\"\n\n    # add cli completion support\n    argcomplete.autocomplete(arg_parser)\n\n    if args is None:\n        args = sys.argv[1:]\n\n    args = arg_parser.parse_args(args)\n\n    input_filename = os.path.abspath(os.path.expanduser(args.input))\n    parser = Parser(BaseModel, DataModelField, filename=input_filename)\n    timestamp = datetime.now(timezone.utc).replace(microsecond=0).isoformat()\n    header = f\"\"\"\\\n# generated by datamodel-codegen:\n#   filename:  {os.path.split(input_filename)[1]}\n#   timestamp: {timestamp}\n\nfrom typing import List, Optional\n\nfrom pydantic import BaseModel\n\n\n\"\"\"\n    with args.output as file:\n        print(header, file=file)\n        print(parser.parse(), file=file)\n\n    return Exit.OK\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n", "path": "datamodel_code_generator/__main__.py"}, {"content": "from typing import Dict, List, Optional, Set, Type, Union\n\nfrom dataclasses import Field, dataclass\nfrom prance import BaseParser, ResolvingParser\n\nfrom ..model import CustomRootType, DataModel, DataModelField\nfrom ..model.base import TemplateBase\n\n\n@dataclass\nclass DataType:\n    type_hint: str\n    format: Optional[str] = None\n    default: Optional[Field] = None\n\n\ndata_types: Dict[str, Dict[str, DataType]] = {\n    # https://docs.python.org/3.7/library/json.html#encoders-and-decoders\n    'integer':\n        {\n            'int32': DataType(type_hint='int'),\n            'int64': DataType(type_hint='int')\n        },\n    'number':\n        {\n            'float': DataType(type_hint='float'),\n            'double': DataType(type_hint='float')\n        },\n    'string':\n        {'default': DataType(type_hint='str'),\n         'byte': DataType(type_hint='str'),\n         'binary': DataType(type_hint='bytes')\n         },\n    #               'data': date,}, #As defined by full-date - RFC3339\n    'boolean': {'default': DataType(type_hint='bool')}\n}\n\n\ndef get_data_type(_type, format =None) -> DataType:\n    _format: str = format or 'default'\n    return data_types[_type][_format]\n\n\ndef dump_templates(templates: Union[TemplateBase, List[TemplateBase]]) -> str:\n    if isinstance(templates, TemplateBase):\n        templates = [templates]\n    return '\\n\\n'.join(str(m) for m in templates)\n\n\nclass Parser:\n    def __init__(self, data_model_type: Type[DataModel], data_model_field_type: Type[DataModelField],\n                 filename: str = \"api.yaml\"):\n        self.base_parser = BaseParser(filename, backend='openapi-spec-validator')\n        self.resolving_parser = ResolvingParser(filename, backend='openapi-spec-validator')\n\n        self.data_model_type: Type[DataModel] = data_model_type\n        self.data_model_field_type: Type[DataModelField] = data_model_field_type\n        self.models = []\n\n    def parse_object(self, name: str, obj: Dict) -> str:\n        requires: Set[str] = set(obj.get('required', []))\n        d_list: List[DataModelField] = []\n        for field_name, filed in obj['properties'].items():\n            # object\n            d_list.append(self.data_model_field_type(\n                name=field_name, type_hint=get_data_type(filed[\"type\"],\n                                                         filed.get(\"format\")).type_hint,\n                required=field_name in requires))\n        return dump_templates(self.data_model_type(name, fields=d_list))\n\n    def parse_array(self, name: str, obj: Dict) -> str:\n        templates: List[TemplateBase] = []\n        # continue\n        if '$ref' in obj['items']:\n            _type: str = f\"List[{obj['items']['$ref'].split('/')[-1]}]\"\n            templates.append(CustomRootType(name, _type))\n        elif 'properties' in obj['items']:\n            self.parse_object(name[:-1], obj['items'])\n            templates.append(CustomRootType(name, f'List[{name[:-1]}]'))\n        return dump_templates(templates)\n\n    def parse(self) -> str:\n        parsed_objects: List[str] = []\n        for obj_name, obj in self.base_parser.specification['components']['schemas'].items():\n            if 'properties' in obj:\n                parsed_objects.append(self.parse_object(obj_name, obj))\n            elif 'items' in obj:\n                parsed_objects.append(self.parse_array(obj_name, obj))\n\n        return '\\n\\n\\n'.join(parsed_objects)\n", "path": "datamodel_code_generator/parser/openapi.py"}]}