pypa/pip · error · TypeError

Can't add %r to environment

Error message

Can't add %r to environment

What it means

Raised by Environment.__iadd__ (the += operator) when the right-hand operand is neither a Distribution nor an Environment. Environment only supports in-place addition of these two types; anything else is a programming error.

Solutions

  1. Wrap the item(s) in the correct type: add Distribution objects individually, or build an Environment first.
  2. If adding multiple distributions, loop and call env.add(dist) instead of env += list.

Example fix

// before
env += [dist1, dist2]  # list, not allowed
// after
for d in [dist1, dist2]:
    env.add(d)
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(other, (Distribution, Environment)):
    raise TypeError(f'Cannot add {type(other)} to Environment')
env += other

Type guard

import pkg_resources
def is_addable_to_env(o) -> bool:
    return isinstance(o, (pkg_resources.Distribution, pkg_resources.Environment))

Prevention

When it happens

Trigger: Writing env += some_list or env += some_string where the operand is not a Distribution or Environment instance.

Common situations: Accidentally passing a raw list of paths or requirement strings to an Environment via +=; refactoring that changes the operand type.

Related errors


AI-assisted analysis of pypa/pip@f399c37189 (2026-08-08). Data as JSON: /api/errors/a508e58fbe87642c. Report an issue: GitHub.

Appendix: source

Thrown at src/pip/_vendor/pkg_resources/__init__.py:1308

        to the `installer` argument."""
        return installer(requirement) if installer else None

    def __iter__(self) -> Iterator[str]:
        """Yield the unique project names of the available distributions"""
        for key in self._distmap.keys():
            if self[key]:
                yield key

    def __iadd__(self, other: Distribution | Environment):
        """In-place addition of a distribution or environment"""
        if isinstance(other, Distribution):
            self.add(other)
        elif isinstance(other, Environment):
            for project in other:
                for dist in other[project]:
                    self.add(dist)
        else:
            raise TypeError("Can't add %r to environment" % (other,))
        return self

    def __add__(self, other: Distribution | Environment):
        """Add an environment or distribution to an environment"""
        new = self.__class__([], platform=None, python=None)
        for env in self, other:
            new += env
        return new


# XXX backward compatibility
AvailableDistributions = Environment


class ExtractionError(RuntimeError):
    """An error occurred extracting a resource

    The following attributes are available from instances of this exception:

View on GitHub (pinned to f399c37189)