Altering imported modules

Discussion in 'Python' started by Tro, Mar 1, 2008.

  1. Tro

    Tro Guest

    Hi, list.

    I've got a simple asyncore-based server. However, I've modified the asyncore
    module to allow me to watch functions as well as sockets. The modified
    asyncore module is in a specific location in my project and is imported as
    usual from my classes.

    Now I'd like to use the tlslite library, which includes an asyncore mixin
    class. However, tlslite imports "asyncore", which doesn't include my own

    I'd like to know if it's possible to make tlslite load *my* asyncore module
    without changing any of the tlslite code.

    Tro, Mar 1, 2008
    1. Advertisements

  2. the pkgutil module might be helpful, not sure though as I've never
    used it myself. is a fairly
    detailed look at what pkgutil can do.

    Floris Bruynooghe, Mar 4, 2008
    1. Advertisements

  3. Tro

    Tro Guest

    Tro, Mar 5, 2008
  4. Tro a écrit :
    Not sure this apply to your case (depends on how asyncore is implemented
    and the exact "modifications"), but monkeypatching is a possible solution.

    Bruno Desthuilliers, Mar 5, 2008
  5. Tro

    Tro Guest

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

    Tro, Mar 6, 2008
  6. 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


    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.
    bruno.desthuilliers, Mar 7, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.