0

In Perl, we have the @INC subroutine trigger that allows executing a subroutine when it's loaded through use or require. When is a subroutine reference in @INC called?

Is there something similar in Python? For example, if I have a file test_random.py which has import random statement in it; is it possible for me to insert functionX() in sys.path so that when Python searches for random in sys.path, it'll run functionX() before it finds random?

Nikhil Hegde
  • 341
  • 1
  • 3
  • 15
  • Not when searching, however upon import python will execute any statement in the module, so if you call `functionX()` in your module, python will run it. – mehdix Mar 07 '18 at 12:46
  • Right, but don't you think that would be overkill? I have more than 50 modules on my plate and if I need to copy-paste the same `functionX()` in all the modules, that would be a lot of duplicate code – Nikhil Hegde Mar 08 '18 at 07:08
  • If you put your 50 modules in one package and put your `functionX()` in `__init__.py` inside that package, python will call it only once. Upon first import from the package. – mehdix Mar 08 '18 at 07:50
  • That's a good idea. I'll try it out and get back to this thread. – Nikhil Hegde Mar 08 '18 at 07:53

0 Answers0