# How to encapsulate Python modules in a single file?

PythonServer Side ProgrammingProgramming

You cannot, in general encapsulate Python modules in a single file. Because doing so would destroy the module searching method that python uses (files and directories). If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given module:

>>> import os, sys
>>> file_path = 'AdditionalModules/'
>>> sys.path.append(os.path.dirname(file_path))
>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH.

You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/

Published on 20-Dec-2017 10:48:48