or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

agents.mdbreaking-changes.mdcli.mddocstrings.mdextensions.mdindex.mdloaders.mdmodels.mdserialization.md

models.mddocs/

0

# Models

1

2

The core object models that represent Python API elements. These classes form the foundation of Griffe's object hierarchy and provide the primary interface for working with analyzed Python code structures.

3

4

## Capabilities

5

6

### Base Object Class

7

8

Abstract base class for all Griffe objects providing common functionality.

9

10

```python { .api }

11

class Object:

12

"""

13

Abstract base class representing a Python object.

14

15

Provides common functionality for all Griffe object types including

16

serialization, path resolution, and member management.

17

"""

18

19

def __init__(

20

self,

21

name: str,

22

*,

23

lineno: int | None = None,

24

endlineno: int | None = None,

25

runtime: bool = True,

26

docstring: Docstring | None = None,

27

parent: Module | Class | None = None,

28

) -> None:

29

"""

30

Initialize the object.

31

32

Args:

33

name: The object's name

34

lineno: Starting line number in source

35

endlineno: Ending line number in source

36

runtime: Whether object was found at runtime

37

docstring: Associated docstring

38

parent: Parent object (module or class)

39

"""

40

41

@property

42

def name(self) -> str:

43

"""The object's name."""

44

45

@property

46

def path(self) -> str:

47

"""The object's full dotted path."""

48

49

@property

50

def filepath(self) -> Path | None:

51

"""Path to the file containing this object."""

52

53

@property

54

def lineno(self) -> int | None:

55

"""Starting line number in source file."""

56

57

@property

58

def endlineno(self) -> int | None:

59

"""Ending line number in source file."""

60

61

@property

62

def docstring(self) -> Docstring | None:

63

"""The object's docstring."""

64

65

@property

66

def parent(self) -> Module | Class | None:

67

"""The object's parent (module or class)."""

68

69

@property

70

def module(self) -> Module:

71

"""The module containing this object."""

72

73

@property

74

def package(self) -> Module:

75

"""The top-level package containing this object."""

76

77

def serialize(self, **kwargs: Any) -> dict[str, Any]:

78

"""

79

Serialize the object to a dictionary.

80

81

Args:

82

**kwargs: Serialization options

83

84

Returns:

85

dict: Serialized representation

86

"""

87

88

def as_json(self, **kwargs: Any) -> str:

89

"""

90

Serialize the object to JSON string.

91

92

Args:

93

**kwargs: JSON serialization options

94

95

Returns:

96

str: JSON representation

97

"""

98

99

@classmethod

100

def from_json(cls, json_str: str, **kwargs: Any) -> Object:

101

"""

102

Deserialize an object from JSON.

103

104

Args:

105

json_str: JSON string to deserialize

106

**kwargs: Deserialization options

107

108

Returns:

109

Object: Deserialized object

110

"""

111

```

112

113

### Module Class

114

115

Represents a Python module containing other objects.

116

117

```python { .api }

118

class Module(Object):

119

"""

120

Class representing a Python module.

121

122

Contains attributes, classes, functions, and other module-level objects.

123

Serves as a container and namespace for Python code elements.

124

"""

125

126

def __init__(

127

self,

128

name: str,

129

*,

130

filepath: str | Path | None = None,

131

parent: Module | None = None,

132

**kwargs: Any,

133

) -> None:

134

"""

135

Initialize the module.

136

137

Args:

138

name: Module name

139

filepath: Path to the module file

140

parent: Parent module (for submodules)

141

**kwargs: Additional Object parameters

142

"""

143

144

@property

145

def filepath(self) -> Path | None:

146

"""Path to the module file."""

147

148

@property

149

def modules(self) -> dict[str, Module]:

150

"""Submodules contained in this module."""

151

152

@property

153

def classes(self) -> dict[str, Class]:

154

"""Classes defined in this module."""

155

156

@property

157

def functions(self) -> dict[str, Function]:

158

"""Functions defined in this module."""

159

160

@property

161

def attributes(self) -> dict[str, Attribute]:

162

"""Attributes defined in this module."""

163

164

@property

165

def aliases(self) -> dict[str, Alias]:

166

"""Aliases (imports) in this module."""

167

168

@property

169

def exports(self) -> set[str] | None:

170

"""Exported names (__all__ list)."""

171

172

def __getitem__(self, key: str) -> Object:

173

"""

174

Get a member by name.

175

176

Args:

177

key: Member name

178

179

Returns:

180

Object: The requested member

181

182

Raises:

183

KeyError: If member not found

184

"""

185

186

def __contains__(self, key: str) -> bool:

187

"""Check if module contains a member."""

188

```

189

190

### Class Class

191

192

Represents a Python class with methods, attributes, and inheritance.

193

194

```python { .api }

195

class Class(Object):

196

"""

197

Class representing a Python class.

198

199

Includes methods, attributes, decorators, base classes, and docstrings.

200

Supports inheritance relationships and method resolution order.

201

"""

202

203

def __init__(

204

self,

205

name: str,

206

*,

207

bases: list[Expr] | None = None,

208

decorators: list[Decorator] | None = None,

209

**kwargs: Any,

210

) -> None:

211

"""

212

Initialize the class.

213

214

Args:

215

name: Class name

216

bases: Base class expressions

217

decorators: Applied decorators

218

**kwargs: Additional Object parameters

219

"""

220

221

@property

222

def bases(self) -> list[Expr]:

223

"""Base class expressions."""

224

225

@property

226

def decorators(self) -> list[Decorator]:

227

"""Decorators applied to this class."""

228

229

@property

230

def methods(self) -> dict[str, Function]:

231

"""Methods defined in this class."""

232

233

@property

234

def attributes(self) -> dict[str, Attribute]:

235

"""Attributes defined in this class."""

236

237

@property

238

def classes(self) -> dict[str, Class]:

239

"""Nested classes defined in this class."""

240

241

@property

242

def aliases(self) -> dict[str, Alias]:

243

"""Aliases defined in this class."""

244

245

def mro(self) -> list[Class]:

246

"""

247

Get the method resolution order.

248

249

Returns:

250

list[Class]: Classes in MRO order

251

"""

252

253

def __getitem__(self, key: str) -> Object:

254

"""Get a member by name."""

255

256

def __contains__(self, key: str) -> bool:

257

"""Check if class contains a member."""

258

```

259

260

### Function Class

261

262

Represents a Python function or method with parameters and return information.

263

264

```python { .api }

265

class Function(Object):

266

"""

267

Class representing a Python function or method.

268

269

Contains parameters, return annotations, decorators, and docstrings.

270

Supports both regular functions and class methods.

271

"""

272

273

def __init__(

274

self,

275

name: str,

276

*,

277

parameters: Parameters | None = None,

278

returns: Expr | None = None,

279

decorators: list[Decorator] | None = None,

280

**kwargs: Any,

281

) -> None:

282

"""

283

Initialize the function.

284

285

Args:

286

name: Function name

287

parameters: Function parameters

288

returns: Return annotation expression

289

decorators: Applied decorators

290

**kwargs: Additional Object parameters

291

"""

292

293

@property

294

def parameters(self) -> Parameters:

295

"""Function parameters."""

296

297

@property

298

def returns(self) -> Expr | None:

299

"""Return type annotation."""

300

301

@property

302

def decorators(self) -> list[Decorator]:

303

"""Decorators applied to this function."""

304

305

@property

306

def signature(self) -> str:

307

"""

308

Get the function signature as a string.

309

310

Returns:

311

str: Function signature

312

"""

313

314

def __call__(self, *args: Any, **kwargs: Any) -> Any:

315

"""

316

Call the function if it's available at runtime.

317

318

Args:

319

*args: Positional arguments

320

**kwargs: Keyword arguments

321

322

Returns:

323

Any: Function return value

324

325

Raises:

326

RuntimeError: If function is not callable

327

"""

328

```

329

330

### Attribute Class

331

332

Represents a module, class, or instance attribute.

333

334

```python { .api }

335

class Attribute(Object):

336

"""

337

Class representing a Python attribute.

338

339

Stores attribute values, type annotations, and metadata for

340

module-level variables, class attributes, and instance variables.

341

"""

342

343

def __init__(

344

self,

345

name: str,

346

*,

347

annotation: Expr | None = None,

348

value: Expr | None = None,

349

**kwargs: Any,

350

) -> None:

351

"""

352

Initialize the attribute.

353

354

Args:

355

name: Attribute name

356

annotation: Type annotation expression

357

value: Value expression

358

**kwargs: Additional Object parameters

359

"""

360

361

@property

362

def annotation(self) -> Expr | None:

363

"""Type annotation expression."""

364

365

@property

366

def value(self) -> Expr | None:

367

"""Attribute value expression."""

368

369

@property

370

def has_type(self) -> bool:

371

"""Whether the attribute has a type annotation."""

372

373

@property

374

def has_value(self) -> bool:

375

"""Whether the attribute has a value."""

376

```

377

378

### Alias Class

379

380

Represents an alias or import reference to an object in another module.

381

382

```python { .api }

383

class Alias(Object):

384

"""

385

Class representing an alias or indirection to an object.

386

387

Handles imported objects and references, providing resolution

388

to the actual target objects when needed.

389

"""

390

391

def __init__(

392

self,

393

name: str,

394

target_path: str,

395

*,

396

lineno: int | None = None,

397

endlineno: int | None = None,

398

) -> None:

399

"""

400

Initialize the alias.

401

402

Args:

403

name: Alias name (local name)

404

target_path: Path to target object

405

lineno: Starting line number

406

endlineno: Ending line number

407

"""

408

409

@property

410

def target_path(self) -> str:

411

"""Path to the target object."""

412

413

@property

414

def target(self) -> Object | None:

415

"""The resolved target object."""

416

417

def resolve(self, *, external: bool | None = None) -> Object | None:

418

"""

419

Resolve the alias to its target object.

420

421

Args:

422

external: Whether to resolve external references

423

424

Returns:

425

Object | None: The target object if resolvable

426

427

Raises:

428

AliasResolutionError: If alias cannot be resolved

429

CyclicAliasError: If circular reference detected

430

"""

431

432

@property

433

def resolved(self) -> bool:

434

"""Whether the alias has been resolved."""

435

```

436

437

## Supporting Classes

438

439

### Decorator Class

440

441

Represents a decorator applied to functions or classes.

442

443

```python { .api }

444

class Decorator:

445

"""

446

Class representing a decorator applied to a function, method, or class.

447

448

Stores decorator expressions and metadata about decorator usage.

449

"""

450

451

def __init__(

452

self,

453

decorator: Expr,

454

*,

455

lineno: int | None = None,

456

endlineno: int | None = None,

457

) -> None:

458

"""

459

Initialize the decorator.

460

461

Args:

462

decorator: Decorator expression

463

lineno: Starting line number

464

endlineno: Ending line number

465

"""

466

467

@property

468

def value(self) -> Expr:

469

"""The decorator expression."""

470

471

@property

472

def lineno(self) -> int | None:

473

"""Starting line number."""

474

475

@property

476

def endlineno(self) -> int | None:

477

"""Ending line number."""

478

```

479

480

### Parameter and Parameters Classes

481

482

Represent function parameters and parameter collections.

483

484

```python { .api }

485

class Parameter:

486

"""

487

Class representing a function parameter.

488

489

Includes name, annotation, default value, and parameter kind.

490

"""

491

492

def __init__(

493

self,

494

name: str,

495

*,

496

annotation: Expr | None = None,

497

default: Expr | None = None,

498

kind: ParameterKind = ParameterKind.POSITIONAL_OR_KEYWORD,

499

) -> None:

500

"""

501

Initialize the parameter.

502

503

Args:

504

name: Parameter name

505

annotation: Type annotation

506

default: Default value expression

507

kind: Parameter kind (positional, keyword-only, etc.)

508

"""

509

510

@property

511

def name(self) -> str:

512

"""Parameter name."""

513

514

@property

515

def annotation(self) -> Expr | None:

516

"""Type annotation expression."""

517

518

@property

519

def default(self) -> Expr | None:

520

"""Default value expression."""

521

522

@property

523

def kind(self) -> ParameterKind:

524

"""Parameter kind."""

525

526

@property

527

def required(self) -> bool:

528

"""Whether parameter is required (no default)."""

529

530

class Parameters:

531

"""

532

Container class for function parameters.

533

534

Allows accessing parameters by position or name and provides

535

iteration over parameter collections.

536

"""

537

538

def __init__(self, *parameters: Parameter) -> None:

539

"""

540

Initialize parameters collection.

541

542

Args:

543

*parameters: Parameter objects

544

"""

545

546

def __iter__(self) -> Iterator[Parameter]:

547

"""Iterate over parameters."""

548

549

def __getitem__(self, key: int | str) -> Parameter:

550

"""

551

Get parameter by index or name.

552

553

Args:

554

key: Parameter index or name

555

556

Returns:

557

Parameter: The requested parameter

558

"""

559

560

def __len__(self) -> int:

561

"""Number of parameters."""

562

563

@property

564

def signature(self) -> str:

565

"""

566

Get parameters as signature string.

567

568

Returns:

569

str: Parameter signature

570

"""

571

```

572

573

### Docstring Class

574

575

Represents and parses docstrings with structured content.

576

577

```python { .api }

578

class Docstring:

579

"""

580

Class representing docstrings.

581

582

Provides parsing capabilities and access to structured

583

docstring content including sections and elements.

584

"""

585

586

def __init__(

587

self,

588

value: str,

589

*,

590

lineno: int | None = None,

591

endlineno: int | None = None,

592

parent: Object | None = None,

593

) -> None:

594

"""

595

Initialize the docstring.

596

597

Args:

598

value: Raw docstring text

599

lineno: Starting line number

600

endlineno: Ending line number

601

parent: Parent object containing this docstring

602

"""

603

604

@property

605

def value(self) -> str:

606

"""Raw docstring text."""

607

608

@property

609

def lineno(self) -> int | None:

610

"""Starting line number."""

611

612

@property

613

def endlineno(self) -> int | None:

614

"""Ending line number."""

615

616

def parse(

617

self,

618

parser: Parser | str | None = None,

619

**options: Any,

620

) -> list[DocstringSection]:

621

"""

622

Parse the docstring into structured sections.

623

624

Args:

625

parser: Parser to use (auto, google, numpy, sphinx)

626

**options: Parser-specific options

627

628

Returns:

629

list[DocstringSection]: Parsed sections

630

"""

631

```

632

633

## Usage Examples

634

635

### Working with Modules

636

637

```python

638

import griffe

639

640

# Load a module

641

module = griffe.load("requests")

642

643

# Access module properties

644

print(f"Module: {module.name}")

645

print(f"Path: {module.path}")

646

print(f"File: {module.filepath}")

647

648

# Iterate through classes

649

for class_name, class_obj in module.classes.items():

650

print(f"Class: {class_name}")

651

print(f" Methods: {list(class_obj.methods.keys())}")

652

653

# Access specific objects

654

session_class = module["Session"] # Get Session class

655

get_function = module["get"] # Get get function

656

```

657

658

### Analyzing Functions

659

660

```python

661

import griffe

662

663

# Load a specific function

664

func = griffe.load("requests.api.get")

665

666

print(f"Function: {func.name}")

667

print(f"Signature: {func.signature}")

668

669

# Examine parameters

670

for param in func.parameters:

671

print(f"Parameter: {param.name}")

672

print(f" Type: {param.annotation}")

673

print(f" Default: {param.default}")

674

print(f" Required: {param.required}")

675

676

# Check return type

677

if func.returns:

678

print(f"Returns: {func.returns}")

679

```

680

681

### Working with Classes

682

683

```python

684

import griffe

685

686

# Load a class

687

cls = griffe.load("requests.Session")

688

689

print(f"Class: {cls.name}")

690

print(f"Base classes: {[str(base) for base in cls.bases]}")

691

692

# Examine methods

693

for method_name, method in cls.methods.items():

694

print(f"Method: {method_name}")

695

print(f" Signature: {method.signature}")

696

697

# Check for specific decorators

698

for method in cls.methods.values():

699

for decorator in method.decorators:

700

if "property" in str(decorator.value):

701

print(f"Property method: {method.name}")

702

```

703

704

### Resolving Aliases

705

706

```python

707

import griffe

708

709

# Load module with imports

710

module = griffe.load("requests")

711

712

# Find aliases (imports)

713

for alias_name, alias in module.aliases.items():

714

print(f"Alias: {alias_name} -> {alias.target_path}")

715

716

# Resolve to actual object

717

target = alias.resolve()

718

if target:

719

print(f" Resolved to: {target.path}")

720

print(f" Type: {type(target).__name__}")

721

```

722

723

## Types

724

725

```python { .api }

726

from pathlib import Path

727

from typing import Any, Iterator

728

from enum import Enum

729

730

class ParameterKind(Enum):

731

"""Parameter kinds matching Python's inspect module."""

732

POSITIONAL_ONLY = 0

733

POSITIONAL_OR_KEYWORD = 1

734

VAR_POSITIONAL = 2

735

KEYWORD_ONLY = 3

736

VAR_KEYWORD = 4

737

738

class Kind(Enum):

739

"""Object kinds."""

740

MODULE = "module"

741

CLASS = "class"

742

FUNCTION = "function"

743

ATTRIBUTE = "attribute"

744

ALIAS = "alias"

745

746

# Expression type (defined in expressions module)

747

class Expr:

748

"""Base expression class."""

749

750

# Docstring section type (defined in docstrings module)

751

class DocstringSection:

752

"""Base docstring section class."""

753

```