简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM