When is it beneficial to use inline, single use importing in Python?
Is the above ever shorter than the below?
import x x.doSomething()
from x import* doSomething()
This can be useful if you want to use a module just once in an anonymous lambda function, as it allows you to avoid writing a separate statement:
is one byte shorter than
from SomeModule import*;f=lambda x:foo(x,123)
If the code is a named function or program, then
__import__ is unlikely to help except in the most extreme or contrived circumstances.
When importing multiple modules with sufficiently long names, it can be helpful to assign the
__import__ function to a shorter variable and use it for imports
Regular import statements - 97 bytes
from itertools import* from datetime import* print list(permutations("abc")) print datetime.now()
i - 94 bytes:
i=__import__ print list(i("itertools").permutations("abc")) print i("datetime").datetime.now()
__import__("x").doSomething() needs 15+x characters to refer to a module with a name of length x.
import x\nx.doSomething() needs 9+2*x characters. These functions overlap at x=6, so compared to this way any module with a longer name is better off using
__import__, anything shorter benefits from normal imports:
from x import*\ndoSomething() needs only 14+x characters, so compared to the normal import it is not worth it unless the module name is longer than 5 characters:
This all assumes that you are referring to a function/class/whatever only once. If you refer to it more than once, the formulas change, and the latter version might become the winner. In case you use something long from an imported module several times, yet another version wins:
from x import y as z nets you 18+x+y+z*(n+1) characters for n uses of z, which is a large improvement if y is big, because z can be made 1.