0

I know it is possible to conditionally import modules. My question is; if the condition to import a module is false, will the module still be loaded (and just sit idle in the background), or not.

I ask this from a resource point of view. Using a Raspberry Pi for programming does have its limits for example. This is just a hypothetical question... I haven't run into any problems yet.

0

1 Answer 1

2

No, it is not imported, and it is not loaded.

This code verifies that the module is not added to the namespace:

>>> if False:
...     import time
... else:
...     time.clock()
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
NameError: name 'time' is not defined

And this code proves that the import statement is never run, as otherwise it would have generated an ImportError. This means that the module is never loaded in sys.modules, the cache (in the memory) of all modules that have been imported previously.

>>> if False:
...     import thismoduledoesnotexist
...
>>> import thismoduledoesnotexist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named thismoduledoesnotexist

This is mainly due to the fact that all that Python does prior to running the script is compile it to bytecode, and as such does not evaluate the statements before their occurence.

Sign up to request clarification or add additional context in comments.

2 Comments

you can also check sys.modules if the module was loaded.
@GabrielSamfira you commented while I was editing my answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.