I am working on Python 2.6/2.7 code which contains the following:
try:
import gmpy
gmpy_imported=True
except ImportError:
gmpy_imported=False
if gmpy_imported and gmpy.__file__ is None:
gmpy_imported=False
I can understand the try-except
part, which is used to see if gmpy has been installed on the system -- and if not, to do whatever. However, I do not understand why the if gmpy.__file__ is None
check is necessary; it seems redundant.
Are there any circumstances when importing a package would appear to have succeeded, but the path to the package would in fact be empty? Is this double-check a failsafe against a corrupted installation?
Use: if "sys" not in dir(): print("sys not imported!")
When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.
When you import a module in Python, all the code in it will be run, and all the variables in that module will be stuck on that module object.
What is import * in Python? Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way. Functions such as importlib.
There's no point in this check. If the module/package had been successfully been imported, __file__
would never be none, it'd be the path of the module.
The docs say "The __file__
attribute is not present for C modules that are statically linked into the interpreter", so I believe it's redundant. Beside, what difference would it make, the module object is there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With