Important
This PEP is a historical document. The up-to-date, canonical spec,Version specifiers, is maintained on thePyPA specs page.
×
See thePyPA specification update process for how to propose changes.
This PEP describes a scheme for identifying versions of Python softwaredistributions, and declaring dependencies on particular versions.
This document addresses several limitations of the previous attempt at astandardized approach to versioning, as described inPEP 345 andPEP 386.
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”,“SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in thisdocument are to be interpreted as described inRFC 2119.
“Projects” are software components that are made available for integration.Projects include Python libraries, frameworks, scripts, plugins,applications, collections of data or other resources, and variouscombinations thereof. Public Python projects are typically registered onthePython Package Index.
“Releases” are uniquely identified snapshots of a project.
“Distributions” are the packaged files which are used to publishand distribute a release.
“Build tools” are automated tools intended to run on development systems,producing source and binary distribution archives. Build tools may also beinvoked by integration tools in order to build software distributed assdists rather than prebuilt binary archives.
“Index servers” are active distribution registries which publish version anddependency metadata and place constraints on the permitted metadata.
“Publication tools” are automated tools intended to run on developmentsystems and upload source and binary distribution archives to index servers.
“Installation tools” are integration tools specifically intended to run ondeployment targets, consuming source and binary distribution archives froman index server or other designated location and deploying them to the targetsystem.
“Automated tools” is a collective term covering build tools, index servers,publication tools, integration tools and any other software that producesor consumes distribution version and dependency metadata.
Distributions are identified by a public version identifier whichsupports all defined version comparison operations
The version scheme is used both to describe the distribution versionprovided by a particular distribution archive, as well as to placeconstraints on the version of dependencies needed in order to build orrun the software.
The canonical public version identifiers MUST comply with the followingscheme:
[N!]N(.N)*[{a|b|rc}N][.postN][.devN]Public version identifiers MUST NOT include leading or trailing whitespace.
Public version identifiers MUST be unique within a given distribution.
Installation tools SHOULD ignore any public versions which do not comply withthis scheme but MUST also include the normalizations specified below.Installation tools MAY warn the user when non-compliant or ambiguous versionsare detected.
See alsoAppendixB:Parsingversionstringswithregularexpressionswhich provides a regular expression to check strict conformance with thecanonical format, as well as a more permissive regular expression acceptinginputs that may require subsequent normalization.
Public version identifiers are separated into up to five segments:
N!N(.N)*{a|b|rc}N.postN.devNAny given release will be a “final release”, “pre-release”, “post-release” or“developmental release” as defined in the following sections.
All numeric components MUST be non-negative integers represented as sequencesof ASCII digits.
All numeric components MUST be interpreted and ordered according to theirnumeric value, not as text strings.
All numeric components MAY be zero. Except as described below for therelease segment, a numeric component of zero has no special significanceaside from always being the lowest possible value in the version ordering.
Note
Some hard to read version identifiers are permitted by this scheme inorder to better accommodate the wide range of versioning practicesacross existing public and private Python projects.
Accordingly, some of the versioning practices which are technicallypermitted by the PEP are strongly discouraged for new projects. Wherethis is the case, the relevant details are noted in the followingsections.
Local version identifiers MUST comply with the following scheme:
<publicversionidentifier>[+<localversionlabel>]
They consist of a normal public version identifier (as defined in theprevious section), along with an arbitrary “local version label”, separatedfrom the public version identifier by a plus. Local version labels haveno specific semantics assigned, but some syntactic restrictions are imposed.
Local version identifiers are used to denote fully API (and, if applicable,ABI) compatible patched versions of upstream projects. For example, thesemay be created by application developers and system integrators by applyingspecific backported bug fixes when upgrading to a new upstream release wouldbe too disruptive to the application or other integrated system (such as aLinux distribution).
The inclusion of the local version label makes it possible to differentiateupstream releases from potentially altered rebuilds by downstreamintegrators. The use of a local version identifier does not affect the kindof a release but, when applied to a source distribution, does indicate thatit may not contain the exact same code as the corresponding upstream release.
To ensure local version identifiers can be readily incorporated as part offilenames and URLs, and to avoid formatting inconsistencies in hexadecimalhash representations, local version labels MUST be limited to the followingset of permitted characters:
[a-zA-Z])[0-9]).)Local version labels MUST start and end with an ASCII letter or digit.
Comparison and ordering of local versions considers each segment of the localversion (divided by a.) separately. If a segment consists entirely ofASCII digits then that section should be considered an integer for comparisonpurposes and if a segment contains any ASCII letters then that segment iscompared lexicographically with case insensitivity. When comparing a numericand lexicographic segment, the numeric section always compares as greater thanthe lexicographic segment. Additionally a local version with a great number ofsegments will always compare as greater than a local version with fewersegments, as long as the shorter local version’s segments match the beginningof the longer local version’s segments exactly.
An “upstream project” is a project that defines its own public versions. A“downstream project” is one which tracks and redistributes an upstream project,potentially backporting security and bug fixes from later versions of theupstream project.
Local version identifiers SHOULD NOT be used when publishing upstreamprojects to a public index server, but MAY be used to identify privatebuilds created directly from the project source. Localversion identifiers SHOULD be used by downstream projects when releasing aversion that is API compatible with the version of the upstream projectidentified by the public version identifier, but contains additional changes(such as bug fixes). As the Python Package Index is intended solely forindexing and hosting upstream projects, it MUST NOT allow the use of localversion identifiers.
Source distributions using a local version identifier SHOULD provide thepython.integrator extension metadata (as defined inPEP 459).
A version identifier that consists solely of a release segment and optionallyan epoch identifier is termed a “final release”.
The release segment consists of one or more non-negative integervalues, separated by dots:
N(.N)*
Final releases within a project MUST be numbered in a consistentlyincreasing fashion, otherwise automated tools will not be able to upgradethem correctly.
Comparison and ordering of release segments considers the numeric valueof each component of the release segment in turn. When comparing releasesegments with different numbers of components, the shorter segment ispadded out with additional zeros as necessary.
While any number of additional components after the first are permittedunder this scheme, the most common variants are to use two components(“major.minor”) or three components (“major.minor.micro”).
For example:
0.90.9.10.9.2...0.9.100.9.111.01.0.11.12.02.0.1...
A release series is any set of final release numbers that start with acommon prefix. For example,3.3.1,3.3.5 and3.3.9.45 are allpart of the3.3 release series.
Note
X.Y andX.Y.0 are not considered distinct release numbers, asthe release segment comparison rules implicit expand the two componentform toX.Y.0 when comparing it to any release segment that includesthree components.
Date based release segments are also permitted. An example of a date basedrelease scheme using the year and month of the release:
2012.42012.72012.102013.12013.6...
Some projects use an “alpha, beta, release candidate” pre-release cycle tosupport testing by their users prior to a final release.
If used as part of a project’s development cycle, these pre-releases areindicated by including a pre-release segment in the version identifier:
X.YaN# Alpha releaseX.YbN# Beta releaseX.YrcN# Release CandidateX.Y# Final release
A version identifier that consists solely of a release segment and apre-release segment is termed a “pre-release”.
The pre-release segment consists of an alphabetical identifier for thepre-release phase, along with a non-negative integer value. Pre-releases fora given release are ordered first by phase (alpha, beta, release candidate)and then by the numerical component within that phase.
Installation tools MAY accept bothc andrc releases for a commonrelease segment in order to handle some existing legacy distributions.
Installation tools SHOULD interpretc versions as being equivalent torc versions (that is,c1 indicates the same version asrc1).
Build tools, publication tools and index servers SHOULD disallow the creationof bothrc andc releases for a common release segment.
Some projects use post-releases to address minor errors in a final releasethat do not affect the distributed software (for example, correcting an errorin the release notes).
If used as part of a project’s development cycle, these post-releases areindicated by including a post-release segment in the version identifier:
X.Y.postN# Post-release
A version identifier that includes a post-release segment without adevelopmental release segment is termed a “post-release”.
The post-release segment consists of the string.post, followed by anon-negative integer value. Post-releases are ordered by theirnumerical component, immediately following the corresponding release,and ahead of any subsequent release.
Note
The use of post-releases to publish maintenance releases containingactual bug fixes is strongly discouraged. In general, it is betterto use a longer release number and increment the final componentfor each maintenance release.
Post-releases are also permitted for pre-releases:
X.YaN.postM# Post-release of an alpha releaseX.YbN.postM# Post-release of a beta releaseX.YrcN.postM# Post-release of a release candidate
Note
Creating post-releases of pre-releases is strongly discouraged, asit makes the version identifier difficult to parse for human readers.In general, it is substantially clearer to simply create a newpre-release by incrementing the numeric component.
Some projects make regular developmental releases, and system packagers(especially for Linux distributions) may wish to create early releasesdirectly from source control which do not conflict with later projectreleases.
If used as part of a project’s development cycle, these developmentalreleases are indicated by including a developmental release segment in theversion identifier:
X.Y.devN# Developmental release
A version identifier that includes a developmental release segment istermed a “developmental release”.
The developmental release segment consists of the string.dev,followed by a non-negative integer value. Developmental releases are orderedby their numerical component, immediately before the corresponding release(and before any pre-releases with the same release segment), and followingany previous release (including any post-releases).
Developmental releases are also permitted for pre-releases andpost-releases:
X.YaN.devM# Developmental release of an alpha releaseX.YbN.devM# Developmental release of a beta releaseX.YrcN.devM# Developmental release of a release candidateX.Y.postN.devM# Developmental release of a post-release
Note
While they may be useful for continuous integration purposes, publishingdevelopmental releases of pre-releases to general purpose public indexservers is strongly discouraged, as it makes the version identifierdifficult to parse for human readers. If such a release needs to bepublished, it is substantially clearer to instead create a newpre-release by incrementing the numeric component.
Developmental releases of post-releases are also strongly discouraged,but they may be appropriate for projects which use the post-releasenotation for full maintenance releases which may include code changes.
If included in a version identifier, the epoch appears before all othercomponents, separated from the release segment by an exclamation mark:
E!X.Y # Version identifier with epoch
If no explicit epoch is given, the implicit epoch is0.
Most version identifiers will not include an epoch, as an explicit epoch isonly needed if a projectchanges the way it handles version numbering ina way that means the normal version ordering rules will give the wronganswer. For example, if a project is using date based versions like2014.04 and would like to switch to semantic versions like1.0, thenthe new releases would be identified asolder than the date based releaseswhen using the normal sorting scheme:
1.01.12.02013.102014.04
However, by specifying an explicit epoch, the sort order can be changedappropriately, as all versions from a later epoch are sorted after versionsfrom an earlier epoch:
2013.102014.041!1.01!1.11!2.0
In order to maintain better compatibility with existing versions there are anumber of “alternative” syntaxes that MUST be taken into account when parsingversions. These syntaxes MUST be considered when parsing a version, howeverthey should be “normalized” to the standard syntax defined above.
All ascii letters should be interpreted case insensitively within a version andthe normal form is lowercase. This allows versions such as1.1RC1 whichwould be normalized to1.1rc1.
All integers are interpreted via theint() built in and normalize to thestring form of the output. This means that an integer version of00 wouldnormalize to0 while09000 would normalize to9000. This does nothold true for integers inside of an alphanumeric segment of a local versionsuch as1.0+foo0100 which is already in its normalized form.
Pre-releases should allow a.,-, or_ separator between therelease segment and the pre-release segment. The normal form for this iswithout a separator. This allows versions such as1.1.a1 or1.1-a1which would be normalized to1.1a1. It should also allow a separator tobe used between the pre-release signifier and the numeral. This allows versionssuch as1.0a.1 which would be normalized to1.0a1.
Pre-releases allow the additional spellings ofalpha,beta,c,pre, andpreview fora,b,rc,rc, andrcrespectively. This allows versions such as1.1alpha1,1.1beta2, or1.1c3 which normalize to1.1a1,1.1b2, and1.1rc3. In everycase the additional spelling should be considered equivalent to their normalforms.
Pre releases allow omitting the numeral in which case it is implicitly assumedto be0. The normal form for this is to include the0 explicitly. Thisallows versions such as1.2a which is normalized to1.2a0.
Post releases allow a.,-, or_ separator as well as omitting theseparator all together. The normal form of this is with the. separator.This allows versions such as1.2-post2 or1.2post2 which normalize to1.2.post2. Like the pre-release separator this also allows an optionalseparator between the post release signifier and the numeral. This allowsversions like1.2.post-2 which would normalize to1.2.post2.
Post-releases allow the additional spellings ofrev andr. This allowsversions such as1.0-r4 which normalizes to1.0.post4. As with thepre-releases the additional spellings should be considered equivalent to theirnormal forms.
Post releases allow omitting the numeral in which case it is implicitly assumedto be0. The normal form for this is to include the0 explicitly. Thisallows versions such as1.2.post which is normalized to1.2.post0.
Post releases allow omitting thepost signifier all together. When usingthis form the separator MUST be- and no other form is allowed. This allowsversions such as1.0-1 to be normalized to1.0.post1. This particularnormalization MUST NOT be used in conjunction with the implicit post releasenumber rule. In other words,1.0- isnot a valid version and it doesnotnormalize to1.0.post0.
Development releases allow a.,-, or a_ separator as well asomitting the separator all together. The normal form of this is with the.separator. This allows versions such as1.2-dev2 or1.2dev2 whichnormalize to1.2.dev2.
Development releases allow omitting the numeral in which case it is implicitlyassumed to be0. The normal form for this is to include the0explicitly. This allows versions such as1.2.dev which is normalized to1.2.dev0.
With a local version, in addition to the use of. as a separator ofsegments, the use of- and_ is also acceptable. The normal form isusing the. character. This allows versions such as1.0+ubuntu-1 to benormalized to1.0+ubuntu.1.
In order to support the common version notation ofv1.0 versions may bepreceded by a single literalv character. This character MUST be ignoredfor all purposes and should be omitted from all normalized forms of theversion. The same version with and without thev is considered equivalent.
Leading and trailing whitespace must be silently ignored and removed from allnormalized forms of a version. This includes"",\t,\n,\r,\f, and\v. This allows accidental whitespace to be handled sensibly,such as a version like1.0\n which normalizes to1.0.
The standard version scheme is designed to encompass a wide range ofidentification practices across public and private Python projects. Inpractice, a single project attempting to use the full flexibility offeredby the scheme would create a situation where human users had difficultyfiguring out the relative order of versions, even though the rules aboveensure all compliant tools will order them consistently.
The following examples illustrate a small selection of the differentapproaches projects may choose to identify their releases, while stillensuring that the “latest release” and the “latest stable release” canbe easily determined, both by human users and automated tools.
Simple “major.minor” versioning:
0.10.20.31.01.1...
Simple “major.minor.micro” versioning:
1.1.01.1.11.1.21.2.0...
“major.minor” versioning with alpha, beta and candidatepre-releases:
0.91.0a11.0a21.0b11.0rc11.01.1a1...
“major.minor” versioning with developmental releases, release candidatesand post-releases for minor corrections:
0.91.0.dev11.0.dev21.0.dev31.0.dev41.0c11.0c21.01.0.post11.1.dev1...
Date based releases, using an incrementing serial within each year, skippingzero:
2012.12012.22012.3...2012.152013.12013.2...
Note
This section is intended primarily for authors of tools thatautomatically process distribution metadata, rather than developersof Python distributions deciding on a versioning scheme.
The epoch segment of version identifiers MUST be sorted according to thenumeric value of the given epoch. If no epoch segment is present, theimplicit numeric value is0.
The release segment of version identifiers MUST be sorted inthe same order as Python’s tuple sorting when the normalized release segment isparsed as follows:
tuple(map(int,release_segment.split(".")))
All release segments involved in the comparison MUST be converted to aconsistent length by padding shorter segments with zeros as needed.
Within a numeric release (1.0,2.7.3), the following suffixesare permitted and MUST be ordered as shown:
.devN,aN,bN,rcN,<nosuffix>,.postN
Note thatc is considered to be semantically equivalent torc and mustbe sorted as if it wererc. Tools MAY reject the case of having the sameN for both ac and arc in the same release segment as ambiguousand remain in compliance with the PEP.
Within an alpha (1.0a1), beta (1.0b1), or release candidate(1.0rc1,1.0c1), the following suffixes are permitted and MUST beordered as shown:
.devN,<nosuffix>,.postN
Within a post-release (1.0.post1), the following suffixes are permittedand MUST be ordered as shown:
.devN,<nosuffix>
Note thatdevN andpostN MUST always be preceded by a dot, evenwhen used immediately following a numeric version (e.g.1.0.dev456,1.0.post1).
Within a pre-release, post-release or development release segment with ashared prefix, ordering MUST be by the value of the numeric component.
The following example covers many of the possible combinations:
1.dev01.0.dev4561.0a11.0a2.dev4561.0a12.dev4561.0a121.0b1.dev4561.0b21.0b2.post345.dev4561.0b2.post3451.0rc1.dev4561.0rc11.01.0+abc.51.0+abc.71.0+51.0.post456.dev341.0.post4561.0.151.1.dev1
Metadata v1.0 (PEP 241) and metadata v1.1 (PEP 314) do not specify a standardversion identification or ordering scheme. However metadata v1.2 (PEP 345)does specify a scheme which is defined inPEP 386.
Due to the nature of the simple installer API it is not possible for aninstaller to be aware of which metadata version a particular distribution wasusing. Additionally installers required the ability to create a reasonablyprioritized list that includes all, or as many as possible, versions ofa project to determine which versions it should install. These requirementsnecessitate a standardization across one parsing mechanism to be used for allversions of a project.
Due to the above, this PEP MUST be used for all versions of metadata andsupersedesPEP 386 even for metadata v1.2. Tools SHOULD ignore any versionswhich cannot be parsed by the rules in this PEP, but MAY fall back toimplementation defined version parsing and ordering schemes if no versionscomplying with this PEP are available.
Distribution users may wish to explicitly remove non-compliant versions fromany private package indexes they control.
Some projects may choose to use a version scheme which requirestranslation in order to comply with the public version scheme defined inthis PEP. In such cases, the project specific version can be stored in themetadata while the translated public version is published in the version field.
This allows automated distribution tools to provide consistently correctordering of published releases, while still allowing developers to usethe internal versioning scheme they prefer for their projects.
Semantic versioning is a popular version identification scheme that ismore prescriptive than this PEP regarding the significance of differentelements of a release number. Even if a project chooses not to abide bythe details of semantic versioning, the scheme is worth understanding asit covers many of the issues that can arise when depending on otherdistributions, and when publishing a distribution that others rely on.
The “Major.Minor.Patch” (described in this PEP as “major.minor.micro”)aspects of semantic versioning (clauses 1-8 in the 2.0.0 specification)are fully compatible with the version scheme defined in this PEP, and abidingby these aspects is encouraged.
Semantic versions containing a hyphen (pre-releases - clause 10) or aplus sign (builds - clause 11) arenot compatible with this PEPand are not permitted in the public version field.
One possible mechanism to translate such semantic versioning based sourcelabels to compatible public versions is to use the.devN suffix tospecify the appropriate version order.
Specific build information may also be included in local version labels.
Many build tools integrate with distributed version control systems likeGit and Mercurial in order to add an identifying hash to the versionidentifier. As hashes cannot be ordered reliably such versions are notpermitted in the public version field.
As with semantic versioning, the public.devN suffix may be used touniquely identify such releases for publication, while the original DVCS basedlabel can be stored in the project metadata.
Identifying hash information may also be included in local version labels.
Thepytz project inherits its versioning scheme from the correspondingOlson timezone database versioning scheme: the year followed by a lowercasecharacter indicating the version of the database within that year.
This can be translated to a compliant public version identifier as<year>.<serial>, where the serial starts at zero or one (for the‘<year>a’ release) and is incremented with each subsequent databaseupdate within the year.
As with other translated version identifiers, the corresponding Olsondatabase version could be recorded in the project metadata.
A version specifier consists of a series of version clauses, separated bycommas. For example:
~=0.9,>=1.0,!=1.3.4.*,<2.0
The comparison operator determines the kind of version clause:
~=:Compatible release clause==:Version matching clause!=:Version exclusion clause<=,>=:Inclusive ordered comparison clause<,>:Exclusive ordered comparison clause===:Arbitrary equality clause.The comma (“,”) is equivalent to a logicaland operator: a candidateversion must match all given version clauses in order to match thespecifier as a whole.
Whitespace between a conditional operator and the following versionidentifier is optional, as is the whitespace around the commas.
When multiple candidate versions match a version specifier, the preferredversion SHOULD be the latest version as determined by the consistentordering defined by the standardVersion scheme. Whether or notpre-releases are considered as candidate versions SHOULD be handled asdescribed inHandling of pre-releases.
Except where specifically noted below, local version identifiers MUST NOT bepermitted in version specifiers, and local version labels MUST be ignoredentirely when checking if candidate versions match a given versionspecifier.
A compatible release clause consists of the compatible release operator~=and a version identifier. It matches any candidate version that is expectedto be compatible with the specified version.
The specified version identifier must be in the standard format described inVersion scheme. Local version identifiers are NOT permitted in thisversion specifier.
For a given release identifierV.N, the compatible release clause isapproximately equivalent to the pair of comparison clauses:
>=V.N,==V.*
This operator MUST NOT be used with a single segment version number such as~=1.
For example, the following groups of version clauses are equivalent:
~=2.2>=2.2,==2.*~=1.4.5>=1.4.5,==1.4.*
If a pre-release, post-release or developmental release is named in acompatible release clause asV.N.suffix, then the suffix is ignoredwhen determining the required prefix match:
~=2.2.post3>=2.2.post3,==2.*~=1.4.5a4>=1.4.5a4,==1.4.*
The padding rules for release segment comparisons means that the assumeddegree of forward compatibility in a compatible release clause can becontrolled by appending additional zeros to the version specifier:
~=2.2.0>=2.2.0,==2.2.*~=1.4.5.0>=1.4.5.0,==1.4.5.*
A version matching clause includes the version matching operator==and a version identifier.
The specified version identifier must be in the standard format described inVersion scheme, but a trailing.* is permitted on public versionidentifiers as described below.
By default, the version matching operator is based on a strict equalitycomparison: the specified version must be exactly the same as the requestedversion. Theonly substitution performed is the zero padding of therelease segment to ensure the release segments are compared with the samelength.
Whether or not strict version matching is appropriate depends on the specificuse case for the version specifier. Automated tools SHOULD at least issuewarnings and MAY reject them entirely when strict version matches are usedinappropriately.
Prefix matching may be requested instead of strict comparison, by appendinga trailing.* to the version identifier in the version matching clause.This means that additional trailing segments will be ignored whendetermining whether or not a version identifier matches the clause. If thespecified version includes only a release segment, than trailing components(or the lack thereof) in the release segment are also ignored.
For example, given the version1.1.post1, the following clauses wouldmatch or not as shown:
==1.1# Not equal, so 1.1.post1 does not match clause==1.1.post1# Equal, so 1.1.post1 matches clause==1.1.*# Same prefix, so 1.1.post1 matches clause
For purposes of prefix matching, the pre-release segment is considered tohave an implied preceding., so given the version1.1a1, thefollowing clauses would match or not as shown:
==1.1# Not equal, so 1.1a1 does not match clause==1.1a1# Equal, so 1.1a1 matches clause==1.1.*# Same prefix, so 1.1a1 matches clause if pre-releases are requested
An exact match is also considered a prefix match (this interpretation isimplied by the usual zero padding rules for the release segment of versionidentifiers). Given the version1.1, the following clauses wouldmatch or not as shown:
==1.1# Equal, so 1.1 matches clause==1.1.0# Zero padding expands 1.1 to 1.1.0, so it matches clause==1.1.dev1# Not equal (dev-release), so 1.1 does not match clause==1.1a1# Not equal (pre-release), so 1.1 does not match clause==1.1.post1# Not equal (post-release), so 1.1 does not match clause==1.1.*# Same prefix, so 1.1 matches clause
It is invalid to have a prefix match containing a development or local releasesuch as1.0.dev1.* or1.0+foo1.*. If present, the development releasesegment is always the final segment in the public version, and the local versionis ignored for comparison purposes, so using either in a prefix match wouldn’tmake any sense.
The use of== (without at least the wildcard suffix) when definingdependencies for published distributions is strongly discouraged as itgreatly complicates the deployment of security fixes. The strict versioncomparison operator is intended primarily for use when definingdependencies for repeatabledeployments of applications while usinga shared distribution index.
If the specified version identifier is a public version identifier (nolocal version label), then the local version label of any candidate versionsMUST be ignored when matching versions.
If the specified version identifier is a local version identifier, then thelocal version labels of candidate versions MUST be considered when matchingversions, with the public version identifier being matched as describedabove, and the local version label being checked for equivalence using astrict string equality comparison.
A version exclusion clause includes the version exclusion operator!=and a version identifier.
The allowed version identifiers and comparison semantics are the same asthose of theVersion matching operator, except that the sense of anymatch is inverted.
For example, given the version1.1.post1, the following clauses wouldmatch or not as shown:
!=1.1# Not equal, so 1.1.post1 matches clause!=1.1.post1# Equal, so 1.1.post1 does not match clause!=1.1.*# Same prefix, so 1.1.post1 does not match clause
An inclusive ordered comparison clause includes a comparison operator and aversion identifier, and will match any version where the comparison is correctbased on the relative position of the candidate version and the specifiedversion given the consistent ordering defined by the standardVersion scheme.
The inclusive ordered comparison operators are<= and>=.
As with version matching, the release segment is zero padded as necessary toensure the release segments are compared with the same length.
Local version identifiers are NOT permitted in this version specifier.
The exclusive ordered comparisons> and< are similar to the inclusiveordered comparisons in that they rely on the relative position of the candidateversion and the specified version given the consistent ordering defined by thestandardVersion scheme. However, they specifically exclude pre-releases,post-releases, and local versions of the specified version.
The exclusive ordered comparison>VMUST NOT allow a post-releaseof the given version unlessV itself is a post release. You may mandatethat releases are later than a particular post release, including additionalpost releases, by using>V.postN. For example,>1.7 will allow1.7.1 but not1.7.0.post1 and>1.7.post2 will allow1.7.1and1.7.0.post3 but not1.7.0.
The exclusive ordered comparison>VMUST NOT match a local version ofthe specified version.
The exclusive ordered comparison<VMUST NOT allow a pre-release ofthe specified version unless the specified version is itself a pre-release.Allowing pre-releases that are earlier than, but not equal to a specificpre-release may be accomplished by using<V.rc1 or similar.
As with version matching, the release segment is zero padded as necessary toensure the release segments are compared with the same length.
Local version identifiers are NOT permitted in this version specifier.
Arbitrary equality comparisons are simple string equality operations which donot take into account any of the semantic information such as zero padding orlocal versions. This operator also does not support prefix matching as the== operator does.
The primary use case for arbitrary equality is to allow for specifying aversion which cannot otherwise be represented by this PEP. This operator isspecial and acts as an escape hatch to allow someone using a tool whichimplements this PEP to still install a legacy version which is otherwiseincompatible with this PEP.
An example would be===foobar which would match a version offoobar.
This operator may also be used to explicitly require an unpatched versionof a project such as===1.0 which would not match for a version1.0+downstream1.
Use of this operator is heavily discouraged and tooling MAY display a warningwhen it is used.
Pre-releases of any kind, including developmental releases, are implicitlyexcluded from all version specifiers,unless they are already presenton the system, explicitly requested by the user, or if the only availableversion that satisfies the version specifier is a pre-release.
By default, dependency resolution tools SHOULD:
Dependency resolution tools MAY issue a warning if a pre-release is neededto satisfy a version specifier.
Dependency resolution tools SHOULD also allow users to request thefollowing alternative behaviours:
Dependency resolution tools MAY also allow the above behaviour to becontrolled on a per-distribution basis.
Post-releases and final releases receive no special treatment in versionspecifiers - they are always included unless explicitly excluded.
~=3.1: version 3.1 or later, but not version 4.0 or later.~=3.1.2: version 3.1.2 or later, but not version 3.2.0 or later.~=3.1a1: version 3.1a1 or later, but not version 4.0 or later.==3.1: specifically version 3.1 (or 3.1.0), excludes all pre-releases,post releases, developmental releases and any 3.1.x maintenance releases.==3.1.*: any version that starts with 3.1. Equivalent to the~=3.1.0 compatible release clause.~=3.1.0,!=3.1.3: version 3.1.0 or later, but not version 3.1.3 andnot version 3.2.0 or later.Some automated tools may permit the use of a direct reference as analternative to a normal version specifier. A direct reference consists ofthe specifier@ and an explicit URL.
Whether or not direct references are appropriate depends on the specificuse case for the version specifier. Automated tools SHOULD at least issuewarnings and MAY reject them entirely when direct references are usedinappropriately.
Public index servers SHOULD NOT allow the use of direct references inuploaded distributions. Direct references are intended as a tool forsoftware integrators rather than publishers.
Depending on the use case, some appropriate targets for a direct URLreference may be an sdist or a wheel binary archive. The exact URLs andtargets supported will be tool dependent.
For example, a local source archive may be referenced directly:
pip@file:///localbuilds/pip-1.3.1.zip
Alternatively, a prebuilt archive may also be referenced:
pip@file:///localbuilds/pip-1.3.1-py33-none-any.whl
All direct references that do not refer to a local file URL SHOULD specifya secure transport mechanism (such ashttps) AND include an expectedhash value in the URL for verification purposes. If a direct reference isspecified without any hash information, with hash information that thetool doesn’t understand, or with a selected hash algorithm that the toolconsiders too weak to trust, automated tools SHOULD at least emit a warningand MAY refuse to rely on the URL. If such a direct reference also uses aninsecure transport, automated tools SHOULD NOT rely on the URL.
It is RECOMMENDED that only hashes which are unconditionally provided bythe latest version of the standard library’shashlib module be usedfor source archive hashes. At time of writing, that list consists of'md5','sha1','sha224','sha256','sha384', and'sha512'.
For source archive and wheel references, an expected hash value may bespecified by including a<hash-algorithm>=<expected-hash> entry aspart of the URL fragment.
For version control references, theVCS+protocol scheme SHOULD beused to identify both the version control system and the secure transport,and a version control system with hash based commit identifiers SHOULD beused. Automated tools MAY omit warnings about missing hashes for versioncontrol systems that do not provide hash based commit identifiers.
To handle version control systems that do not support including commit ortag references directly in the URL, that information may be appended to theend of the URL using the@<commit-hash> or the@<tag>#<commit-hash>notation.
Note
This isn’tquite the same as the existing VCS reference notationsupported by pip. Firstly, the distribution name is moved in front ratherthan embedded as part of the URL. Secondly, the commit hash is includedeven when retrieving based on a tag, in order to meet the requirementabove thatevery link should include a hash to make things harder toforge (creating a malicious repo with a particular tag is easy, creatingone with a specifichash, less so).
Remote URL examples:
pip@https://github.com/pypa/pip/archive/1.3.1.zip#sha1=da9234ee9982d4bbb3c72346a6de940a148ea686pip@git+https://github.com/pypa/pip.git@7921be1537eac1e97bc40179a57f0349c2aee67dpip@git+https://github.com/pypa/pip.git@1.3.1#7921be1537eac1e97bc40179a57f0349c2aee67d
File URLs take the form offile://<host>/<path>. If the<host> isomitted it is assumed to belocalhost and even if the<host> is omittedthe third slash MUST still exist. The<path> defines what the file path onthe filesystem that is to be accessed.
On the various *nix operating systems the only allowed values for<host>is for it to be omitted,localhost, or another FQDN that the currentmachine believes matches its own host. In other words, on *nix thefile://scheme can only be used to access paths on the local machine.
On Windows the file format should include the drive letter if applicable aspart of the<path> (e.g.file:///c:/path/to/a/file). Unlike *nix onWindows the<host> parameter may be used to specify a file residing on anetwork share. In other words, in order to translate\\machine\volume\fileto afile:// url, it would end up asfile://machine/volume/file. Formore information onfile:// URLs on Windows see MSDN[4].
The versioning specification may be updated with clarifications withoutrequiring a new PEP or a change to the metadata version.
Any technical changes that impact the version identification and comparisonsyntax and semantics would require an updated versioning scheme to bedefined in a new PEP.
pkg_resourses.parse_version as it existed atthe time the PEP was written. After the PEP was accepted, setuptools 6.0 andlater versions adopted the behaviour described in this PEP.pkg_resources.parse_version considers it a pre-release marker.pkg_resources.parse_version attempts to provide some meaning fromany arbitrary string.pkg_resources.parse_version allows arbitrarily deeply nested versionsignifiers like1.0.dev1.post1.dev5. This PEP however allows only asingle use of each type and they must exist in a certain order..devN suffixc torc.The rationale for major changes is given in the following sections.
One key change in the version scheme in this PEP relative to that inPEP 386 is to sort top level developmental releases likeX.Y.devN aheadof alpha releases likeX.Ya1. This is a far more logical sort order, asprojects already using both development releases and alphas/betas/releasecandidates do not want their developmental releases sorted inbetween their release candidates and their final releases. There is norationale for usingdev releases in that position rather thanmerely creating additional release candidates.
The updated sort order also means the sorting ofdev versions is nowconsistent between the metadata standard and the pre-existing behaviourofpkg_resources (and hence the behaviour of current installationtools).
Making this change should make it easier for affected existing projects tomigrate to the latest version of the metadata standard.
Another change to the version scheme is to allow single numberversions, similar to those used by non-Python projects like MozillaFirefox, Google Chrome and the Fedora Linux distribution. This is actuallyexpected to be more useful for version specifiers, but it is easier toallow it for both version specifiers and release numbers, rather thansplitting the two definitions.
The exclusion of leading and trailing whitespace was made explicit aftera couple of projects with version identifiers differing only in atrailing\n character were found on PyPI.
Various other normalisation rules were also added as described in theseparate section on version normalisation below.
AppendixA shows detailed results of an analysis of PyPI distributionversion information, as collected on 8th August, 2014. This analysiscompares the behavior of the explicitly ordered version scheme defined inthis PEP with the de facto standard defined by the behavior of setuptools.These metrics are useful, as the intent of this PEP is to follow existingsetuptools behavior as closely as is feasible, while still throwingexceptions for unorderable versions (rather than trying to guess anappropriate order as setuptools does).
As inPEP 386, the primary focus is on codifying existing practices to makethem more amenable to automation, rather than demanding that existingprojects make non-trivial changes to their workflow. However, thestandard scheme allows significantly more flexibility than is neededfor the vast majority of simple Python packages (which often don’t evenneed maintenance releases - many users are happy with needing to upgrade to anew feature release to get bug fixes).
For the benefit of novice developers, and for experienced developerswishing to better understand the various use cases, the specificationnow goes into much greater detail on the components of the definedversion scheme, including examples of how each component may be usedin practice.
The PEP also explicitly guides developers in the direction ofsemantic versioning (without requiring it), and discourages the use ofseveral aspects of the full versioning scheme that have largely beenincluded in order to cover esoteric corner cases in the practices ofexisting projects and in repackaging software for Linux distributions.
The main reason to even have a standardised version scheme in the first placeis to make it easier to do reliable automated dependency analysis. It makesmore sense to describe the primary use case for version identifiers alongsidetheir definition.
The previous interpretation of version specifiers made it very easy toaccidentally download a pre-release version of a dependency. This inturn made it difficult for developers to publish pre-release versionsof software to the Python Package Index, as even marking the package ashidden wasn’t enough to keep automated tools from downloading it, and alsomade it harder for users to obtain the test release manually through themain PyPI web interface.
The previous interpretation also excluded post-releases from some versionspecifiers for no adequately justified reason.
The updated interpretation is intended to make it difficult to accidentallyaccept a pre-release version as satisfying a dependency, while stillallowing pre-release versions to be retrieved automatically when that’s theonly way to satisfy a dependency.
The “some forward compatibility assumed” version constraint is derived from theRuby community’s “pessimistic version constraint” operator[2] to allowprojects to take a cautious approach to forward compatibility promises, whilestill easily setting a minimum required version for their dependencies. Thespelling of the compatible release clause (~=) is inspired by the Ruby(~>) and PHP (~) equivalents.
Further improvements are also planned to the handling of parallelinstallation of multiple versions of the same library, but these willdepend on updates to the installation database definition along withimproved tools for dynamic path manipulation.
The trailing wildcard syntax to request prefix based version matching wasadded to make it possible to sensibly define compatible release clauses.
Excluding date based versions caused significant problems in migratingpytz to the new metadata standards. It also caused concerns for theOpenStack developers, as they use a date based versioning scheme and wouldlike to be able to migrate to the new metadata standards without changingit.
Version epochs are added for the same reason they are part of otherversioning schemes, such as those of the Fedora and Debian Linuxdistributions: to allow projects to gracefully change their approach tonumbering releases, without having a new release appear to have a lowerversion number than previous releases and without having to change the nameof the project.
In particular, supporting version epochs allows a project that was previouslyusing date based versioning to switch to semantic versioning by specifyinga new version epoch.
The! character was chosen to delimit an epoch version rather than the: character, which is commonly used in other systems, due to the fact that: is not a valid character in a Windows directory name.
Direct references are added as an “escape clause” to handle messy realworld situations that don’t map neatly to the standard distribution model.This includes dependencies on unpublished software for internal use, as wellas handling the more complex compatibility issues that may arise whenwrapping third party libraries as C extensions (this is of especial concernto the scientific community).
Index servers are deliberately given a lot of freedom to disallow directreferences, since they’re intended primarily as a tool for integratorsrather than publishers. PyPI in particular is currently going through theprocess ofeliminating dependencies on external references, as unreliableexternal services have the effect of slowing down installation operations,as well as reducing PyPI’s own apparent reliability.
Arbitrary equality is added as an “escape clause” to handle the case wheresomeone needs to install a project which uses a non compliant version. Althoughthis PEP is able to attain ~97% compatibility with the versions that arealready on PyPI there are still ~3% of versions which cannot be parsed. Thisoperator gives a simple and effective way to still depend on them withouthaving to “guess” at the semantics of what they mean (which would be requiredif anything other than strict string based equality was supported).
It’s a fact of life that downstream integrators often need to backportupstream bug fixes to older versions. It’s one of the services that getsLinux distro vendors paid, and application developers may also apply patchesthey need to bundled dependencies.
Historically, this practice has been invisible to cross-platform languagespecific distribution tools - the reported “version” in the upstreammetadata is the same as for the unmodified code. This inaccuracy can thencause problems when attempting to work with a mixture of integratorprovided code and unmodified upstream code, or even just attempting toidentify exactly which version of the software is installed.
The introduction of local version identifiers and “local version labels”into the versioning scheme, with the correspondingpython.integratormetadata extension allows this kind of activity to be representedaccurately, which should improve interoperability between the upstreamtools and various integrated platforms.
The exact scheme chosen is largely modeled on the existing behavior ofpkg_resources.parse_version andpkg_resources.parse_requirements,with the main distinction being that wherepkg_resources currently alwaystakes the suffix into account when comparing versions for exact matches,the PEP requires that the local version label of the candidate version beignored when no local version label is present in the version specifierclause. Furthermore, the PEP does not attempt to impose any structure onthe local version labels (aside from limiting the set of permittedcharacters and defining their ordering).
This change is designed to ensure that an integrator provided version likepip1.5+1 orpip1.5+1.git.abc123de will still satisfy a versionspecifier likepip>=1.5.
The plus is chosen primarily for readability of local version identifiers.It was chosen instead of the hyphen to preventpkg_resources.parse_version from parsing it as a prerelease, which isimportant for enabling a successful migration to the new, more structured,versioning scheme. The plus was chosen instead of a tilde because of thesignificance of the tilde in Debian’s version ordering algorithm.
Historically, the de facto standard for parsing versions in Python has been thepkg_resources.parse_version command from the setuptools project. This doesnot attempt to rejectany version and instead tries to make somethingmeaningful, with varying levels of success, out of whatever it is given. It hasa few simple rules but otherwise it more or less relies largely on stringcomparison.
The normalization rules provided in this PEP exist primarily to either increasethe compatibility withpkg_resources.parse_version, particularly indocumented use cases such asrev,r,pre, etc or to do somethingmore reasonable with versions that already exist on PyPI.
All possible normalization rules were weighed against whether or not they werelikely to cause any ambiguity (e.g. while someone might devise a scheme wherev1.0 and1.0 are considered distinct releases, the likelihood of anyoneactually doing that, much less on any scale that is noticeable, is fairly low).They were also weighed against howpkg_resources.parse_version treated aparticular version string, especially with regards to how it was sorted. Finallyeach rule was weighed against the kinds of additional versions it allowed, how“ugly” those versions looked, how hard there were to parse (both mentally andmechanically) and how much additional compatibility it would bring.
The breadth of possible normalizations were kept to things that could easilybe implemented as part of the parsing of the version and not pre-parsingtransformations applied to the versions. This was done to limit the sideeffects of each transformation as simple search and replace style transformsincrease the likelihood of ambiguous or “junk” versions.
For an extended discussion on the various types of normalizations that wereconsidered, please see the proof of concept forPEP 440 within pip[5].
There are not a lot of projects on PyPI which utilize a_ in the versionstring. However this PEP allows its use anywhere that- is acceptable. Thereason for this is that the Wheel normalization scheme specifies that-gets normalized to a_ to enable easier parsing of the filename.
The following changes were made to this PEP based on feedback received afterthe initial reference implementation was released in setuptools 8.0 and pip6.0:
!=V.*which was deemed to be surprising behavior which was too hard to accuratelydescribe. Instead the exclusive ordered comparisons will simply disallowmatching pre-releases, post-releases, and local versions of the specifiedversion (unless the specified version is itself a pre-release, post-releaseor local version). For an extended discussion see the threads ondistutils-sig[6][7].is_canonical regex were updated to be explicitthat numeric components are specifically required to be represented assequences of ASCII digits, not arbitrary Unicode [Nd] code points. Thiswas previously implied by the version parsing regex in Appendix B, butnot stated explicitly[10].The initial attempt at a standardised version scheme, along with thejustifications for needing such a standard can be found inPEP 386.
Metadata v2.0 guidelines versus setuptools:
$ invoke check.pep440Total Version Compatibility: 245806/250521 (98.12%)Total Sorting Compatibility (Unfiltered): 45441/47114 (96.45%)Total Sorting Compatibility (Filtered): 47057/47114 (99.88%)Projects with No Compatible Versions: 498/47114 (1.06%)Projects with Differing Latest Version: 688/47114 (1.46%)
As noted earlier in thePublicversionidentifiers section, publishedversion identifiers SHOULD use the canonical format. This section providesregular expressions that can be used to test whether a version is alreadyin that form, and if it’s not, extract the various components for subsequentnormalization.
To test whether a version identifier is in the canonical format, you can usethe following function:
importredefis_canonical(version):returnre.match(r'^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$',version)isnotNone
To extract the components of a version identifier, use the following regularexpression (as defined by thepackagingproject):
VERSION_PATTERN=r""" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version"""_regex=re.compile(r"^\s*"+VERSION_PATTERN+r"\s*$",re.VERBOSE|re.IGNORECASE,)
This document has been placed in the public domain.
Source:https://github.com/python/peps/blob/main/peps/pep-0440.rst
Last modified:2025-02-01 08:55:40 GMT