Blue Monday Blue Monday - 9 days ago 7
Python Question

Importing module in a function when returning

I've being searching on how to do this, but I could not find if there is a solution. I thought

__import__
? But I still couldn't manage to figure it out.
For example:

>>> def combs(s = []):
... from itertools import combinations
... return [list(combinations(s, 2))]
...
>>> lst = ["A","B",'C']
>>> print(combs(lst))
[[('A', 'B'), ('A', 'C'), ('B', 'C')]]
>>>


I'm curious if something like this could be done?

def combs(s = []):
return [list(combinations(s, 2))]__import__(itertools, list)

Answer

Here is how to achieve a dynamic import in your example:

def combs(s = []):
    return list(__import__('itertools').combinations(s, 2))

NB: the python docs for __import__ state that:

This is an advanced function that is not needed in everyday Python programming

Many Pythonistas would prefer an explicit import (as in your original example), and would probably consider excessive use of __import__ to be a bit of a code smell.

Comments