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?

Community
  • 1
  • 1
Hamzeh Alsalhi
  • 403
  • 1
  • 4
  • 10

2 Answers2

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__)
Jared Mackey
  • 3,998
  • 4
  • 31
  • 50
  • 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` – Hamzeh Alsalhi Dec 04 '15 at 19:36
  • 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. – Jared Mackey Dec 04 '15 at 19:37
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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154