Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: can __file__ be None if import has succeeded?

Tags:

python

import

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?

like image 462
Boris Avatar asked Feb 20 '13 00:02

Boris


People also ask

How do I know if a Python module is imported?

Use: if "sys" not in dir(): print("sys not imported!")

What happens when you import a module Python?

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.

Does importing a Python file run it?

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?

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.


2 Answers

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.

like image 64
Toby Person Avatar answered Sep 22 '22 11:09

Toby Person


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.

like image 23
martineau Avatar answered Sep 21 '22 11:09

martineau