Golfing with Python Import

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.


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

Example:

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()