How do you favor one package if both packages share the same module name?

Viewed 66

So two packages have the same module name, docopt and docopt-ng both export docopt - when there is a dependency, e.g.

pipenv install pip-upgrader docopt-ng

When you attempt to import

import docopt

You get one of the two, but not the one I want today. Is there a trick to get the importer to import the other module (the one in docopt-ng)?

Things that didn't work:

$ python -c "from docopt-ng import docopt; print(docopt.__file__)"

  File "<string>", line 1
    from docopt-ng import docopt; print(docopt.__file__)

In .NET this is solved with four-part names.

1 Answers

OK, I got it.

  1. Use the --target flag to specify a location to install the docopt-ng version to a location that doesn't conflict with the other package.
  2. Add that location to your PYTHONPATH env variable ahead of your normal packages directory.
(docopt) % pip install pip-upgrader
(docopt) % mkdir shims
(docopt) % pip install --target /Users/dickfox/docopt/shims docopt-ng
(docopt) % export PYTHONPATH='/Users/dickfox/docopt/shims'
(docopt) % python
>>> import docopt
>>> docopt.__file__ 
'/Users/dickfox/docopt/shims/docopt.py'

To use the original version:

(docopt) % python
>>> import sys
>>> sys.path
['', '/Users/dickfox/docopt/shims', ETC...]
>>> del sys.path[1]
>>> import docopt
>>> docopt.__file__
'/Users/dickfox/lib/python3.8/site-packages/docopt.py'

It didn't work for me to insert the special install location using sys.path.insert once I had already started python. I had to use the env variable.

Related