0

I have used this SO answer to dynamically generate a module x and register it in sys.modules. I want a piece of code to run automatically when an import is called on this module. so for example I want print "you just imported module x". So it behaves like:

>>> import x
you just imported module x

How do I get this behavior?

3
  • 4
    why not put it in the module itself? i.e right before class Foo: in the example Commented Dec 4, 2015 at 19:08
  • Should this happen every time the module is imported? If so, you'll probably need to mess with import hooks to do that. Commented Dec 4, 2015 at 19:15
  • Padraic that doesn't give the desired behavior because the print code is executed when exec is called not when the module is imported. Commented Dec 4, 2015 at 19:37

2 Answers 2

0

To simply extend the example given in the selected answer you could something like this.

print "You just imported module {}".format(foo.Foo.__module__)
Sign up to request clarification or add additional context in comments.

2 Comments

If you do that and then run the line from the example exec foo_code in foo.__dict__ the print will happen as soon as you call exec this does not make it so the print runs on import foo
That would be true if that was in the module being imported. My understand is this code would go in the module doing the importing.
0

Any "orphan" code (code that isn't written inside a class or a function, or inside an if __name__ == '__main__:' block) will be executed when you import the module.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.