or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

base-classes.mdconfiguration.mddocument.mdfigures.mdindex.mdlayout.mdlists.mdmath.mdquantities.mdreferences.mdsectioning.mdtables.mdtext-formatting.mdtikz.mdutilities.md

base-classes.mddocs/

0

# Base Classes and Object Model

1

2

Fundamental base classes that provide the foundation for all PyLaTeX objects, including the core inheritance hierarchies and common functionality. Understanding these base classes is essential for extending PyLaTeX or creating custom LaTeX elements.

3

4

## Capabilities

5

6

### Core Base Class

7

8

The foundational class for all LaTeX objects in PyLaTeX, providing common functionality for code generation and package management.

9

10

```python { .api }

11

class LatexObject:

12

def __init__(self):

13

"""Base class for all LaTeX objects."""

14

15

def dumps(self):

16

"""

17

Return LaTeX representation as string.

18

19

Returns:

20

- str: LaTeX code for this object

21

"""

22

23

def dump(self, file_w):

24

"""

25

Write LaTeX representation to file.

26

27

Parameters:

28

- file_w: file-like object to write to

29

"""

30

31

def generate_tex(self, filepath):

32

"""

33

Generate standalone .tex file.

34

35

Parameters:

36

- filepath: str, output file path

37

"""

38

39

def dumps_packages(self):

40

"""

41

Get required packages as LaTeX string.

42

43

Returns:

44

- str: LaTeX package declarations

45

"""

46

47

def dumps_as_content(self):

48

"""

49

String representation with paragraph formatting.

50

51

Returns:

52

- str: formatted content

53

"""

54

```

55

56

### Container Base Class

57

58

Base class for LaTeX objects that can contain other objects, providing list-like functionality and content management.

59

60

```python { .api }

61

class Container(LatexObject):

62

def __init__(self, *, data=None):

63

"""

64

Container for other LaTeX objects.

65

66

Parameters:

67

- data: list or single object, initial content

68

"""

69

70

def create(self, child):

71

"""

72

Context manager for adding child objects.

73

74

Parameters:

75

- child: LatexObject to add and return

76

77

Returns:

78

- child object for use in with statement

79

"""

80

81

def dumps_content(self, **kwargs):

82

"""

83

Represent container contents as LaTeX.

84

85

Returns:

86

- str: LaTeX code for all contained objects

87

"""

88

89

# List-like methods

90

def append(self, item): ...

91

def extend(self, items): ...

92

def insert(self, index, item): ...

93

def remove(self, item): ...

94

def pop(self, index=-1): ...

95

def clear(self): ...

96

def index(self, item): ...

97

def count(self, item): ...

98

```

99

100

Usage example:

101

102

```python

103

from pylatex.base_classes import Container

104

from pylatex import Section

105

106

# Using create() context manager

107

container = Container()

108

with container.create(Section('Title')) as section:

109

section.append('Content inside the section')

110

111

# Direct manipulation

112

container.append('Some text')

113

container.extend(['More text', 'Even more text'])

114

```

115

116

### Environment Base Class

117

118

Base class for LaTeX environments that use \\begin{} and \\end{} delimiters.

119

120

```python { .api }

121

class Environment(Container):

122

def __init__(self, *, options=None, arguments=None,

123

start_arguments=None, **kwargs):

124

"""

125

LaTeX environment with begin/end delimiters.

126

127

Parameters:

128

- options: Options in square brackets

129

- arguments: Arguments in curly braces

130

- start_arguments: Arguments only for \\begin command

131

"""

132

133

# Properties

134

omit_if_empty = False # Skip output if environment is empty

135

content_separator = "%\n" # Separator between content items

136

```

137

138

### Command Base Classes

139

140

Base classes for LaTeX commands with various argument and option handling patterns.

141

142

```python { .api }

143

class CommandBase(LatexObject):

144

def __init__(self, arguments=None, options=None, *,

145

extra_arguments=None):

146

"""

147

Base class for LaTeX commands.

148

149

Parameters:

150

- arguments: Command arguments

151

- options: Command options

152

- extra_arguments: Additional arguments

153

"""

154

155

class Command(CommandBase):

156

def __init__(self, command=None, arguments=None, options=None, *,

157

extra_arguments=None, packages=None):

158

"""

159

Generic LaTeX command for one-off usage.

160

161

Parameters:

162

- command: str, LaTeX command name

163

- arguments: Command arguments

164

- options: Command options

165

- extra_arguments: Additional arguments

166

- packages: Required packages

167

"""

168

169

class UnsafeCommand(Command):

170

"""Command that doesn't escape arguments/options by default."""

171

escape = False

172

```

173

174

Usage examples:

175

176

```python

177

from pylatex.base_classes import Command, UnsafeCommand

178

179

# Generic command

180

cmd = Command('textbf', arguments='bold text')

181

# Generates: \textbf{bold text}

182

183

# Custom command with options

184

cmd = Command('includegraphics',

185

arguments='image.png',

186

options=['width=0.5\\textwidth', 'center'])

187

# Generates: \includegraphics[width=0.5\textwidth,center]{image.png}

188

189

# Unsafe command (no escaping)

190

unsafe_cmd = UnsafeCommand('raw', arguments='$x^2$')

191

```

192

193

### Container Command

194

195

Command that contains data, combining command functionality with container capabilities.

196

197

```python { .api }

198

class ContainerCommand(Container):

199

def __init__(self, arguments=None, options=None, *, data=None, **kwargs):

200

"""

201

Command that contains data: \\CommandName{data}.

202

203

Parameters:

204

- arguments: Command arguments

205

- options: Command options

206

- data: Container content

207

"""

208

```

209

210

### Float Base Class

211

212

Base class for floating environments like figures and tables.

213

214

```python { .api }

215

class Float(Environment):

216

def __init__(self, *, position=None, **kwargs):

217

"""

218

Base class for floating environments.

219

220

Parameters:

221

- position: str, float position specifier ('h', 't', 'b', 'p', '!')

222

"""

223

224

def add_caption(self, caption):

225

"""

226

Add caption to float.

227

228

Parameters:

229

- caption: str or LatexObject, caption content

230

"""

231

```

232

233

### Parameter Classes

234

235

Classes for handling LaTeX command options and arguments with different formatting requirements.

236

237

```python { .api }

238

class Options:

239

def __init__(self, *args, **kwargs):

240

"""

241

LaTeX command options in square brackets [option1,option2].

242

"""

243

244

class SpecialOptions(Options):

245

"""Options separated by '][' instead of ',' -> [option1][option2]"""

246

247

class Arguments:

248

def __init__(self, *args, **kwargs):

249

"""

250

LaTeX command arguments in curly braces {arg1}{arg2}.

251

"""

252

253

class SpecialArguments(Arguments):

254

"""Arguments separated by ',' instead of '}{' -> {arg1,arg2}"""

255

```

256

257

## Object Hierarchy

258

259

The PyLaTeX object hierarchy follows this structure:

260

261

```

262

LatexObject (base)

263

├── CommandBase

264

│ ├── Command

265

│ │ └── UnsafeCommand

266

│ └── Various command classes (Package, etc.)

267

├── Container

268

│ ├── Environment

269

│ │ ├── Document

270

│ │ ├── Section

271

│ │ ├── Figure (Float)

272

│ │ └── Various environments

273

│ └── ContainerCommand

274

│ └── TextColor, etc.

275

└── Fragment (special container)

276

```

277

278

## Extending PyLaTeX

279

280

Create custom LaTeX elements by inheriting from appropriate base classes:

281

282

```python

283

from pylatex.base_classes import Environment, Command

284

285

class CustomEnvironment(Environment):

286

"""Custom LaTeX environment."""

287

288

_latex_name = "myenvironment" # LaTeX environment name

289

packages = [Package('mypackage')] # Required packages

290

291

def __init__(self, title, **kwargs):

292

super().__init__(arguments=title, **kwargs)

293

294

class CustomCommand(Command):

295

"""Custom LaTeX command."""

296

297

def __init__(self, text):

298

super().__init__('mycommand', arguments=text)

299

```

300

301

## Common Patterns

302

303

### Context Manager Usage

304

305

Many PyLaTeX objects support context manager syntax for cleaner code:

306

307

```python

308

from pylatex import Document, Section

309

310

doc = Document()

311

312

with doc.create(Section('Introduction')) as intro:

313

intro.append('This is automatically added to the section')

314

with intro.create(Subsection('Background')) as bg:

315

bg.append('Nested content')

316

```

317

318

### Package Management

319

320

Objects automatically manage their package dependencies:

321

322

```python

323

from pylatex.math import Matrix

324

from pylatex import Document

325

326

doc = Document()

327

matrix = Matrix([[1, 2], [3, 4]])

328

doc.append(matrix)

329

330

# 'amsmath' package is automatically added to doc.packages

331

print([p.name for p in doc.packages]) # Includes 'amsmath'

332

```

333

334

### Escaping Control

335

336

Control LaTeX character escaping on a per-object basis:

337

338

```python

339

from pylatex.base_classes import Command

340

from pylatex.utils import NoEscape

341

342

# Escaped by default

343

cmd1 = Command('textbf', arguments='Text with $pecial chars')

344

345

# No escaping

346

cmd2 = Command('textbf', arguments=NoEscape('Text with $pecial chars'))

347

348

# Object-level escaping control

349

class MyCommand(Command):

350

escape = False # Never escape arguments

351

```