Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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()
share|improve this question
10  
Questions asking about how to shorten specific pieces of code or for general help with golfing are most definitely on topic. –  Martin Büttner 21 hours ago

1 Answer 1

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.

share|improve this answer
    
__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.) –  Alex A. 21 hours ago
    
@AlexA I see no problem with placing imports outside of a named function. –  feersum 21 hours ago
    
Then would there ever be a time when import would be called inside of an indented block? Probably not. –  Alex A. 21 hours ago
    
placing imports outside of the named function won't work for challenges where you're writing just one function. –  Sparr 19 hours ago
2  
The second example doesn't require the f= because anonymous functions are allowed and can have content outside the function. –  xnor 19 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.