Skip to content

Config

docstring_format_checker.config 🔗

Summary

Configuration handling for the docstring format checker.

VALID_TYPES module-attribute 🔗

VALID_TYPES: tuple[str, ...] = (
    "free_text",
    "list_name",
    "list_type",
    "list_name_and_type",
)

GlobalConfig dataclass 🔗

Summary

Global configuration for docstring checking behavior.

Source code in src/docstring_format_checker/config.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@dataclass
class GlobalConfig:
    """
    !!! note "Summary"
        Global configuration for docstring checking behavior.
    """

    allow_undefined_sections: bool = field(
        default=False,
        metadata={
            "title": "Allow Undefined Sections",
            "description": "Allow sections not defined in the configuration.",
        },
    )
    require_docstrings: bool = field(
        default=True,
        metadata={
            "title": "Require Docstrings",
            "description": "Require docstrings for all functions/methods.",
        },
    )
    check_private: bool = field(
        default=False,
        metadata={
            "title": "Check Private Members",
            "description": "Check docstrings for private members (starting with an underscore).",
        },
    )
    validate_param_types: bool = field(
        default=True,
        metadata={
            "title": "Validate Parameter Types",
            "description": "Validate that parameter types are provided in the docstring.",
        },
    )
    optional_style: Literal["silent", "validate", "strict"] = field(
        default="validate",
        metadata={
            "title": "Optional Style",
            "description": "The style for reporting issues in optional sections.",
        },
    )
__init__ 🔗
__init__(
    allow_undefined_sections: bool = False,
    require_docstrings: bool = True,
    check_private: bool = False,
    validate_param_types: bool = True,
    optional_style: Literal[
        "silent", "validate", "strict"
    ] = "validate",
) -> None
allow_undefined_sections class-attribute instance-attribute 🔗
allow_undefined_sections: bool = field(
    default=False,
    metadata={
        "title": "Allow Undefined Sections",
        "description": "Allow sections not defined in the configuration.",
    },
)
require_docstrings class-attribute instance-attribute 🔗
require_docstrings: bool = field(
    default=True,
    metadata={
        "title": "Require Docstrings",
        "description": "Require docstrings for all functions/methods.",
    },
)
check_private class-attribute instance-attribute 🔗
check_private: bool = field(
    default=False,
    metadata={
        "title": "Check Private Members",
        "description": "Check docstrings for private members (starting with an underscore).",
    },
)
validate_param_types class-attribute instance-attribute 🔗
validate_param_types: bool = field(
    default=True,
    metadata={
        "title": "Validate Parameter Types",
        "description": "Validate that parameter types are provided in the docstring.",
    },
)
optional_style class-attribute instance-attribute 🔗
optional_style: Literal["silent", "validate", "strict"] = (
    field(
        default="validate",
        metadata={
            "title": "Optional Style",
            "description": "The style for reporting issues in optional sections.",
        },
    )
)

SectionConfig dataclass 🔗

Summary

Configuration for a docstring section.

Source code in src/docstring_format_checker/config.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
@dataclass
class SectionConfig:
    """
    !!! note "Summary"
        Configuration for a docstring section.
    """

    name: str = field(
        metadata={
            "title": "Name",
            "description": "Name of the docstring section.",
        },
    )
    type: Literal["free_text", "list_name", "list_type", "list_name_and_type"] = field(
        metadata={
            "title": "Type",
            "description": "Type of the section content.",
        },
    )
    order: Optional[int] = field(
        default=None,
        metadata={
            "title": "Order",
            "description": "Order of the section in the docstring.",
        },
    )
    admonition: Union[bool, str] = field(
        default=False,
        metadata={
            "title": "Admonition",
            "description": "Admonition style for the section. Can be False (no admonition) or a string specifying the admonition type.",
        },
    )
    prefix: str = field(
        default="",
        metadata={
            "title": "Prefix",
            "description": "Prefix string for the admonition values.",
        },
    )
    required: bool = field(
        default=False,
        metadata={
            "title": "Required",
            "description": "Whether this section is required in the docstring.",
        },
    )
    message: str = field(
        default="",
        metadata={
            "title": "Message",
            "description": "Optional message for validation errors.",
        },
    )

    def __post_init__(self) -> None:
        """
        !!! note "Summary"
            Validate configuration after initialization.
        """
        self._validate_types()
        self._validate_admonition_prefix_combination()

    def _validate_types(self) -> None:
        """
        !!! note "Summary"
            Validate the 'type' field.
        """
        if self.type not in VALID_TYPES:
            raise InvalidTypeValuesError(f"Invalid section type: {self.type}. Valid types: {VALID_TYPES}")

    def _validate_admonition_prefix_combination(self) -> None:
        """
        !!! note "Summary"
            Validate admonition and prefix combination rules.
        """

        if isinstance(self.admonition, bool):
            # Rule: admonition cannot be True (only False or string)
            if self.admonition is True:
                raise ValueError(f"Section '{self.name}': admonition cannot be True, must be False or a string")

            # Rule: if admonition is False, prefix cannot be provided
            if self.admonition is False and self.prefix:
                raise ValueError(f"Section '{self.name}': when admonition=False, prefix cannot be provided")

        elif isinstance(self.admonition, str):
            # Rule: if admonition is a string, prefix must be provided
            if not self.prefix:
                raise ValueError(f"Section '{self.name}': when admonition is a string, prefix must be provided")

        else:
            raise ValueError(
                f"Section '{self.name}': admonition must be a boolean or string, got {type(self.admonition)}"
            )
__init__ 🔗
__init__(
    name: str,
    type: Literal[
        "free_text",
        "list_name",
        "list_type",
        "list_name_and_type",
    ],
    order: Optional[int] = None,
    admonition: Union[bool, str] = False,
    prefix: str = "",
    required: bool = False,
    message: str = "",
) -> None
name class-attribute instance-attribute 🔗
name: str = field(
    metadata={
        "title": "Name",
        "description": "Name of the docstring section.",
    }
)
type class-attribute instance-attribute 🔗
type: Literal[
    "free_text",
    "list_name",
    "list_type",
    "list_name_and_type",
] = field(
    metadata={
        "title": "Type",
        "description": "Type of the section content.",
    }
)
order class-attribute instance-attribute 🔗
order: Optional[int] = field(
    default=None,
    metadata={
        "title": "Order",
        "description": "Order of the section in the docstring.",
    },
)
admonition class-attribute instance-attribute 🔗
admonition: Union[bool, str] = field(
    default=False,
    metadata={
        "title": "Admonition",
        "description": "Admonition style for the section. Can be False (no admonition) or a string specifying the admonition type.",
    },
)
prefix class-attribute instance-attribute 🔗
prefix: str = field(
    default="",
    metadata={
        "title": "Prefix",
        "description": "Prefix string for the admonition values.",
    },
)
required class-attribute instance-attribute 🔗
required: bool = field(
    default=False,
    metadata={
        "title": "Required",
        "description": "Whether this section is required in the docstring.",
    },
)
message class-attribute instance-attribute 🔗
message: str = field(
    default="",
    metadata={
        "title": "Message",
        "description": "Optional message for validation errors.",
    },
)
__post_init__ 🔗
__post_init__() -> None

Summary

Validate configuration after initialization.

Source code in src/docstring_format_checker/config.py
211
212
213
214
215
216
217
def __post_init__(self) -> None:
    """
    !!! note "Summary"
        Validate configuration after initialization.
    """
    self._validate_types()
    self._validate_admonition_prefix_combination()
_validate_types 🔗
_validate_types() -> None

Summary

Validate the 'type' field.

Source code in src/docstring_format_checker/config.py
219
220
221
222
223
224
225
def _validate_types(self) -> None:
    """
    !!! note "Summary"
        Validate the 'type' field.
    """
    if self.type not in VALID_TYPES:
        raise InvalidTypeValuesError(f"Invalid section type: {self.type}. Valid types: {VALID_TYPES}")
_validate_admonition_prefix_combination 🔗
_validate_admonition_prefix_combination() -> None

Summary

Validate admonition and prefix combination rules.

Source code in src/docstring_format_checker/config.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def _validate_admonition_prefix_combination(self) -> None:
    """
    !!! note "Summary"
        Validate admonition and prefix combination rules.
    """

    if isinstance(self.admonition, bool):
        # Rule: admonition cannot be True (only False or string)
        if self.admonition is True:
            raise ValueError(f"Section '{self.name}': admonition cannot be True, must be False or a string")

        # Rule: if admonition is False, prefix cannot be provided
        if self.admonition is False and self.prefix:
            raise ValueError(f"Section '{self.name}': when admonition=False, prefix cannot be provided")

    elif isinstance(self.admonition, str):
        # Rule: if admonition is a string, prefix must be provided
        if not self.prefix:
            raise ValueError(f"Section '{self.name}': when admonition is a string, prefix must be provided")

    else:
        raise ValueError(
            f"Section '{self.name}': admonition must be a boolean or string, got {type(self.admonition)}"
        )

_validate_config_order 🔗

_validate_config_order(
    config_sections: list[SectionConfig],
) -> None

Summary

Validate that section order values are unique.

Parameters:

Name Type Description Default
config_sections list[SectionConfig]

List of section configurations to validate.

required

Raises:

Type Description
InvalidConfigError_DuplicateOrderValues

If duplicate order values are found.

Returns:

Type Description
None

Nothing is returned.

Source code in src/docstring_format_checker/config.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def _validate_config_order(config_sections: list[SectionConfig]) -> None:
    """
    !!! note "Summary"
        Validate that section order values are unique.

    Params:
        config_sections (list[SectionConfig]):
            List of section configurations to validate.

    Raises:
        (InvalidConfigError_DuplicateOrderValues):
            If duplicate order values are found.

    Returns:
        (None):
            Nothing is returned.
    """

    # Validate no duplicate order values
    order_values: list[int] = [section.order for section in config_sections if section.order is not None]
    seen_orders: set[int] = set()
    duplicate_orders: set[int] = set()

    for order in order_values:
        if order in seen_orders:
            duplicate_orders.add(order)
        else:
            seen_orders.add(order)

    if duplicate_orders:
        raise InvalidConfigError_DuplicateOrderValues(
            f"Configuration contains duplicate order values: {sorted(duplicate_orders)}. "
            "Each section must have a unique order value."
        )

Config dataclass 🔗

Summary

Complete configuration containing global settings and section definitions.

Source code in src/docstring_format_checker/config.py
301
302
303
304
305
306
307
308
309
@dataclass
class Config:
    """
    !!! note "Summary"
        Complete configuration containing global settings and section definitions.
    """

    global_config: GlobalConfig
    sections: list[SectionConfig]
__init__ 🔗
__init__(
    global_config: GlobalConfig,
    sections: list[SectionConfig],
) -> None
global_config instance-attribute 🔗
global_config: GlobalConfig
sections instance-attribute 🔗
sections: list[SectionConfig]

DEFAULT_SECTIONS module-attribute 🔗

DEFAULT_SECTIONS: list[SectionConfig] = [
    SectionConfig(
        order=1,
        name="summary",
        type="free_text",
        admonition="note",
        prefix="!!!",
        required=True,
    ),
    SectionConfig(
        order=2,
        name="details",
        type="free_text",
        admonition="info",
        prefix="???+",
        required=False,
    ),
    SectionConfig(
        order=3,
        name="params",
        type="list_name_and_type",
        required=True,
    ),
    SectionConfig(
        order=4,
        name="returns",
        type="list_name_and_type",
        required=False,
    ),
    SectionConfig(
        order=5,
        name="yields",
        type="list_type",
        required=False,
    ),
    SectionConfig(
        order=6,
        name="raises",
        type="list_type",
        required=False,
    ),
    SectionConfig(
        order=7,
        name="examples",
        type="free_text",
        admonition="example",
        prefix="???+",
        required=False,
    ),
    SectionConfig(
        order=8,
        name="notes",
        type="free_text",
        admonition="note",
        prefix="???",
        required=False,
    ),
]

DEFAULT_CONFIG module-attribute 🔗

DEFAULT_CONFIG: Config = Config(
    global_config=GlobalConfig(), sections=DEFAULT_SECTIONS
)

load_config 🔗

load_config(
    config_path: Optional[Union[str, Path]] = None,
) -> Config

Summary

Load configuration from a TOML file or return default configuration.

Parameters:

Name Type Description Default
config_path Optional[Union[str, Path]]

Path to the TOML configuration file. If None, looks for pyproject.toml in current directory. Default: None.

None

Raises:

Type Description
FileNotFoundError

If the specified config file doesn't exist.

InvalidConfigError

If the configuration is invalid.

Returns:

Type Description
Config

Configuration object containing global settings and section definitions.

Source code in src/docstring_format_checker/config.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def load_config(config_path: Optional[Union[str, Path]] = None) -> Config:
    """
    !!! note "Summary"
        Load configuration from a TOML file or return default configuration.

    Params:
        config_path (Optional[Union[str, Path]]):
            Path to the TOML configuration file.
            If `None`, looks for `pyproject.toml` in current directory.
            Default: `None`.

    Raises:
        (FileNotFoundError):
            If the specified config file doesn't exist.
        (InvalidConfigError):
            If the configuration is invalid.

    Returns:
        (Config):
            Configuration object containing global settings and section definitions.
    """
    # Resolve config file path
    resolved_path = _resolve_config_path(config_path)
    if resolved_path is None:
        return DEFAULT_CONFIG

    # Parse TOML configuration
    config_data = _parse_toml_file(resolved_path)

    # Extract tool configuration
    tool_config = _extract_tool_config(config_data)
    if tool_config is None:
        return DEFAULT_CONFIG

    # Parse configuration components
    global_config = _parse_global_config(tool_config)
    sections_config = _parse_sections_config(tool_config)

    return Config(global_config=global_config, sections=sections_config)

_resolve_config_path 🔗

_resolve_config_path(
    config_path: Optional[Union[str, Path]],
) -> Optional[Path]

Summary

Resolve configuration file path.

Parameters:

Name Type Description Default
config_path Optional[Union[str, Path]]

Optional path to configuration file.

required

Raises:

Type Description
FileNotFoundError

If specified config file does not exist.

Returns:

Type Description
Optional[Path]

Resolved Path object or None if no config found.

Source code in src/docstring_format_checker/config.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
def _resolve_config_path(config_path: Optional[Union[str, Path]]) -> Optional[Path]:
    """
    !!! note "Summary"
        Resolve configuration file path.

    Params:
        config_path (Optional[Union[str, Path]]):
            Optional path to configuration file.

    Raises:
        (FileNotFoundError):
            If specified config file does not exist.

    Returns:
        (Optional[Path]):
            Resolved Path object or None if no config found.
    """
    if config_path is None:
        # Look for pyproject.toml in current directory
        pyproject_path: Path = Path.cwd().joinpath("pyproject.toml")
        if pyproject_path.exists():
            return pyproject_path
        else:
            return None

    # Convert to Path object and check existence
    config_path = Path(config_path)
    if not config_path.exists():
        raise FileNotFoundError(f"Configuration file not found: {config_path}")

    return config_path

_parse_toml_file 🔗

_parse_toml_file(config_path: Path) -> dict[str, Any]

Summary

Parse TOML configuration file.

Parameters:

Name Type Description Default
config_path Path

Path to TOML file to parse.

required

Raises:

Type Description
InvalidConfigError

If TOML parsing fails.

Returns:

Type Description
dict[str, Any]

Parsed TOML data as dictionary.

Source code in src/docstring_format_checker/config.py
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def _parse_toml_file(config_path: Path) -> dict[str, Any]:
    """
    !!! note "Summary"
        Parse TOML configuration file.

    Params:
        config_path (Path):
            Path to TOML file to parse.

    Raises:
        (InvalidConfigError):
            If TOML parsing fails.

    Returns:
        (dict[str, Any]):
            Parsed TOML data as dictionary.
    """
    try:
        with open(config_path, "rb") as f:
            return tomllib.load(f)
    except Exception as e:
        raise InvalidConfigError(f"Failed to parse TOML file {config_path}: {e}") from e

_extract_tool_config 🔗

_extract_tool_config(
    config_data: dict[str, Any],
) -> Optional[dict[str, Any]]

Summary

Extract tool configuration from TOML data.

Parameters:

Name Type Description Default
config_data dict[str, Any]

Parsed TOML data dictionary.

required

Returns:

Type Description
Optional[dict[str, Any]]

Tool configuration dictionary or None if not found.

Source code in src/docstring_format_checker/config.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def _extract_tool_config(config_data: dict[str, Any]) -> Optional[dict[str, Any]]:
    """
    !!! note "Summary"
        Extract tool configuration from TOML data.

    Params:
        config_data (dict[str, Any]):
            Parsed TOML data dictionary.

    Returns:
        (Optional[dict[str, Any]]):
            Tool configuration dictionary or None if not found.
    """
    if "tool" not in config_data:
        return None

    tool_section = config_data["tool"]
    if "dfc" in tool_section:
        return tool_section["dfc"]
    elif "docstring-format-checker" in tool_section:
        return tool_section["docstring-format-checker"]

    return None

_parse_global_config 🔗

_parse_global_config(
    tool_config: dict[str, Any],
) -> GlobalConfig

Summary

Parse global configuration flags.

Parameters:

Name Type Description Default
tool_config dict[str, Any]

Tool configuration dictionary.

required

Returns:

Type Description
GlobalConfig

Parsed global configuration object.

Source code in src/docstring_format_checker/config.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def _parse_global_config(tool_config: dict[str, Any]) -> GlobalConfig:
    """
    !!! note "Summary"
        Parse global configuration flags.

    Params:
        tool_config (dict[str, Any]):
            Tool configuration dictionary.

    Returns:
        (GlobalConfig):
            Parsed global configuration object.
    """
    # Validate optional_style if provided
    optional_style: str = tool_config.get("optional_style", "validate")
    valid_styles: tuple[str, str, str] = ("silent", "validate", "strict")
    if optional_style not in valid_styles:
        raise InvalidConfigError(
            f"Invalid optional_style: '{optional_style}'. Must be one of: {', '.join(valid_styles)}"
        )

    return GlobalConfig(
        allow_undefined_sections=tool_config.get("allow_undefined_sections", False),
        require_docstrings=tool_config.get("require_docstrings", True),
        check_private=tool_config.get("check_private", False),
        validate_param_types=tool_config.get("validate_param_types", True),
        optional_style=optional_style,  # type:ignore
    )

_parse_sections_config 🔗

_parse_sections_config(
    tool_config: dict[str, Any],
) -> list[SectionConfig]

Summary

Parse sections configuration.

Parameters:

Name Type Description Default
tool_config dict[str, Any]

Tool configuration dictionary.

required

Returns:

Type Description
list[SectionConfig]

List of section configuration objects or defaults.

Source code in src/docstring_format_checker/config.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
def _parse_sections_config(tool_config: dict[str, Any]) -> list[SectionConfig]:
    """
    !!! note "Summary"
        Parse sections configuration.

    Params:
        tool_config (dict[str, Any]):
            Tool configuration dictionary.

    Returns:
        (list[SectionConfig]):
            List of section configuration objects or defaults.
    """
    if "sections" not in tool_config:
        return DEFAULT_SECTIONS

    sections_config: list[SectionConfig] = []
    sections_data = tool_config["sections"]

    for section_data in sections_data:
        try:
            # Get admonition value with proper default handling
            admonition_value: Union[str, bool] = section_data.get("admonition")
            if admonition_value is None:
                admonition_value = False  # Use SectionConfig default

            section = SectionConfig(
                order=section_data.get("order"),
                name=section_data.get("name", ""),
                type=section_data.get("type", ""),
                admonition=admonition_value,
                prefix=section_data.get("prefix", ""),
                required=section_data.get("required", False),
            )
            sections_config.append(section)
        except (KeyError, TypeError, ValueError, InvalidTypeValuesError) as e:
            raise InvalidConfigError(f"Invalid section configuration: {section_data}. Error: {e}") from e

    # Validate and sort sections
    if sections_config:
        _validate_config_order(config_sections=sections_config)
        sections_config.sort(key=lambda x: x.order if x.order is not None else float("inf"))
    else:
        sections_config = DEFAULT_SECTIONS

    return sections_config

find_config_file 🔗

find_config_file(
    start_path: Optional[Path] = None,
) -> Optional[Path]

Summary

Find configuration file by searching up the directory tree.

Parameters:

Name Type Description Default
start_path Optional[Path]

Directory to start searching from. If None, resolves to current directory. Default: None.

None

Returns:

Type Description
Optional[Path]

Path to the configuration file if found, None otherwise.

Source code in src/docstring_format_checker/config.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def find_config_file(start_path: Optional[Path] = None) -> Optional[Path]:
    """
    !!! note "Summary"
        Find configuration file by searching up the directory tree.

    Params:
        start_path (Optional[Path]):
            Directory to start searching from.
            If `None`, resolves to current directory.
            Default: `None`.

    Returns:
        (Optional[Path]):
            Path to the configuration file if found, None otherwise.
    """
    if start_path is None:
        start_path = Path.cwd()

    current_path: Path = start_path.resolve()

    while current_path != current_path.parent:
        pyproject_path: Path = current_path.joinpath("pyproject.toml")
        if pyproject_path.exists():
            # Check if it contains dfc configuration
            try:
                with open(pyproject_path, "rb") as f:
                    config_data: dict[str, Any] = tomllib.load(f)
                    if "tool" in config_data and (
                        "dfc" in config_data["tool"] or "docstring-format-checker" in config_data["tool"]
                    ):
                        return pyproject_path
            except Exception:
                pass

        current_path = current_path.parent

    return None