Altering imported modules

bruno.desthuilliers at bruno.desthuilliers at
Fri Mar 7 11:23:55 CET 2008

On 6 mar, 21:29, Tro <trowo... at> wrote:
> On Wednesday 05 March 2008, Bruno Desthuilliers wrote:
> > Tro a écrit :
> > > I'd like to know if it's possible to make tlslite load *my* asyncore
> > > module without changing any of the tlslite code.
> > Not sure this apply to your case (depends on how asyncore is implemented
> > and the exact "modifications"), but monkeypatching is a possible solution.
> >
> >
> >
> Ooh. I didn't know this technique had a name. But that's basically how I'm
> modifying the built-in asyncore in my own class. I override its poll() and
> poll2() methods to do something extra.
> However, the issue with tlslite is that it imports the regular asyncore
> instead of the one I wrote,

One of us must be missing something here. The monkeypatch way is:

# -- --
import BaseModule
# backup original if we want to call it
_original_something = BaseModule.something

def my_patched_something(args):
  # eventually

BaseModule.something = my_patched_something

# -- --

import mypatch
# From now on, any other module calling
# BaseModule.something will call my_patched_something.

import other_module_using_BaseModule


> which means that I'd have to somehow monkeypatch
> its "import" statement. I'm guessing that means simply monkeypatching both
> the original asyncore module AND the tlslite module's asyncore attribute with
> my own version.

Unless there are some really strange things happening in tlslite and
asyncore, if you import your monkeypatch before importing tlslite, you
shouldn't have to touch anything in tlslite. Which is the whole point
of monkeypatching.

More information about the Python-list mailing list