0
# poetry-core
1
2
Poetry Core is a PEP 517 build backend implementation developed for Poetry. It provides a lightweight, fully compliant, self-contained package allowing PEP 517-compatible build frontends to build Poetry-managed projects.
3
4
## Package Information
5
6
- **Package Name**: poetry-core
7
- **Package Type**: PyPI
8
- **Language**: Python
9
- **Version**: 2.1.3
10
- **Installation**: `pip install poetry-core`
11
- **Main Package**: `poetry.core`
12
- **Build Backend**: `poetry.core.masonry.api`
13
14
## Core Imports
15
16
```python { .api }
17
# Version information
18
from poetry.core import __version__
19
20
# Factory for creating Poetry instances
21
from poetry.core.factory import Factory
22
23
# Main Poetry class
24
from poetry.core.poetry import Poetry
25
26
# Version constraints
27
from poetry.core.constraints.version import (
28
Version, VersionConstraint, VersionRange, VersionUnion,
29
EmptyConstraint as VersionEmptyConstraint,
30
parse_constraint, parse_marker_version_constraint
31
)
32
33
# Generic constraints
34
from poetry.core.constraints.generic import (
35
BaseConstraint, Constraint, AnyConstraint, EmptyConstraint,
36
MultiConstraint, UnionConstraint,
37
parse_constraint as parse_generic_constraint,
38
parse_extra_constraint
39
)
40
41
# Package types
42
from poetry.core.packages.dependency import Dependency
43
from poetry.core.packages.package import Package
44
from poetry.core.packages.project_package import ProjectPackage
45
from poetry.core.packages.specification import PackageSpecification
46
from poetry.core.packages.dependency_group import DependencyGroup, MAIN_GROUP
47
48
# Dependency types
49
from poetry.core.packages.directory_dependency import DirectoryDependency
50
from poetry.core.packages.file_dependency import FileDependency
51
from poetry.core.packages.url_dependency import URLDependency
52
from poetry.core.packages.vcs_dependency import VCSDependency
53
54
# Version and markers
55
from poetry.core.version.pep440 import PEP440Version, Release, ReleaseTag, LocalSegmentType
56
from poetry.core.version.markers import (
57
BaseMarker, AnyMarker, EmptyMarker, SingleMarker, MultiMarker, MarkerUnion,
58
parse_marker, intersection, union
59
)
60
from poetry.core.version.helpers import format_python_constraint, PYTHON_VERSION
61
62
# Configuration
63
from poetry.core.pyproject.toml import PyProjectTOML
64
from poetry.core.pyproject.tables import BuildSystem
65
66
# Builders
67
from poetry.core.masonry.builders.wheel import WheelBuilder
68
from poetry.core.masonry.builders.sdist import SdistBuilder
69
from poetry.core.masonry.builders.builder import Builder
70
71
# VCS Support
72
from poetry.core.vcs import get_vcs
73
from poetry.core.vcs.git import Git
74
75
# JSON Schema Validation
76
from poetry.core.json import validate_object, ValidationError
77
78
# SPDX License Support
79
from poetry.core.spdx.license import License
80
from poetry.core.spdx.helpers import license_by_id
81
82
# Exceptions
83
from poetry.core.exceptions import PoetryCoreError
84
```
85
86
## Basic Usage
87
88
### Creating a Poetry Project Instance
89
90
```python { .api }
91
from pathlib import Path
92
from poetry.core.factory import Factory
93
94
# Create Poetry instance from current directory
95
factory = Factory()
96
poetry = factory.create_poetry()
97
98
# Create from specific path
99
poetry = factory.create_poetry(Path("/path/to/project"))
100
101
# Get package information
102
package = poetry.package
103
print(f"Package: {package.name} v{package.version}")
104
print(f"Description: {package.description}")
105
```
106
107
### Working with Dependencies
108
109
```python { .api }
110
from poetry.core.packages.dependency import Dependency
111
from poetry.core.constraints.version import parse_constraint
112
113
# Create a simple dependency
114
dep = Dependency("requests", parse_constraint("^2.25.0"))
115
116
# Create from PEP 508 string
117
dep = Dependency.create_from_pep_508("requests>=2.25.0,<3.0.0")
118
119
# Check dependency properties
120
print(f"Name: {dep.name}")
121
print(f"Constraint: {dep.constraint}")
122
print(f"Optional: {dep.optional}")
123
```
124
125
## Capabilities
126
127
Poetry Core provides 10 major functional areas for building and managing Python packages:
128
129
### 1. PEP 517 Build Backend
130
131
Complete PEP 517 compliant build backend for building wheels and source distributions. Provides all required entry points for modern Python packaging tools.
132
133
**Key APIs**: `get_requires_for_build_wheel`, `build_wheel`, `build_sdist`, `build_editable`
134
135
[Build Backend API →](./build-backend.md)
136
137
### 2. Factory and Core Poetry
138
139
Central orchestration through the Factory class for creating Poetry instances and managing project configuration. The Poetry class represents a complete project context.
140
141
**Key APIs**: `Factory.create_poetry`, `Factory.get_package`, `Poetry.package`, `Poetry.pyproject`
142
143
[Factory and Core →](./factory-core.md)
144
145
### 3. Version Constraints
146
147
Comprehensive version constraint system supporting PEP 440 version specifications, ranges, unions, and complex constraint operations.
148
149
**Key APIs**: `parse_constraint`, `Version`, `VersionRange`, `VersionUnion`, `EmptyConstraint`
150
151
[Version Constraints →](./constraints.md)
152
153
### 4. Package System
154
155
Complete package specification system including dependencies, project packages, and various dependency types (VCS, file, directory, URL).
156
157
**Key APIs**: `PackageSpecification`, `Dependency`, `Package`, `ProjectPackage`, dependency types
158
159
[Package System →](./packages.md)
160
161
### 5. PEP 440 Version and Markers
162
163
Full PEP 440 version implementation with environment marker support for conditional dependencies and platform-specific requirements.
164
165
**Key APIs**: `PEP440Version`, `parse_marker`, `BaseMarker`, `SingleMarker`, `MultiMarker`
166
167
[Version System →](./version-system.md)
168
169
### 6. PyProject Configuration
170
171
Robust pyproject.toml parsing and management with full Poetry configuration support and build system handling.
172
173
**Key APIs**: `PyProjectTOML`, `BuildSystem`, configuration validation
174
175
[Configuration →](./configuration.md)
176
177
### 7. Package Builders
178
179
Modern package building system supporting wheels, source distributions, and editable installs with metadata generation.
180
181
**Key APIs**: `WheelBuilder`, `SdistBuilder`, `Builder.build`, metadata preparation
182
183
[Builders →](./builders.md)
184
185
### 8. VCS Support
186
187
Version control system integration for handling Git repositories and dependency sources from VCS.
188
189
**Key APIs**: `get_vcs`, `Git`, VCS dependency handling
190
191
[VCS Support →](./vcs-support.md)
192
193
### 9. JSON Schema Validation
194
195
Comprehensive JSON schema validation for Poetry configuration files and internal data structures.
196
197
**Key APIs**: `validate_object`, `ValidationError`, schema validation
198
199
[JSON Schema Validation →](./json-validation.md)
200
201
### 10. Utilities and Validation
202
203
Helper functions, SPDX license handling, version formatting, and various utility functions for package management.
204
205
**Key APIs**: `license_by_id`, `format_python_constraint`, `readme_content_type`, helpers
206
207
[Utilities →](./utilities.md)
208
209
## Type Definitions
210
211
### Core Types
212
213
```python
214
from typing import Any, Mapping, Union, Iterable
215
from pathlib import Path
216
217
# Common constraint types
218
DependencyConstraint = Union[str, Mapping[str, Any]]
219
DependencyConfig = Mapping[str, Union[list[DependencyConstraint], DependencyConstraint]]
220
221
# Package naming types
222
NormalizedName = str # From packaging.utils
223
DistributionName = str
224
225
# Version types
226
LocalSegmentType = Union[int, str]
227
228
# Configuration types
229
ConfigDict = dict[str, Any]
230
TomlData = dict[str, Any]
231
232
# Build types
233
BuildIncludeFile = Any # Internal build file representation
234
MetadataPath = Path
235
``` { .api }
236
237
### Exception Types
238
239
```python { .api }
240
# Base exception
241
class PoetryCoreError(Exception):
242
"""Base exception for all Poetry Core errors"""
243
244
# Version and constraint exceptions
245
class InvalidVersionError(ValueError):
246
"""Invalid version format"""
247
248
class ParseConstraintError(ValueError):
249
"""Constraint parsing error"""
250
251
# Marker and requirement exceptions
252
class InvalidMarkerError(ValueError):
253
"""Invalid PEP 508 marker"""
254
255
class UndefinedComparisonError(ValueError):
256
"""Undefined comparison in marker"""
257
258
class UndefinedEnvironmentNameError(ValueError):
259
"""Undefined environment name in marker"""
260
261
class InvalidRequirementError(ValueError):
262
"""Invalid requirement specification"""
263
264
# Configuration exceptions
265
class PyProjectError(PoetryCoreError):
266
"""PyProject configuration error"""
267
268
# JSON schema validation
269
class ValidationError(ValueError):
270
"""JSON schema validation error"""
271
272
# VCS exceptions
273
class GitError(RuntimeError):
274
"""Git operation errors"""
275
276
# Module/package discovery
277
class ModuleOrPackageNotFoundError(ValueError):
278
"""Module or package not found during discovery"""
279
```
280
281
### Dependency Group Constants
282
283
```python { .api }
284
# Dependency group identifiers
285
MAIN_GROUP = "main" # Main dependency group
286
```
287
288
## Common Patterns
289
290
### Building Packages Programmatically
291
292
```python { .api }
293
from pathlib import Path
294
from poetry.core.factory import Factory
295
from poetry.core.masonry.builders.wheel import WheelBuilder
296
from poetry.core.masonry.builders.sdist import SdistBuilder
297
298
# Create Poetry instance
299
poetry = Factory().create_poetry(Path("/path/to/project"))
300
301
# Build wheel
302
wheel_path = WheelBuilder.make_in(
303
poetry,
304
Path("./dist"),
305
config_settings={"--build-option": ["--plat-name", "linux_x86_64"]}
306
)
307
308
# Build source distribution
309
sdist_builder = SdistBuilder(poetry)
310
sdist_path = sdist_builder.build(Path("./dist"))
311
```
312
313
### Working with Version Constraints
314
315
```python { .api }
316
from poetry.core.constraints.version import parse_constraint, Version
317
318
# Parse various constraint formats
319
constraint1 = parse_constraint(">=1.2.0,<2.0.0")
320
constraint2 = parse_constraint("^1.5.0") # Poetry caret syntax
321
constraint3 = parse_constraint("~1.5.2") # Tilde syntax
322
323
# Check version satisfaction
324
version = Version.parse("1.6.3")
325
print(constraint1.allows(version)) # True
326
print(constraint2.allows(version)) # True
327
328
# Combine constraints
329
intersection = constraint1.intersect(constraint2)
330
union = constraint1.union(constraint3)
331
```
332
333
### Parsing Project Configuration
334
335
```python { .api }
336
from pathlib import Path
337
from poetry.core.pyproject.toml import PyProjectTOML
338
from poetry.core.factory import Factory
339
340
# Load project configuration
341
pyproject_path = Path("pyproject.toml")
342
pyproject = PyProjectTOML(pyproject_path)
343
344
# Access Poetry configuration
345
poetry_config = pyproject.poetry_config
346
build_system = pyproject.build_system
347
348
# Validate configuration
349
errors = Factory.validate(pyproject.data)
350
if errors:
351
for section, section_errors in errors.items():
352
print(f"Errors in {section}: {section_errors}")
353
```
354
355
## Dependencies
356
357
Poetry Core is designed to be self-contained with minimal external dependencies:
358
359
- Python 3.8+
360
- `packaging` - For version parsing and normalization
361
- `tomli` (Python < 3.11) / `tomllib` (Python >= 3.11) - For TOML parsing
362
- Internal vendored dependencies for isolated operation
363
364
## Related Documentation
365
366
- [PEP 517 - A build-system independent format for source trees](https://pep.python.org/pep-0517/)
367
- [PEP 440 - Version Identification and Dependency Specification](https://pep.python.org/pep-0440/)
368
- [PEP 508 - Dependency specification for Python Software Packages](https://pep.python.org/pep-0508/)
369
- [Poetry Documentation](https://python-poetry.org/docs/)