0
# Core API
1
2
Core Poetry classes and factory methods for creating and managing Python projects programmatically. These components form the foundation of Poetry's functionality and provide the primary interfaces for programmatic usage.
3
4
## Capabilities
5
6
### Poetry Class
7
8
The central class representing a Poetry project, providing access to all project-related functionality including configuration, dependencies, build system, and metadata.
9
10
```python { .api }
11
class Poetry:
12
"""
13
Main Poetry project representation extending poetry-core functionality.
14
15
Provides access to project configuration, dependencies, lock file management,
16
repository pools, and build system integration.
17
"""
18
VERSION: str # Poetry version
19
20
def __init__(self, file: Path, local_config: dict, package: ProjectPackage,
21
locker: Locker, config: Config, disable_cache: bool = False):
22
"""
23
Initialize Poetry instance.
24
25
Args:
26
file: Path to pyproject.toml file
27
local_config: Project-specific configuration
28
package: Project package metadata
29
locker: Lock file manager
30
config: Global configuration
31
disable_cache: Whether to disable caching
32
"""
33
34
@property
35
def pyproject(self) -> PyProjectTOML:
36
"""Access to enhanced pyproject.toml handler."""
37
38
@property
39
def file(self) -> TOMLFile:
40
"""Access to pyproject.toml file handler."""
41
42
@property
43
def locker(self) -> Locker:
44
"""Access to lock file manager."""
45
46
@property
47
def pool(self) -> RepositoryPool:
48
"""Access to repository pool for package sources."""
49
50
@property
51
def config(self) -> Config:
52
"""Access to configuration manager."""
53
54
@property
55
def disable_cache(self) -> bool:
56
"""Whether caching is disabled."""
57
58
def set_locker(self, locker: Locker) -> Poetry:
59
"""
60
Configure lock file handler.
61
62
Args:
63
locker: Lock file manager instance
64
65
Returns:
66
Self for method chaining
67
"""
68
69
def set_pool(self, pool: RepositoryPool) -> Poetry:
70
"""
71
Set repository pool for package sources.
72
73
Args:
74
pool: Repository pool instance
75
76
Returns:
77
Self for method chaining
78
"""
79
80
def set_config(self, config: Config) -> Poetry:
81
"""
82
Set configuration manager.
83
84
Args:
85
config: Configuration instance
86
87
Returns:
88
Self for method chaining
89
"""
90
91
def get_sources(self) -> list[Source]:
92
"""
93
Get configured package sources from pyproject.toml.
94
95
Returns:
96
List of configured package sources
97
"""
98
```
99
100
#### Usage Example
101
102
```python
103
from poetry.factory import Factory
104
from pathlib import Path
105
106
# Create Poetry instance
107
poetry = Factory().create_poetry(cwd=Path("/path/to/project"))
108
109
# Access project information
110
print(f"Project: {poetry.package.name} v{poetry.package.version}")
111
print(f"Poetry version: {poetry.VERSION}")
112
113
# Check if project is locked
114
if poetry.locker.is_locked():
115
print("Project has lock file")
116
117
# Get package sources
118
sources = poetry.get_sources()
119
for source in sources:
120
print(f"Source: {source.name} -> {source.url}")
121
```
122
123
### Factory Class
124
125
Factory class for creating Poetry instances and related components. Provides the primary entry points for programmatic Poetry usage.
126
127
```python { .api }
128
class Factory:
129
"""
130
Factory for creating Poetry instances and components.
131
132
Handles discovery of Poetry projects, validation of configuration,
133
and creation of properly configured Poetry instances.
134
"""
135
136
def create_poetry(self, cwd: Path = None, with_groups: bool = True,
137
io = None, disable_plugins: bool = False,
138
disable_cache: bool = False) -> Poetry:
139
"""
140
Create Poetry instance from project directory.
141
142
Args:
143
cwd: Project directory path (default: current directory)
144
with_groups: Whether to include dependency groups
145
io: IO interface for output
146
disable_plugins: Whether to disable plugin loading
147
disable_cache: Whether to disable caching
148
149
Returns:
150
Configured Poetry instance
151
152
Raises:
153
PoetryError: If pyproject.toml not found or invalid
154
"""
155
156
def create_pool(self, config: Config, sources = None, io = None,
157
disable_cache: bool = False) -> RepositoryPool:
158
"""
159
Create repository pool for package sources.
160
161
Args:
162
config: Configuration instance
163
sources: Optional list of package sources
164
io: IO interface for output
165
disable_cache: Whether to disable caching
166
167
Returns:
168
Configured repository pool
169
"""
170
171
def create_package_source(self, source: dict, config: Config,
172
disable_cache: bool = False):
173
"""
174
Create package source from configuration.
175
176
Args:
177
source: Source configuration dictionary
178
config: Configuration instance
179
disable_cache: Whether to disable caching
180
181
Returns:
182
Package source instance
183
"""
184
185
def create_pyproject_from_package(self, package) -> dict:
186
"""
187
Generate pyproject.toml data from package metadata.
188
189
Args:
190
package: Package instance
191
192
Returns:
193
Dictionary containing pyproject.toml data
194
"""
195
196
def validate(self, toml_data: dict, strict: bool = False) -> dict:
197
"""
198
Validate Poetry configuration against schema.
199
200
Args:
201
toml_data: TOML configuration data
202
strict: Whether to use strict validation
203
204
Returns:
205
Validated configuration data
206
207
Raises:
208
PoetryError: If validation fails
209
"""
210
```
211
212
#### Usage Example
213
214
```python
215
from poetry.factory import Factory
216
from poetry.config.config import Config
217
from pathlib import Path
218
219
factory = Factory()
220
221
# Create Poetry instance from current directory
222
poetry = factory.create_poetry()
223
224
# Create Poetry instance from specific directory
225
poetry = factory.create_poetry(
226
cwd=Path("/path/to/project"),
227
disable_cache=True
228
)
229
230
# Create repository pool
231
config = Config.create()
232
pool = factory.create_pool(config)
233
234
# Validate configuration
235
toml_data = {
236
"tool": {
237
"poetry": {
238
"name": "my-project",
239
"version": "1.0.0",
240
"description": "My project description"
241
}
242
}
243
}
244
validated_data = factory.validate(toml_data)
245
```
246
247
### Project Discovery
248
249
Helper functions for discovering and working with Poetry projects.
250
251
```python { .api }
252
def locate_config_file(cwd: Path = None) -> Path:
253
"""
254
Locate pyproject.toml file in directory hierarchy.
255
256
Args:
257
cwd: Starting directory (default: current directory)
258
259
Returns:
260
Path to pyproject.toml file
261
262
Raises:
263
PoetryError: If no pyproject.toml found
264
"""
265
266
def validate_pyproject_file(file_path: Path) -> dict:
267
"""
268
Validate pyproject.toml file contains Poetry configuration.
269
270
Args:
271
file_path: Path to pyproject.toml file
272
273
Returns:
274
Parsed TOML data
275
276
Raises:
277
PoetryError: If file invalid or missing Poetry section
278
"""
279
```
280
281
## Integration Patterns
282
283
### Context Manager Usage
284
285
```python
286
from poetry.factory import Factory
287
from pathlib import Path
288
289
def with_poetry_project(project_path: Path):
290
"""Example context manager pattern for Poetry projects."""
291
poetry = Factory().create_poetry(cwd=project_path)
292
try:
293
yield poetry
294
finally:
295
# Cleanup if needed
296
pass
297
298
# Usage
299
with with_poetry_project(Path("/path/to/project")) as poetry:
300
print(f"Working with {poetry.package.name}")
301
# Perform operations
302
```
303
304
### Dependency Analysis
305
306
```python
307
from poetry.factory import Factory
308
309
def analyze_project_dependencies(project_path):
310
"""Analyze project dependencies."""
311
poetry = Factory().create_poetry(cwd=project_path)
312
313
# Get all dependencies
314
dependencies = poetry.package.all_requires
315
316
print(f"Project: {poetry.package.name}")
317
print(f"Dependencies: {len(dependencies)}")
318
319
for dep in dependencies:
320
print(f" {dep.name}: {dep.constraint}")
321
322
# Check lock file status
323
if poetry.locker.is_locked() and poetry.locker.is_fresh():
324
print("Lock file is up to date")
325
else:
326
print("Lock file needs update")
327
```
328
329
## Error Handling
330
331
The core API raises specific exceptions for different error conditions:
332
333
```python { .api }
334
class PoetryError(Exception):
335
"""Base exception for Poetry-specific errors."""
336
337
class InvalidProjectError(PoetryError):
338
"""Raised when project configuration is invalid."""
339
340
class ProjectNotFoundError(PoetryError):
341
"""Raised when Poetry project cannot be found."""
342
```
343
344
Common error scenarios include:
345
- Missing or invalid pyproject.toml files
346
- Projects without Poetry configuration section
347
- Invalid dependency specifications
348
- Circular dependency detection
349
- Configuration validation failures