Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 62 additions & 12 deletions docs/using_as_module.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pip install 'datamodel-code-generator[http]'
When the `output` parameter is omitted (or set to `None`), `generate()` returns the generated code directly as a string:

```python
from datamodel_code_generator import InputFileType, generate, DataModelType
from datamodel_code_generator import InputFileType, generate, GenerateConfig, DataModelType
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# Check if GenerateConfig is exported from the main module
echo "=== Checking GenerateConfig in datamodel_code_generator/__init__.py ==="
cat datamodel_code_generator/__init__.py | grep -n "GenerateConfig"

# Check for JSONSchemaParserConfig
echo ""
echo "=== Checking JSONSchemaParserConfig ==="
rg "class JSONSchemaParserConfig" --type python

# Check for GeneratedModules
echo ""
echo "=== Checking GeneratedModules ==="
rg "class GeneratedModules|GeneratedModules" --type python | head -20

# Check for get_data_model_types
echo ""
echo "=== Checking get_data_model_types ==="
rg "def get_data_model_types" --type python

# List what's actually exported from __init__.py
echo ""
echo "=== Checking __all__ in datamodel_code_generator/__init__.py ==="
grep "__all__" datamodel_code_generator/__init__.py -A 50

Repository: koxudaxi/datamodel-code-generator

Length of output: 163


🏁 Script executed:

# Check key imports with specific line limits
echo "=== GenerateConfig in __init__.py ==="
rg "GenerateConfig" datamodel_code_generator/__init__.py --max-count=5

echo ""
echo "=== JSONSchemaParserConfig location ==="
rg "class JSONSchemaParserConfig" --type python --max-count=5

echo ""
echo "=== GeneratedModules location ==="
rg "class GeneratedModules" --type python --max-count=5

echo ""
echo "=== get_data_model_types location ==="
rg "def get_data_model_types" --type python --max-count=5

echo ""
echo "=== Checking __init__.py __all__ export list ==="
rg "^__all__" datamodel_code_generator/__init__.py -A 30 --max-count=1

Repository: koxudaxi/datamodel-code-generator

Length of output: 543


🏁 Script executed:

# Find the datamodel_code_generator module
echo "=== Locating datamodel_code_generator module ==="
fd -t d "datamodel_code_generator" | head -5

# List top-level directory structure
echo ""
echo "=== Repository root structure ==="
ls -la | head -20

# Find __init__.py files
echo ""
echo "=== Finding __init__.py files ==="
fd "__init__\.py" | grep datamodel | head -10

Repository: koxudaxi/datamodel-code-generator

Length of output: 1638


🏁 Script executed:

# Check main __init__.py for exports
echo "=== Checking src/datamodel_code_generator/__init__.py ==="
head -100 src/datamodel_code_generator/__init__.py | grep -E "GenerateConfig|GeneratedModules|__all__|import"

echo ""
echo "=== Searching for GenerateConfig definition ==="
rg "class GenerateConfig|^GenerateConfig" src/ --max-count=5

echo ""
echo "=== Searching for JSONSchemaParserConfig ==="
rg "class JSONSchemaParserConfig" src/ --max-count=5

echo ""
echo "=== Searching for GeneratedModules ==="
rg "class GeneratedModules" src/ --max-count=5

echo ""
echo "=== Searching for get_data_model_types ==="
rg "def get_data_model_types" src/ --max-count=5

Repository: koxudaxi/datamodel-code-generator

Length of output: 1765


🏁 Script executed:

# Check __all__ in main __init__.py
echo "=== Checking __all__ in main __init__.py ==="
rg "^__all__" src/datamodel_code_generator/__init__.py -A 50

echo ""
echo "=== Checking if JSONSchemaParserConfig is in main __init__.py imports ==="
grep -n "JSONSchemaParserConfig" src/datamodel_code_generator/__init__.py

echo ""
echo "=== Check what the docs file actually imports on line 20 ==="
sed -n '15,25p' docs/using_as_module.md

echo ""
echo "=== Check imports on other lines mentioned (47, 74, 138) ==="
sed -n '42,52p' docs/using_as_module.md
echo "---"
sed -n '69,79p' docs/using_as_module.md
echo "---"
sed -n '133,143p' docs/using_as_module.md

Repository: koxudaxi/datamodel-code-generator

Length of output: 2697


🏁 Script executed:

# Check for DataModelType
echo "=== Searching for DataModelType ==="
rg "class DataModelType|DataModelType.*=" src/datamodel_code_generator/__init__.py | head -10

echo ""
echo "=== Check full imports in main __init__.py that aren't in __all__ ==="
rg "^from|^import" src/datamodel_code_generator/__init__.py | grep -E "GenerateConfig|DataModelType" | head -10

echo ""
echo "=== Check what DataModelType actually is ==="
rg "class DataModelType|DataModelType\s*=" src/ --max-count=10

Repository: koxudaxi/datamodel-code-generator

Length of output: 883


🏁 Script executed:

# Get full imports section from main __init__.py
echo "=== Full import section of main __init__.py ==="
head -80 src/datamodel_code_generator/__init__.py | tail -40

echo ""
echo "=== Check if DataModelType is imported in main ==="
grep "DataModelType" src/datamodel_code_generator/__init__.py

echo ""
echo "=== Check full __all__ list to confirm ==="
grep -A 50 "^__all__" src/datamodel_code_generator/__init__.py | grep -E "DataModelType|GenerateConfig"

Repository: koxudaxi/datamodel-code-generator

Length of output: 1775


🏁 Script executed:

# Check the enums import in main __init__.py more carefully
echo "=== Check enums imports in main __init__.py ==="
rg "from datamodel_code_generator.enums import" src/datamodel_code_generator/__init__.py -A 15

echo ""
echo "=== Verify GenerateConfig is ONLY in TYPE_CHECKING ==="
grep -n "GenerateConfig" src/datamodel_code_generator/__init__.py

echo ""
echo "=== Check if there's runtime import of GenerateConfig elsewhere ==="
head -150 src/datamodel_code_generator/__init__.py | grep -n "GenerateConfig"

Repository: koxudaxi/datamodel-code-generator

Length of output: 183


🏁 Script executed:

# Simple check: Can these be imported at runtime?
echo "=== Check DataModelType in main __init__.py (first 100 lines) ==="
head -100 src/datamodel_code_generator/__init__.py | grep -n "DataModelType"

echo ""
echo "=== Count GenerateConfig occurrences and context ==="
grep -B2 -A2 "GenerateConfig" src/datamodel_code_generator/__init__.py | head -20

echo ""
echo "=== Check if DataModelType is in the enums import ==="
sed -n '1,50p' src/datamodel_code_generator/__init__.py | grep -A 20 "from datamodel_code_generator.enums"

Repository: koxudaxi/datamodel-code-generator

Length of output: 183


🏁 Script executed:

# Read first part of __init__.py to find all imports
wc -l src/datamodel_code_generator/__init__.py

# Read lines 1-50 to see initial imports
echo "=== Lines 1-50 ==="
sed -n '1,50p' src/datamodel_code_generator/__init__.py

# Then check around the TYPE_CHECKING section
echo ""
echo "=== Search for TYPE_CHECKING section ==="
grep -n "TYPE_CHECKING" src/datamodel_code_generator/__init__.py

Repository: koxudaxi/datamodel-code-generator

Length of output: 183


🏁 Script executed:

python3 << 'EOF'
import sys

# Read the main __init__.py file
with open('src/datamodel_code_generator/__init__.py', 'r') as f:
    lines = f.readlines()

# Find TYPE_CHECKING import block
print("=== Checking TYPE_CHECKING block for GenerateConfig ===")
in_type_checking = False
for i, line in enumerate(lines[:100], 1):
    if 'TYPE_CHECKING' in line:
        in_type_checking = True
        print(f"Line {i}: {line.rstrip()}")
    elif in_type_checking:
        print(f"Line {i}: {line.rstrip()}")
        if 'GenerateConfig' in line:
            print("  ^^^ GenerateConfig found in TYPE_CHECKING block")
        if line.strip() == '' or (line[0] not in ' \t' and 'import' not in line):
            in_type_checking = False

# Check if DataModelType is imported outside TYPE_CHECKING
print("\n=== Checking for DataModelType in runtime imports ===")
for i, line in enumerate(lines[:100], 1):
    if 'DataModelType' in line and 'TYPE_CHECKING' not in line:
        print(f"Line {i}: {line.rstrip()}")
EOF

Repository: koxudaxi/datamodel-code-generator

Length of output: 183


🏁 Script executed:

# Try very simple file size check first
stat src/datamodel_code_generator/__init__.py

# Then use cat with head
cat src/datamodel_code_generator/__init__.py | head -80

Repository: koxudaxi/datamodel-code-generator

Length of output: 183


🌐 Web query:

datamodel-code-generator GenerateConfig public API export import

💡 Result:

I’m not sure what you mean by “GenerateConfig” in the context of datamodel-code-generator. Do you mean:

  • the CLI/module generate function and its config/options (using datamodel_code_generator.generate or CLI flags), or
  • a specific class named GenerateConfig in another library, or
  • exporting/importing a saved configuration (e.g., pyproject.toml / CLI flags) for datamodel-code-generator?

Tell me which one and I’ll give exact import/export code or commands (and examples).


Fix import path for GenerateConfig in documentation examples (lines 20, 47, 74, 138).

GenerateConfig cannot be imported from the main datamodel_code_generator module at runtime—it is only available for type checking. Update all documentation examples to import from the config submodule:

from datamodel_code_generator.config import GenerateConfig

instead of:

from datamodel_code_generator import GenerateConfig

The imports for JSONSchemaParserConfig (from datamodel_code_generator.config) and get_data_model_types (from datamodel_code_generator.model) are correct. GeneratedModules is also correctly exported from the main module.

🤖 Prompt for AI Agents
In docs/using_as_module.md around line 20 (and also update lines 47, 74, 138),
the examples import GenerateConfig from the top-level package which only exposes
it for type checking; change those imports to import GenerateConfig from the
config submodule (i.e., use from datamodel_code_generator.config import
GenerateConfig) so the examples work at runtime—leave other imports
(JSONSchemaParserConfig, get_data_model_types, GeneratedModules) as they are.


json_schema: str = """{
"type": "object",
Expand All @@ -30,12 +30,12 @@ json_schema: str = """{
}
}"""

result = generate(
json_schema,
config = GenerateConfig(
input_file_type=InputFileType.JsonSchema,
input_filename="example.json",
output_model_type=DataModelType.PydanticV2BaseModel,
)
result = generate(json_schema, config=config)
print(result)
```

Expand All @@ -44,13 +44,16 @@ print(result)
When the schema generates multiple modules, `generate()` returns a `GeneratedModules` dictionary mapping module path tuples to generated code:

```python
from datamodel_code_generator import InputFileType, generate, GeneratedModules
from datamodel_code_generator import InputFileType, generate, GenerateConfig, GeneratedModules

# Your OpenAPI specification (string, Path, or dict)
openapi_spec: str = "..." # Replace with your actual OpenAPI spec

# Schema that generates multiple modules (e.g., with $ref to other files)
result: str | GeneratedModules = generate(
openapi_spec,
config = GenerateConfig(
input_file_type=InputFileType.OpenAPI,
)
result: str | GeneratedModules = generate(openapi_spec, config=config)

if isinstance(result, dict):
for module_path, content in result.items():
Expand All @@ -63,13 +66,12 @@ else:

### 📝 Writing to Files

To write generated code to the file system, provide a `Path` to the `output` parameter:
To write generated code to the file system, provide a `Path` to the `output` parameter in the config:

```python
from pathlib import Path
from tempfile import TemporaryDirectory
from datamodel_code_generator import InputFileType, generate
from datamodel_code_generator import DataModelType
from datamodel_code_generator import InputFileType, generate, GenerateConfig, DataModelType

json_schema: str = """{
"type": "object",
Expand All @@ -85,14 +87,14 @@ json_schema: str = """{
with TemporaryDirectory() as temporary_directory_name:
temporary_directory = Path(temporary_directory_name)
output = Path(temporary_directory / 'model.py')
generate(
json_schema,
config = GenerateConfig(
input_file_type=InputFileType.JsonSchema,
input_filename="example.json",
output=output,
# set up the output model types
output_model_type=DataModelType.PydanticV2BaseModel,
)
generate(json_schema, config=config)
model: str = output.read_text()
print(model)
```
Expand Down Expand Up @@ -127,10 +129,13 @@ class Model(BaseModel):

## 🔧 Using the Parser Directly

You can also call the parser directly for more control:
You can also call the parser directly for more control. Parser classes also support the `config` parameter similar to `generate()`.

### Using `config` Parameter (Recommended)

```python
from datamodel_code_generator import DataModelType, PythonVersion
from datamodel_code_generator.config import JSONSchemaParserConfig
from datamodel_code_generator.model import get_data_model_types
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser

Expand All @@ -145,6 +150,39 @@ json_schema: str = """{
}
}"""

data_model_types = get_data_model_types(
DataModelType.PydanticV2BaseModel,
target_python_version=PythonVersion.PY_311
)
config = JSONSchemaParserConfig(
data_model_type=data_model_types.data_model,
data_model_root_type=data_model_types.root_model,
data_model_field_type=data_model_types.field_model,
data_type_manager_type=data_model_types.data_type_manager,
dump_resolve_reference_action=data_model_types.dump_resolve_reference_action,
)
parser = JsonSchemaParser(json_schema, config=config)
result = parser.parse()
print(result)
```

### Using Keyword Arguments (Backward Compatible)

```python
from datamodel_code_generator import DataModelType, PythonVersion
from datamodel_code_generator.model import get_data_model_types
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser

json_schema: str = """{
"type": "object",
"properties": {
"number": {"type": "number"},
"street_name": {"type": "string"},
"street_type": {"type": "string",
"enum": ["Street", "Avenue", "Boulevard"]
}
}
}"""

data_model_types = get_data_model_types(
DataModelType.PydanticV2BaseModel,
Expand All @@ -162,6 +200,18 @@ result = parser.parse()
print(result)
```

### Available Parser Config Classes

Each parser type has its own config class:

| Parser | Config Class |
|--------|-------------|
| `JsonSchemaParser` | `JSONSchemaParserConfig` |
| `OpenAPIParser` | `OpenAPIParserConfig` |
| `GraphQLParser` | `GraphQLParserConfig` |

All config classes inherit from `ParserConfig` and include additional parser-specific options.

**✨ Output:**
```python
from __future__ import annotations
Expand Down
Loading