Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import syntax

Does this:

import foo as bar

do the same thing as this?

bar = __import__('foo')

Is there ever a reason to use the latter one?

I'm reading through someone elses code, I found the latter one and am not sure why they didn't use the prior syntax

like image 881
tMC Avatar asked Dec 09 '22 08:12

tMC


2 Answers

Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.

source

like image 182
Alex Hirzel Avatar answered Dec 31 '22 19:12

Alex Hirzel


The two statements do the same thing. The only reason to use the latter syntax is not knowing the module name in advance.

like image 29
Sven Marnach Avatar answered Dec 31 '22 18:12

Sven Marnach