or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-tools.mddocstring-parsing.mdhooks.mdindex.mdsphinx-extension.mdvalidation.md

validation.mddocs/

0

# Validation

1

2

The numpydoc validation module provides extensive docstring validation functionality with configurable error codes, detailed error messages, and support for both programmatic and command-line validation workflows.

3

4

## Core Validation

5

6

### Main Validator Class

7

8

```python { .api }

9

class Validator:

10

"""

11

Main docstring validation class with extensive validation methods.

12

13

Performs comprehensive validation of NumPy-style docstrings according

14

to configurable rules, checking formatting, content, structure, and

15

cross-reference consistency.

16

17

Parameters

18

----------

19

obj_name : str

20

Fully qualified name of object to validate (e.g., 'numpy.array')

21

obj : object, optional

22

The actual Python object (loaded if not provided)

23

**kwargs

24

Additional configuration options

25

26

Attributes

27

----------

28

obj_name : str

29

Name of the object being validated

30

obj : object

31

The Python object being validated

32

code : str

33

Source code of the object

34

raw_doc : str

35

Raw docstring content

36

clean_doc : str

37

Processed docstring content

38

doc : NumpyDocString

39

Parsed docstring object

40

errors : list of tuple

41

List of (error_code, message) validation errors

42

"""

43

44

```

45

46

### Validator Properties

47

48

The Validator class provides many properties to access different aspects of the parsed docstring and object being validated:

49

50

```python { .api }

51

@property

52

def name(self) -> str:

53

"""Fully qualified name of the object being validated."""

54

55

@property

56

def type(self) -> str:

57

"""Type name of the object (e.g., 'function', 'method', 'class')."""

58

59

@property

60

def is_function_or_method(self) -> bool:

61

"""True if the object is a function or method."""

62

63

@property

64

def is_mod(self) -> bool:

65

"""True if the object is a module."""

66

67

@property

68

def is_generator_function(self) -> bool:

69

"""True if the object is a generator function."""

70

71

@property

72

def summary(self) -> str:

73

"""Summary section of the docstring (single line)."""

74

75

@property

76

def num_summary_lines(self) -> int:

77

"""Number of lines in the summary section."""

78

79

@property

80

def extended_summary(self) -> str:

81

"""Extended summary section content."""

82

83

@property

84

def doc_parameters(self) -> Dict:

85

"""Dictionary of documented parameters from Parameters section."""

86

87

@property

88

def doc_other_parameters(self) -> Dict:

89

"""Dictionary of documented parameters from Other Parameters section."""

90

91

@property

92

def doc_all_parameters(self) -> Dict:

93

"""Combined dictionary of all documented parameters."""

94

95

@property

96

def signature_parameters(self) -> Dict:

97

"""Dictionary of parameters from the function signature."""

98

99

@property

100

def parameter_mismatches(self) -> List:

101

"""List of parameter mismatches between signature and documentation."""

102

103

@property

104

def see_also(self) -> Dict:

105

"""See Also section content organized by reference type."""

106

107

@property

108

def examples(self) -> str:

109

"""Examples section content."""

110

111

@property

112

def returns(self) -> List:

113

"""Returns section content."""

114

115

@property

116

def yields(self) -> List:

117

"""Yields section content."""

118

119

@property

120

def deprecated(self) -> bool:

121

"""True if the object has a deprecation notice."""

122

123

@property

124

def source_file_name(self) -> str:

125

"""Name of the source file containing the object."""

126

127

@property

128

def source_file_def_line(self) -> int:

129

"""Line number where the object is defined."""

130

```

131

132

### Validation Function

133

134

```python { .api }

135

def validate(obj_name, validator_cls=None, **validator_kwargs):

136

"""

137

Validate the docstring for a given object name.

138

139

Parameters

140

----------

141

obj_name : str

142

The name of the object whose docstring will be evaluated, e.g.

143

'pandas.read_csv'. The string must include the full, unabbreviated

144

package/module names, i.e. 'pandas.read_csv', not 'pd.read_csv' or

145

'read_csv'.

146

validator_cls : Validator, optional

147

The Validator class to use. By default, Validator will be used.

148

**validator_kwargs

149

Keyword arguments to pass to validator_cls upon initialization.

150

Note that obj_name will be passed as a named argument as well.

151

152

Returns

153

-------

154

dict

155

A dictionary containing all the information obtained from validating

156

the docstring, including error codes and validation results.

157

158

Examples

159

--------

160

>>> result = validate('numpy.mean')

161

>>> if result['errors']:

162

... print(f"Found {len(result['errors'])} validation issues")

163

"""

164

```

165

166

## Validation Configuration

167

168

### Validation Rules

169

170

```python { .api }

171

def get_validation_checks(validation_checks):

172

"""

173

Process validation configuration into standardized format.

174

175

Converts validation check specifications (strings, sets, dicts)

176

into normalized format for use by validators.

177

178

Parameters

179

----------

180

validation_checks : str, set, or dict

181

Validation configuration:

182

- str: 'all' enables all checks, 'none' disables all

183

- set: Set of specific error codes to check

184

- dict: Mapping of check names to enabled status

185

186

Returns

187

-------

188

set

189

Set of enabled validation check codes

190

191

Examples

192

--------

193

>>> get_validation_checks('all')

194

{'GL01', 'GL02', 'GL03', ...}

195

196

>>> get_validation_checks({'SS01', 'PR01'})

197

{'SS01', 'PR01'}

198

"""

199

```

200

201

## Error Handling

202

203

### Error Functions

204

205

```python { .api }

206

def error(code: str, **kwargs) -> str:

207

"""

208

Generate error message for validation error code.

209

210

Creates formatted error message using the error code template

211

and provided keyword arguments for parameter substitution.

212

213

Parameters

214

----------

215

code : str

216

Error code (e.g., 'GL01', 'SS01', 'PR01')

217

**kwargs

218

Parameters for message template substitution

219

220

Returns

221

-------

222

str

223

Formatted error message

224

225

Examples

226

--------

227

>>> error('GL01')

228

'Docstring text (summary) should start in the line immediately after the opening quotes'

229

230

>>> error('PR01', param_name='x')

231

"No description given for parameter 'x'"

232

"""

233

234

def extract_ignore_validation_comments(lines: List[str]) -> Set[str]:

235

"""

236

Extract ignore validation comments from source code lines.

237

238

Parses special comments that disable validation for specific

239

error codes, supporting both inline and block ignore patterns.

240

241

Parameters

242

----------

243

lines : list of str

244

Source code lines to scan for ignore comments

245

246

Returns

247

-------

248

set of str

249

Set of error codes to ignore during validation

250

251

Examples

252

--------

253

>>> lines = [

254

... '# numpydoc ignore=GL01,SS01',

255

... 'def func():',

256

... ' pass # numpydoc ignore=PR01'

257

... ]

258

>>> extract_ignore_validation_comments(lines)

259

{'GL01', 'SS01', 'PR01'}

260

"""

261

```

262

263

## Utility Functions

264

265

### Object Handling

266

267

```python { .api }

268

def _unwrap(obj):

269

"""

270

Traverse obj.__wrapped__ until unwrapped object found.

271

272

Handles decorated functions and objects that use __wrapped__

273

to provide access to the original undecorated object.

274

275

Parameters

276

----------

277

obj : object

278

Object to unwrap

279

280

Returns

281

-------

282

object

283

Unwrapped object (original if no __wrapped__ attribute)

284

"""

285

286

def _check_desc(desc: List[str], code_no_desc: str, code_no_upper: str,

287

code_no_period: str, **kwargs) -> List[Tuple[str, str]]:

288

"""

289

Validate description content for proper formatting.

290

291

Checks description sections for common formatting issues like

292

missing descriptions, capitalization, and punctuation.

293

294

Parameters

295

----------

296

desc : list of str

297

Description lines to validate

298

code_no_desc : str

299

Error code for missing description

300

code_no_upper : str

301

Error code for improper capitalization

302

code_no_period : str

303

Error code for missing period

304

**kwargs

305

Additional parameters for error message formatting

306

307

Returns

308

-------

309

list of tuple

310

List of (error_code, error_message) validation errors

311

"""

312

```

313

314

## Error Codes and Messages

315

316

### Error Code Constants

317

318

```python { .api }

319

ERROR_MSGS: Dict[str, str]

320

"""

321

Dictionary mapping validation error codes to message templates.

322

323

Contains templates for all validation error messages with placeholders

324

for dynamic content like parameter names, section names, etc.

325

326

Key error codes include:

327

- GL01-GL08: General formatting issues

328

- SS01-SS06: Summary section issues

329

- ES01: Extended summary issues

330

- PR01-PR10: Parameter section issues

331

- RT01-RT05: Returns section issues

332

- YD01: Yields section issues

333

- EX01-EX04: Examples section issues

334

- SA01-SA04: See Also section issues

335

- """

336

337

ALLOWED_SECTIONS: List[str]

338

"""

339

List of allowed docstring sections in NumPy format.

340

341

Standard sections include: Summary, Extended Summary, Parameters,

342

Returns, Yields, Other Parameters, Raises, See Also, Notes,

343

References, Examples, and Attributes.

344

"""

345

346

DIRECTIVES: List[str] = ["versionadded", "versionchanged", "deprecated"]

347

"""List of allowed reStructuredText directives in docstrings."""

348

349

DIRECTIVE_PATTERN: Pattern[str]

350

"""Regular expression pattern for matching reStructuredText directives."""

351

352

IGNORE_STARTS: Tuple[str, ...] = (" ", "* ", "- ")

353

"""Tuple of line prefixes to ignore during certain validations."""

354

355

IGNORE_COMMENT_PATTERN: Pattern[str]

356

"""Regular expression for matching numpydoc ignore comments."""

357

```

358

359

## Usage Examples

360

361

### Basic Validation

362

363

```python

364

from numpydoc.validate import validate, Validator

365

366

# Validate a function

367

errors = validate('numpy.array')

368

for code, message in errors:

369

print(f"{code}: {message}")

370

371

# Use validator class directly

372

validator = Validator('scipy.stats.norm')

373

errors = validator.validate()

374

print(f"Found {len(errors)} validation issues")

375

```

376

377

### Custom Validation Configuration

378

379

```python

380

from numpydoc.validate import Validator, get_validation_checks

381

382

# Configure specific checks

383

checks = get_validation_checks({'GL01', 'SS01', 'PR01'})

384

validator = Validator('mymodule.func', validation_checks=checks)

385

errors = validator.validate()

386

387

# Validate with all checks enabled

388

validator = Validator('mymodule.func', validation_checks='all')

389

errors = validator.validate()

390

```

391

392

### Error Message Generation

393

394

```python

395

from numpydoc.validate import error

396

397

# Generate specific error messages

398

msg = error('GL01')

399

print(msg) # "Docstring text (summary) should start in the line..."

400

401

msg = error('PR01', param_name='x')

402

print(msg) # "No description given for parameter 'x'"

403

404

msg = error('RT02', returned_type='dict')

405

print(msg) # "The first line of the Returns section should contain only the type, unless multiple values are being returned"

406

```

407

408

### Ignore Comment Processing

409

410

```python

411

from numpydoc.validate import extract_ignore_validation_comments

412

413

source_lines = [

414

'# numpydoc ignore=GL01',

415

'def my_function(x, y):',

416

' """Function with validation issues."""',

417

' pass # numpydoc ignore=PR01,RT01'

418

]

419

420

ignored = extract_ignore_validation_comments(source_lines)

421

print(ignored) # {'GL01', 'PR01', 'RT01'}

422

```

423

424

### Integration with Sphinx

425

426

```python

427

# In Sphinx conf.py

428

numpydoc_validation_checks = {

429

'all', # Enable all validation

430

'GL08', # Check specific formatting

431

'SS01', # Check summary sections

432

'PR01', # Check parameter documentation

433

}

434

435

numpydoc_validation_exclude = {

436

r'\.tests\..*', # Exclude test modules

437

r'.*\._private_func$' # Exclude private functions

438

}

439

440

# Per-object validation overrides

441

numpydoc_validation_overrides = {

442

'mypackage.special_func': {'GL01': False}, # Disable GL01 for this function

443

'mypackage.legacy.*': {'all': False} # Disable all validation for legacy code

444

}

445

```

446

447

## Common Error Codes

448

449

### General Issues (GL01-GL08)

450

- **GL01**: Docstring text should start immediately after opening quotes

451

- **GL02**: Closing quotes should be on separate line

452

- **GL03**: Double line break found; blank line expected

453

- **GL08**: The object does not have a docstring

454

455

### Summary Issues (SS01-SS06)

456

- **SS01**: No summary found

457

- **SS02**: Summary does not start with a capital letter

458

- **SS03**: Summary does not end with a period

459

- **SS04**: Summary contains heading whitespaces

460

- **SS05**: Summary must start with infinitive verb, not third person

461

462

### Parameter Issues (PR01-PR10)

463

- **PR01**: Parameters {param_name} not documented

464

- **PR02**: Unknown parameters {param_name} in docstring

465

- **PR03**: Wrong parameters order

466

- **PR07**: Parameter {param_name} has no description

467

- **PR09**: Parameter {param_name} description should start with capital letter

468

469

### Return Issues (RT01-RT05)

470

- **RT01**: No Returns section found

471

- **RT02**: The first line should contain only the type

472

- **RT03**: Return value has no description

473

- **RT04**: Return value description should start with capital letter