Running code on module import

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Grant D. Watson

    Running code on module import

    If this has been answered before, or if my terminology is off, please bear with
    me; my Python experience is limited to use in one class and to personal
    projects.

    I'd like to do something rather silly: I'd like to run a particular piece of
    code from a given module every time that the module is imported, and not just
    at the time that the module is originally loaded. So, every time a module says
    import foo
    or something analogous, I want foo.doYourThing () to be invoked, in addition to
    the usual effects on the importing module's namespace.

    Now, my reaction is to create a newfangled import hook that will intercept
    requests to load "foo" and send back a reference to the first loaded copy, so
    that I only have one copy of foo at any given time, but omit (or delete, as
    necessary) a reference to foo from sys.modules; this way my import hook will be
    invoked each time someone wants to import foo (from which I can launch
    foo.doYourThing ()).

    The problem is that I want to do all this without use of another module or
    additional code in the module that imports foo. This means that I have to
    install the hook from _inside_ foo. But if I do that, I can't seem to avoid
    leaving a reference in sys.modules; removing it prevents the initial import
    (the one that loads the module in the first place) from succeeding.

    You're probably all foo-ed out by now. Is there any way to do this? I'm not
    married to the import hook idea, it just seemed like the most promising to me.
    Is there some API I missed that would simplify things?

    Your help is much appreciated.

    Grant D. Watson
    grant_watson@ya hoo.pleasedonts pamme.com (Use this one!)
  • Michael Hudson

    #2
    Re: Running code on module import

    vbasicboy@aol.c om (Grant D. Watson) writes:
    [color=blue]
    > You're probably all foo-ed out by now. Is there any way to do this?
    > I'm not married to the import hook idea, it just seemed like the
    > most promising to me.[/color]

    I'd agree with that.

    I would also wonder just what on earth you are up to... it seems very
    unnatural to me.

    Cheers,
    mwh

    --
    It's a measure of how much I love Python that I moved to VA, where
    if things don't work out Guido will buy a plantation and put us to
    work harvesting peanuts instead. -- Tim Peters, comp.lang.pytho n

    Comment

    • Grant D. Watson

      #3
      Re: Running code on module import

      >I would also wonder just what on earth you are up to... it seems very[color=blue]
      >unnatural to me.[/color]

      Well, it is somewhat unnatural for Python.

      By importing my magic module, I want to have my main() function invoked,
      without any "if __name__..." stuff. My C-and-Java trained aesthetic
      sensibilities aside, I want to do this so that I can do a bunch of
      argv-processing stuff and just pass the results to main() without having to
      call anything manually.

      So, for example, "demo.py":
      ---
      import runmain

      options = "ab:c"

      def main(switches, args):
      if switches["a"]:
      print "-a is set"
      else:
      print "-a is not set"
      print "The value of -b is", switches["b"]
      print "Non-switch arguments:", args
      return 42
      ---

      Now, I've got some stuff for dealing cleanly with invalid switches, and I've
      just rewritten runmain to be a bit cleaner and to allow long-style switches
      ("--bar").

      This works so long as runmain is the first module imported by any module that
      uses it. When the module is loaded, it can check what module loaded it and
      whether that is the "top-level" module; if it is, it invokes main(). But if
      the top-level module imports baz, and baz imports runmain, *then* the top-level
      module imports runmain -- well, the code never gets to check the top-level
      module for main(), because it is just imported from sys.modules.

      I suppose I could just check the top module for main(), regardless of who
      imported runmain, but I don't want to be calling main()s that were meant to
      work differently and sending them the wrong parameters.

      Hence the whole import-hook scheme and its flaw. If I could get it to work,
      that would let me check every module that imported runmain, to see if it was
      the top one.

      Grant D. Watson
      grant_watson@ya hoo.pleasedonts pamme.com
      (Please use this address, not my AOL one.)

      Comment

      • Grant D. Watson

        #4
        Re: Running code on module import

        >This works so long as runmain is the first module imported by any module that[color=blue]
        >uses it.[/color]

        No sooner said than I find that this doesn't work in my rewrite, only in my
        first "version" (prototype is more like). Anyway, I suspect that this is
        because in the first one I used a recursive import. (Is this dangerous? It
        seems like it ought to be.) In the second one I tried to find the main()
        function in the module object when the module hadn't finished initializing
        yet.

        Am I attempting the impossible, here? Will recursive imports burn me?

        Grant D. Watson
        grant_watson@ya hoo.pleasedonts pamme.com
        (Please use this address, not my AOL one.)

        Comment

        • Troy Melhase

          #5
          Re: Running code on module import

          On Saturday 22 May 2004 12:13 am, Grant D. Watson wrote:[color=blue]
          > Am I attempting the impossible, here? Will recursive imports burn me?[/color]

          Recursive imports won't bury you, but the next maintenance programmer might
          for modifying the behavior of the import statement beyond it's original
          intent.

          And you just never know: that maintenance programmer might be you!

          --
          Troy Melhase, troy@gci.net
          --
          The riddles of God are more satisfying than the solutions of man. - G. K.
          Chesterton


          Comment

          • Hung Jung Lu

            #6
            Re: Running code on module import

            vbasicboy@aol.c om (Grant D. Watson) wrote in message news:<200405220 35701.13396.000 01028@mb-m06.aol.com>...[color=blue]
            > By importing my magic module, I want to have my main() function invoked,
            > without any "if __name__..." stuff. My C-and-Java trained aesthetic
            > sensibilities aside, I want to do this so that I can do a bunch of
            > argv-processing stuff and just pass the results to main() without having to
            > call anything manually.[/color]

            ---------------------

            When in Rome, do as the Romans do.

            I thought your posting had some more substance to it. But now I
            realize you were simply a barbarian not used to the way of the Romans.

            But if you really want to do things the barbarian way, here is one
            way.

            ---------------------

            I guess you are a Unix user. However, I'll give you a Windows version,
            you should be able to easily do the same thing in Unix.

            Instead of running:

            python demo.py

            Create a batch (shell) file called watson.bat, with a line like:

            python runmain.py %1 %2 %3 %4 %5 %6

            and inside your runmain.py:

            # runmain.py
            import sys
            import os.path
            module_name = os.path.splitex t(sys.argv[1])[0]
            exec 'import %s' % module_name
            module = sys.modules[module_name]
            del sys.modules[module_name] # if you want so
            # tweak the args and set the switches
            .....
            # run main()
            module.main(swi tches, args)

            and then run your program using:

            watson demo.py --option1 --option2

            ---------------------

            Python may have some hooks that would allow you to intercept moments
            like the end of compilation stage, the start of execution stage, and
            the exit of normal execution. What you want to do falls into the
            general category of aspect-oriented programming. So there may be some
            other tricks. However, why complicate your life? It's much simpler
            just to do things the way Romans do, when you are in Rome.

            regards,

            Hung Jung

            Comment

            • John Roth

              #7
              Re: Running code on module import

              "Grant D. Watson" <vbasicboy@aol. com> wrote in message
              news:2004052105 0534.21796.0000 1788@mb-m15.aol.com...[color=blue]
              > If this has been answered before, or if my terminology is off, please bear[/color]
              with[color=blue]
              > me; my Python experience is limited to use in one class and to personal
              > projects.
              >
              > I'd like to do something rather silly: I'd like to run a particular piece[/color]
              of[color=blue]
              > code from a given module every time that the module is imported, and not[/color]
              just[color=blue]
              > at the time that the module is originally loaded. So, every time a module[/color]
              says[color=blue]
              > import foo
              > or something analogous, I want foo.doYourThing () to be invoked, in[/color]
              addition to[color=blue]
              > the usual effects on the importing module's namespace.[/color]

              Look at the built-in __import__() function, and the ihooks module.
              For what you want to do, you should be able to hook __import__
              so that you get control both before and after it.

              John Roth
              [color=blue]
              > Grant D. Watson
              > grant_watson@ya hoo.pleasedonts pamme.com (Use this one!)[/color]


              Comment

              • Grant D. Watson

                #8
                Re: Running code on module import

                >I thought your posting had some more substance to it. But now I[color=blue]
                >realize you were simply a barbarian not used to the way of the Romans.[/color]

                I may have visited Rome only to build a mead hall, but I'm building it with
                concrete, arches and marble columns. ;-)
                [color=blue]
                >But if you really want to do things the barbarian way, here is one
                >way.[/color]

                The way you described is quite practical, but not nearly as fun. If I was just
                concerned with making things work, it would do very well.

                It just doesn't fall into the "neat hack" category. My first concept and first
                attempts at runmain didn't add anything to "if __name__..."; I just wanted to
                see if I could do it, and learn a little bit about Python in the process. I
                still want to see if I can do it, and learn something about Python; my target
                is a bit bigger, is all.

                Grant D. Watson
                grant_watson@ya hoo.pleasedonts pamme.com
                (Please use this address, not my AOL one.)

                Comment

                • Hung Jung Lu

                  #9
                  Re: Running code on module import

                  "John Roth" <newsgroups@jhr othjr.com> wrote:[color=blue]
                  > Look at the built-in __import__() function, and the ihooks module.
                  > For what you want to do, you should be able to hook __import__
                  > so that you get control both before and after it.[/color]

                  He wants action performed *after* the main() is defined, not around
                  the time of import of his runmain. So, in a sense, he wants something
                  like a metaclass for the __main__ module.

                  Unfortunately:

                  (a) Python's modules are not classes, you can't intercept module
                  features with metaclasses.

                  (b) He wants something specified at the top module, like an "import"
                  statement. (If the *something* were specified at the bottom, it would
                  make things a bit easier.)

                  At the moment, I can only think on the sys.exitfunc as a proper hook.
                  :) It's totally esoteric/un-orthodox. But for whatever it's worth,
                  here is one example. Since it's totally un-orthodox, do not expect it
                  to run properly under all circumstances. (E.g.: it won't run from
                  console, it won't run inside Pythonwin, etc.) But it does run when
                  executed with standard shell command line.

                  #--- demo.py
                  import runmain
                  x=3
                  def main(switches, args):
                  if switches['print']:
                  legend = args[0]
                  print legend, x

                  #--- runmain.py
                  import sys
                  def runmain():
                  args = ['The value of %s is' % sys.argv[1]]
                  switches = {'print': 1}
                  sys.modules['__main__'].main(switches, args)
                  sys.exitfunc = runmain

                  #--- command line
                  python demo.py x

                  #--- result
                  The value of x is 3

                  --------------------------------

                  As I have said, it's best to do as the Romans do, when in Rome. Bite
                  the bullet and use the "if __name__ == '__main__':" that everyone else
                  uses. It's really not that bad looking. Any args tweaking or switches
                  can be done at the import of a tweaking module. Seriously, something
                  like below would do.

                  import myparams # creates args (from sys.argv) and switches

                  def main():
                  .... uses myparams.args and myparams.switch es

                  if __name__ == '__main__':
                  main()

                  Hung Jung

                  Comment

                  Working...