Differences between version dated 2005-11-16 16:50:41 and 2010-01-31 00:36:31
(spanning 22 versions)
Deletions are marked like this.
Additions are marked like this.
corresponding package in all distributions on ``sys.path`` that contain a
package of that name. (More precisely, if an importer's
``find_module(name)`` returns a loader, then it will also be searched for
the package's contents.) Whenever a Distribution's ``to_install()`` method
the package's contents.) Whenever a Distribution's ``activate()`` method
is invoked, it checks for the presence of namespace packages and updates
their ``__path__`` contents accordingly.
For the syntax of requirement specifiers, see the section below on
`Requirements Parsing`_.
Note: in general, it should not be necessary for you to call this method
In general, it should not be necessary for you to call this method
directly. It's intended more for use in quick-and-dirty scripting and
interactive interpreter hacking than for production use. If you're creating
an actual library or application, it's strongly recommended that you create
there. That way, tools like EasyInstall can automatically detect what
requirements your package has, and deal with them accordingly.
Note that calling ``require('SomePackage')`` will not install
``SomePackage`` if it isn't already present. If you need to do this, you
should use the ``resolve()`` method instead, which allows you to pass an
``installer`` callback that will be invoked when a needed distribution
can't be found on the local machine. You can then have this callback
display a dialog, automatically download the needed distribution, or
whatever else is appropriate for your application. See the documentation
below on the ``resolve()`` method for more information, and also on the
``obtain()`` method of ``Environment`` objects.
``run_script(requires, script_name)``
Locate distribution specified by `requires` and run its `script_name`
script. `requires` must be a string containing a requirement specifier.
the global ``working_set`` to reflect the change. This method is also
called by the ``WorkingSet()`` constructor during initialization.
This method uses ``find_distributions(entry,False)`` to find distributions
This method uses ``find_distributions(entry, True)`` to find distributions
corresponding to the path entry, and then ``add()`` them. `entry` is
always appended to the ``entries`` attribute, even if it is already
present, however. (This is because ``sys.path`` can contain the same value
yourself to deal with the existing items; just register the callback and
be prepared for the fact that it will be called immediately by this method.
Note that callbacks *must not* allow exceptions to propagate, or they will
interfere with the operation of other callbacks and possibly result in an
inconsistent working set state. Callbacks should use a try/except block
to ignore, log, or otherwise process any errors, especially since the code
that caused the callback to be invoked is unlikely to be able to handle
the errors any better than the callback itself.
``pkg_resources.add_activation_listener()`` is an alternate spelling of
``pkg_resources.working_set.subscribe()``.
Locating Plugins
----------------
Extensible applications will sometimes have a "plugin directory" or a set of
plugin directories, from which they want to load entry points or other
metadata. The ``find_plugins()`` method allows you to do this, by scanning an
environment for the newest version of each project that can be safely loaded
without conflicts or missing requirements.
``find_plugins(plugin_env, full_env=None, fallback=True)``
Scan `plugin_env` and identify which distributions could be added to this
working set without version conflicts or missing requirements.
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
)
map(working_set.add, distributions) # add plugins+libs to sys.path
print "Couldn't load", errors # display errors
The `plugin_env` should be an ``Environment`` instance that contains only
distributions that are in the project's "plugin directory" or directories.
The `full_env`, if supplied, should be an ``Environment`` instance that
contains all currently-available distributions.
If `full_env` is not supplied, one is created automatically from the
``WorkingSet`` this method is called on, which will typically mean that
every directory on ``sys.path`` will be scanned for distributions.
This method returns a 2-tuple: (`distributions`, `error_info`), where
`distributions` is a list of the distributions found in `plugin_env` that
were loadable, along with any other distributions that are needed to resolve
their dependencies. `error_info` is a dictionary mapping unloadable plugin
distributions to an exception instance describing the error that occurred.
Usually this will be a ``DistributionNotFound`` or ``VersionConflict``
instance.
Most applications will use this method mainly on the master ``working_set``
instance in ``pkg_resources``, and then immediately add the returned
distributions to the working set so that they are available on sys.path.
This will make it possible to find any entry points, and allow any other
metadata tracking and hooks to be activated.
The resolution algorithm used by ``find_plugins()`` is as follows. First,
the project names of the distributions present in `plugin_env` are sorted.
Then, each project's eggs are tried in descending version order (i.e.,
newest version first).
An attempt is made to resolve each egg's dependencies. If the attempt is
successful, the egg and its dependencies are added to the output list and to
a temporary copy of the working set. The resolution process continues with
the next project name, and no older eggs for that project are tried.
If the resolution attempt fails, however, the error is added to the error
dictionary. If the `fallback` flag is true, the next older version of the
plugin is tried, until a working version is found. If false, the resolution
process continues with the next plugin project name.
Some applications may have stricter fallback requirements than others. For
example, an application that has a database schema or persistent objects
may not be able to safely downgrade a version of a package. Others may want
to ensure that a new plugin configuration is either 100% good or else
revert to a known-good configuration. (That is, they may wish to revert to
a known configuration if the `error_info` return value is non-empty.)
Note that this algorithm gives precedence to satisfying the dependencies of
alphabetically prior project names in case of version conflicts. If two
projects named "AaronsPlugin" and "ZekesPlugin" both need different versions
of "TomsLibrary", then "AaronsPlugin" will win and "ZekesPlugin" will be
disabled due to version conflict.
``Environment`` Objects
=======================
``Environment`` objects are used by ``pkg_resources`` to index available
distributions during dependency resolution.
``Environment(search_path=None, platform=get_platform(), python=PY_MAJOR)``
``Environment(search_path=None, platform=get_supported_platform(), python=PY_MAJOR)``
Create an environment snapshot by scanning `search_path` for distributions
compatible with `platform` and `python`. `search_path` should be a
sequence of strings such as might be used on ``sys.path``. If a
``can_add(dist)``
Is distribution `dist` acceptable for this environment? If it's not
compatible with the platform and python version specified at creation of
the environment, False is returned.
compatible with the ``platform`` and ``python`` version values specified
when the environment was created, a false value is returned.
``__add__(dist_or_env)`` (``+`` operator)
Add a distribution or environment to an ``Environment`` instance, returning
a *new* environment object that contains all the distributions previously
contained by both. The new environment will have a ``platform`` and
``python`` of ``None``, meaning that it will not reject any distributions
from being added to it; it will simply accept whatever is added. If you
want the added items to be filtered for platform and Python version, or
you want to add them to the *same* environment instance, you should use
in-place addition (``+=``) instead.
``__iadd__(dist_or_env)`` (``+=`` operator)
Add a distribution or environment to an ``Environment`` instance
*in-place*, updating the existing instance and returning it. The
``platform`` and ``python`` filter attributes take effect, so distributions
in the source that do not have a suitable platform string or Python version
are silently ignored.
``best_match(req, working_set, installer=None)``
Find distribution best matching `req` and usable on `working_set`
parsed using the ``parse_version()`` utility function. Otherwise, it is
assumed to be an already-parsed version.
The ``Requirement`` object's version specifiers (``.specs``) are internally
sorted into ascending version order, and used to establish what ranges of
versions are acceptable. Adjacent redundant conditions are effectively
consolidated (e.g. ``">1, >2"`` produces the same results as ``">1"``, and
``"<2,<3"`` produces the same results as``"<3"``). ``"!="`` versions are
excised from the ranges they fall within. The version being tested for
acceptability is then checked for membership in the resulting ranges.
(Note that providing conflicting conditions for the same version (e.g.
``"<2,>=2"`` or ``"==2,!=2"``) is meaningless and may therefore produce
bizarre results when compared with actual version number(s).)
``__eq__(other_requirement)``
A requirement compares equal to another requirement if they have
case-insensitively equal project names, version specifiers, and "extras".
function, so they may not exactly equal the extras the requirement was
created with.)
``specs``
A list of ``(op,version)`` tuples, sorted in ascending parsed-version
order. The `op` in each tuple is a comparison operator, represented as
a string. The `version` is the (unparsed) version number. The relative
order of tuples containing the same version numbers is undefined, since
having more than one operator for a given version is either redundant or
self-contradictory.
Entry Points
============
implement both the `IResourceProvider`_ and `IMetadataProvider Methods`_ by
delegating them to the `metadata` object.
``Distribution.from_location(location, basename, metadata=None)`` (classmethod)
``Distribution.from_location(location, basename, metadata=None, **kw)`` (classmethod)
Create a distribution for `location`, which must be a string such as a
URL, filename, or other string that might be used on ``sys.path``.
`basename` is a string naming the distribution, like ``Foo-1.2-py2.4.egg``.
If `basename` ends with ``.egg``, then the project's name, version, python
version and platform are extracted from the filename and used to set those
properties of the created distribution.
properties of the created distribution. Any additional keyword arguments
are forwarded to the ``Distribution()`` constructor.
``Distribution.from_filename(filename, metadata=None)`` (classmethod)
``Distribution.from_filename(filename, metadata=None**kw)`` (classmethod)
Create a distribution by parsing a local filename. This is a shorter way
of saying ``Distribution.from_location(normalize_path(filename),
os.path.basename(filename), metadata)``. In other words, it creates a
distribution whose location is the normalize form of the filename, parsing
name and version information from the base portion of the filename.
name and version information from the base portion of the filename. Any
additional keyword arguments are forwarded to the ``Distribution()``
constructor.
``Distribution(location,metadata,project_name,version,py_version,platform,precedence)``
Create a distribution by setting its properties. All arguments are
``dist.key`` is short for ``dist.project_name.lower()``. It's used for
case-insensitive comparison and indexing of distributions by project name.
extras
A list of strings, giving the names of extra features defined by the
project's dependency list (the ``extras_require`` argument specified in
the project's setup script).
version
A string denoting what release of the project this distribution contains.
When a ``Distribution`` is constructed, the `version` argument is passed
``parsed_version``. The default precedence is ``pkg_resources.EGG_DIST``,
which is the highest (i.e. most preferred) precedence. The full list
of predefined precedences, from most preferred to least preferred, is:
``EGG_DIST``, ``BINARY_DIST``, ``SOURCE_DIST``, and ``CHECKOUT_DIST``.
Normally, precedences other than ``EGG_DIST`` are used only by the
``setuptools.package_index`` module, when sorting distributions found in a
package index to determine their suitability for installation.
``EGG_DIST``, ``BINARY_DIST``, ``SOURCE_DIST``, ``CHECKOUT_DIST``, and
``DEVELOP_DIST``. Normally, precedences other than ``EGG_DIST`` are used
only by the ``setuptools.package_index`` module, when sorting distributions
found in a package index to determine their suitability for installation.
"System" and "Development" eggs (i.e., ones that use the ``.egg-info``
format), however, are automatically given a precedence of ``DEVELOP_DIST``.
of "extras" defined by the distribution, and the list returned will then
include any dependencies needed to support the named "extras".
``clone(**kw)``
Create a copy of the distribution. Any supplied keyword arguments override
the corresponding argument to the ``Distribution()`` constructor, allowing
you to change some of the copied distribution's attributes.
``egg_name()``
Return what this distribution's standard filename should be, not including
the ".egg" extension. For example, a distribution for project "Foo"
obtain an extraction location, and only for names they intend to
extract, as it tracks the generated names for possible cleanup later.
``extraction_error()``
Raise an ``ExtractionError`` describing the active exception as interfering
with the extraction process. You should call this if you encounter any
OS errors extracting the file to the cache path; it will format the
operating system exception for you, and add other information to the
``ExtractionError`` instance that may be needed by programs that want to
wrap or handle extraction errors themselves.
``postprocess(tempname, filename)``
Perform any platform-specific postprocessing of `tempname`.
Resource providers should call this method ONLY after successfully
to the working set). If the named package can't be imported, or the
``Requirement`` can't be satisfied, an exception is raised.
Note also that if you supply a package name, and the package is not part
of a pluggable distribution (i.e., it has no metadata), then you will still
get an ``IResourceProvider`` object, but it will return ``False`` when
asked if any metadata files or directories exist.
NOTE: if you use a package name rather than a ``Requirement``, the object
you get back may not be a pluggable distribution, depending on the method
by which the package was installed. In particular, "development" packages
and "single-version externally-managed" packages do not have any way to
map from a package name to the corresponding project's metadata. Do not
write code that passes a package name to ``get_provider()`` and then tries
to retrieve project metadata from the returned object. It may appear to
work when the named package is in an ``.egg`` file or directory, but
it will fail in other installation scenarios. If you want project
metadata, you need to ask for a *project*, not a package.
``IMetadataProvider`` Methods
VersionConflict
UnknownExtra
ExtractionError
``ResolutionError``
This class is used as a base class for the other three exceptions, so that
you can catch all of them with a single "except" clause. It is also raised
One of the "extras" requested was not recognized by the distribution it
was requested from.
``ExtractionError``
A problem occurred extracting a resource to the Python Egg cache. The
following attributes are available on instances of this exception:
manager
The resource manager that raised this exception
cache_path
The base directory for resource extraction
original_error
The exception instance that caused extraction to fail
Supporting Custom Importers
===========================
ZipProvider
EggMetadata
EmptyProvider
FileMetadata
``NullProvider``
itself is a ".egg"). It can also be a combination, such as a zipfile egg
that also contains other eggs.
``FileMetadata(path_to_pkg_info)``
Create an ``IResourceProvider`` that provides exactly one metadata
resource: ``PKG-INFO``. The supplied path should be a distutils PKG-INFO
file. This is basically the same as an ``EmptyProvider``, except that
requests for ``PKG-INFO`` will be answered using the contents of the
designated file. (This provider is used to wrap ``.egg-info`` files
installed by vendor-supplied system packages.)
Utility Functions
=================
The algorithm assumes that strings like "-" and any alpha string that
alphabetically follows "final" represents a "patch level". So, "2.4-1"
is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
considered newer than "2.4-1", whic in turn is newer than "2.4".
considered newer than "2.4-1", which in turn is newer than "2.4".
Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
come before "final" alphabetically) are assumed to be pre-release versions,
so that the version "2.4" is considered newer than "2.4a1".
so that the version "2.4" is considered newer than "2.4a1". Any "-"
characters preceding a pre-release indicator are removed. (In versions of
setuptools prior to 0.6a9, "-" characters were not removed, leading to the
unintuitive result that "0.2-rc1" was considered a newer version than
"0.2".)
Finally, to handle miscellaneous cases, the strings "pre", "preview", and
"rc" are treated as if they were "c", i.e. as though they were release
candidates, and therefore are not as new as a version string that does not
contain them.
contain them. And the string "dev" is treated as if it were an "@" sign;
that is, a version coming before even "a" or "alpha".
.. _yield_lines():
similar to ``safe_name()`` except that non-alphanumeric runs are replaced
by a single underbar (``_``), and the result is lowercased.
``to_filename(name_or_version)``
Escape a name or version string so it can be used in a dash-separated
filename (or ``#egg=name-version`` tag) without ambiguity. You
should only pass in values that were returned by ``safe_name()`` or
``safe_version()``.
Platform Utilities
------------------
``get_platform()``
``get_build_platform()``
Return this platform's identifier string. For Windows, the return value
is ``"win32"``, and for Mac OS X it is a string of the form
``"macosx-10.4-ppc"``. All other platforms return the same uname-based
string that the ``distutils.util.get_platform()`` function returns.
This string is the minimum platform version required by distributions built
on the local machine. (Backward compatibility note: setuptools versions
prior to 0.6b1 called this function ``get_platform()``, and the function is
still available under that name for backward compatibility reasons.)
``get_supported_platform()`` (New in 0.6b1)
This is the similar to ``get_build_platform()``, but is the maximum
platform version that the local machine supports. You will usually want
to use this value as the ``provided`` argument to the
``compatible_platforms()`` function.
``compatible_platforms(provided, required)``
Return true if a distribution built on the `provided` platform may be used
for obtaining an "importer" object. It first checks for an importer for
the path item in ``sys.path_importer_cache``, and if not found it calls
each of the ``sys.path_hooks`` and caches the result if a good importer is
found. If no importer is found, this routine returns an ``ImpWrapper``
instance that wraps the builtin import machinery as a PEP 302-compliant
"importer" object. This ``ImpWrapper`` is *not* cached; instead a new
instance is returned each time.
found. If no importer is found, this routine returns a wrapper object
that wraps the builtin import machinery as a PEP 302-compliant "importer"
object. This wrapper object is *not* cached; instead a new instance is
returned each time.
File/Path Utilities
Release Notes/Change History
----------------------------
0.6c10
* Prevent lots of spurious "already imported from another path" warnings (e.g.
when pkg_resources is imported late).
0.6c9
* Fix ``resource_listdir('')`` always returning an empty list for zipped eggs.
0.6c7
* Fix package precedence problem where single-version eggs installed in
``site-packages`` would take precedence over ``.egg`` files (or directories)
installed in ``site-packages``.
0.6c6
* Fix extracted C extensions not having executable permissions under Cygwin.
* Allow ``.egg-link`` files to contain relative paths.
* Fix cache dir defaults on Windows when multiple environment vars are needed
to construct a path.
0.6c4
* Fix "dev" versions being considered newer than release candidates.
0.6c3
* Python 2.5 compatibility fixes.
0.6c2
* Fix a problem with eggs specified directly on ``PYTHONPATH`` on
case-insensitive filesystems possibly not showing up in the default
working set, due to differing normalizations of ``sys.path`` entries.
0.6b3
* Fixed a duplicate path insertion problem on case-insensitive filesystems.
0.6b1
* Split ``get_platform()`` into ``get_supported_platform()`` and
``get_build_platform()`` to work around a Mac versioning problem that caused
the behavior of ``compatible_platforms()`` to be platform specific.
* Fix entry point parsing when a standalone module name has whitespace
between it and the extras.
0.6a11
* Added ``ExtractionError`` and ``ResourceManager.extraction_error()`` so that
cache permission problems get a more user-friendly explanation of the
problem, and so that programs can catch and handle extraction errors if they
need to.
0.6a10
* Added the ``extras`` attribute to ``Distribution``, the ``find_plugins()``
method to ``WorkingSet``, and the ``__add__()`` and ``__iadd__()`` methods
to ``Environment``.
* ``safe_name()`` now allows dots in project names.
* There is a new ``to_filename()`` function that escapes project names and
versions for safe use in constructing egg filenames from a Distribution
object's metadata.
* Added ``Distribution.clone()`` method, and keyword argument support to other
``Distribution`` constructors.
* Added the ``DEVELOP_DIST`` precedence, and automatically assign it to
eggs using ``.egg-info`` format.
0.6a9
* Don't raise an error when an invalid (unfinished) distribution is found
unless absolutely necessary. Warn about skipping invalid/unfinished eggs
when building an Environment.
* Added support for ``.egg-info`` files or directories with version/platform
information embedded in the filename, so that system packagers have the
option of including ``PKG-INFO`` files to indicate the presence of a
system-installed egg, without needing to use ``.egg`` directories, zipfiles,
or ``.pth`` manipulation.
* Changed ``parse_version()`` to remove dashes before pre-release tags, so
that ``0.2-rc1`` is considered an *older* version than ``0.2``, and is equal
to ``0.2rc1``. The idea that a dash *always* meant a post-release version
was highly non-intuitive to setuptools users and Python developers, who
seem to want to use ``-rc`` version numbers a lot.
0.6a8
* Fixed a problem with ``WorkingSet.resolve()`` that prevented version
conflicts from being detected at runtime.
0.3a1
* Initial release.