Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimizing Python Modules

Tags:

python

Suppose that I have a python module A in my libraries directory. How can I export the same library as module B, however use only the functions and the code parts I need automatically? For instance, I want to build a minimal version of openCV for Python for a laser tracking project and I am sure that the code I actually need is much less than the whole openCV library. I don't want to do this by hand, so is there any kind of application that automates this proceedure?

like image 428
bolzano Avatar asked Jan 25 '26 00:01

bolzano


1 Answers

EDIT: I saw the comments and noted you are struggling with a space issue. In that case the code below is not what you are looking for. I think you will have to write the minimized version of the target module. Otherwise you will have to implement some kind of tool that enables you to find all dependences of functions you want to use automatically.

You have to choose if it's worth the effort.

class Importer:
    def __init__(self, module_name, funcion_list):
        self.__module = __import__(module_name)
        self.__specific = funcion_list

        self.initialize()

    def initialize(self):
        for elem in self.__specific:
            setattr(self, elem, getattr(self.__module, elem))

Lets say you want only export the function listdir from module os. So, in your B module you can:

os_minimized = Importer("os", ("listdir",))

And then in other module you write:

from B import os_minimized
print(os_minimized.listdir("."))
like image 114
Raydel Miranda Avatar answered Jan 27 '26 13:01

Raydel Miranda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!