Python: Override method in installed egg file?

508 Views Asked by At

So I have installed a python module (python install setup.py), the egg is created, but how can I override a method in one of the classes inside the egg file?

This is what I am doing, I fix the source and install it again. it's very tedious to do this again and again.

1

There are 1 best solutions below

0
On

It is not a good idea to modify source code of third party package directly, you can either fork the repo, modify the code and build your own .egg file, then you can install the customized version instead of the standard one, please reference to http://peak.telecommunity.com/DevCenter/setuptools

Or you can just inherit the class and override the method, for example, you have a class EggClass in egg file.

python module egg.py in egg

class EggClass(object):

    def cook(self):
        print 'Cooking ...'

And you use it like this

import egg
my_egg = egg.EggClass()
egg.cook()

But you want the cook method does cooking differently, why not just inherit EggClass and override the cook method like this

class MySuperEgg(EggClass):

    def cook(self):
        print 'Special cooking manner ...'

So you can use it like this

egg = MySuperEgg()
egg.cook()

Instead of inherit the class, you can also use a dirty hack to replace the original method like this

def cook(self, time):
    print 'Special cooking for {} minutes ...'.format(time)

# ah... a dirty hack to override the original cook method
EggClass.cook = cook
egg = EggClass()
egg.cook(10)

You can leave these in your code, so there will be no need to modify their source code.