When is it beneficial to use inline, single use importing in Python?
For example:
__import__("x").doSomething()
Is the above ever shorter than the below?
import x
x.doSomething()
Or
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:
lambda x:__import__('SomeModule').foo(x,123)
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.
__import__
would help inside of a named function since it would be inside of an indented block. An import would cost extra since it's on two lines and indented. (That's assuming that imports aren't allowed outside of the function.)
\$\endgroup\$
import
would be called inside of an indented block? Probably not.
\$\endgroup\$
f=
because anonymous functions are allowed and can have content outside the function.
\$\endgroup\$
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()
Assigning __import__
to 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:
However, 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.
__import__("x").doSomething()
to be one char shorter than from x import*;doSomething()
. Maybe you're counting the newline as two chars? And I recall the break-even point being 5, falling between time
and random
.
\$\endgroup\$
z=__import__("x").y
is a byte shorter than from x import y as z
\$\endgroup\$
Commented
Jun 18, 2019 at 13:06
from x import*;z=y
.
\$\endgroup\$
Commented
Jun 18, 2019 at 14:05