Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a Python library in my own package

Tags:

python

How can I 'embed' a Python library in my own Python package?

Take the Requests library, for instance. How could I integrate it into my own package, the objective being to allow me to run my application on different machines without actually installing Requests on every one, but having it in the same folder as my package?

Is this even possible?

like image 731
Sean Bone Avatar asked Sep 15 '13 12:09

Sean Bone


People also ask

How do I add a library to a Python project?

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 | `- ...

Can we create our own packages in Python?

Creating PackagesWhenever you want to create a package, then you have to include __init__.py file in the directory. You can write code inside or leave it as blank as your wish. It doesn't bothers Python. Create a directory and include a __init__.py file in it to tell Python that the current directory is a package.


2 Answers

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 
like image 160
Hubro Avatar answered Sep 23 '22 21:09

Hubro


If you only need to run your application may be pyinstaller packaging is a better option.

It will create a single bundle with everything that is needed, including Python, to avoid dependencies on the system you're running in.

like image 44
6502 Avatar answered Sep 22 '22 21:09

6502