I’m trying to conditionally call a function based on the availability of a module, and that availability is not known until runtime.
The code does not work and I’ve reduced my issue down to the following minimum reproducible testcase where a module imported within a function is visible in sys.modules
but is otherwise not actually fully available. What is going on? (And how can I fix it?)
#!/usr/bin/env python3
import sys
# python --version - Python 3.10.12
def import_re():
import re
if 're' in sys.modules:
print("Yes, it is there 1")
import_re()
if 're' in sys.modules:
print("Yes, it is there 2")
re.match('a', 'a')
'''
Output:
Yes, it is there 1
Yes, it is there 2
Traceback (most recent call last):
File "/tmp/test2.py", line 13, in <module>
re.match('a', 'a')
NameError: name 're' is not defined
'''