1

I have a python program running in the background that has a multitude of packages/modules. It has also a specific module I have added to the python installation folder called qwerty.pyc.

I am importing this said module using the _import_ method and my script looks something like this:

import json
    
qwerty = __import__("qwerty")
c = qwerty.qwerty()
c.data()

Now, whenever I remove qwerty.py from the python installation folder (in libs folder) the python script that's running in the background still runs without any issues instead of throwing an error that it can't find the module.

I believed using _import_ will dynamically load the module at runtime. Is there a way to truly load this module during runtime without caching?

qwerty
  • 887
  • 11
  • 33
  • Are you repeatedly importing qwerty? If you only do it once, its contents will reside in main memory and won't be affected by changes in the file system. – Jan Wilamowski May 17 '22 at 05:17
  • @JanWilamowski is there a way around this without restarting the interpreter? – qwerty May 17 '22 at 17:06
  • What do you actually want to achieve? If you need to check whether a file exists at runtime, there are multiple ways to do that. No need to rely on import mechanics. – Jan Wilamowski May 18 '22 at 00:35
  • @JanWilamowski I want to check if the file actually exists that I'd like to import into my script so I can use the methods inside that pre-compiled script. – qwerty May 18 '22 at 04:41
  • That doesn't sound like a safe way to do it. The execution could fail for a number of reasons which will be hard to predict. In that case, Python should raise an appropriate error. If you want to check that at import time and output a custom error message, you can wrap the import call in a try/except block. – Jan Wilamowski May 18 '22 at 05:18
  • @JanWilamowski I have taken care of the errors that it could cause. What's eluding me is to import the module at runtime. So basically, everytime the script is executed it imports the module (.pyc script) each time. This means even if the module (.pyc script) is changed, it picks up the changes. – qwerty May 18 '22 at 06:30

0 Answers0