Embedding a Python library in my own package

If it’s a pure python library (no compiled modules) you can simply place the library in a folder in your project and add that folder to your module search path. Here’s an example project:

|- application.py
|- lib
|  `- ...
|- docs
|  `- ...
`- vendor
   |- requests
   |  |- __init__.py
   |  `- ...
   `- other libraries...

The vendor folder in this example contains all third party modules. The file application.py would contain this:

import os
import sys

# Add vendor directory to module search path
parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'vendor')

sys.path.append(vendor_dir)

# Now you can import any library located in the "vendor" folder!
import requests

Bonus fact

As noted by seeafish in the comments, you can install packages directly into the vendor directory:

pip install <pkg_name> -t /path/to/vendor_dir

Leave a Comment