'Python Import in if performance

I know normally you should descripe your question the best you can. But now im just wondering if this code has better performance than import module on top of the code, because maybe its not in use.

a = 1
b = int(input()) # Input for testing
if b - a == 1:
    import Module 
    # use module

What about Not builtin librarys?

Cheers.



Solution 1:[1]

if (condition):
    import module
else:
   pass
module.foo()

This will raise an exception when the condition is False, because at module.foo() the module won't be defined.


What's more writing

else:
    pass

is completely useless, since an if statement doesn't need an else.


Probably you were asking something like:

Has not importing things you don't use a performance advantage over importing it?

In this case the answer is YES, but if your code doesn't need a very fast performance, I would suggest to simply import it even if you're not sure if you'll use it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FLAK-ZOSO