1

I wanna something like that :

import Variant
x = Variant.Pop1
from x import mid

is this possible?

7
  • 5
    Can't you simply do from Variant.Pop1 import mid? Commented Mar 2, 2020 at 16:18
  • @chuck2002 Because I have a list of the file as Variant.Pop1, Variant.Pop2,... and each file has the same function name "mid" like def mid(a,b) but different context. I wanna get result unit test like mid(1,2) mid(1,3) mid(1,4)... from Variant.Pop1, Variant.Pop2,... . I wanna pass Variant.Pop1, Variant.Pop2,.. as a variable of a function Commented Mar 2, 2020 at 16:30
  • 2
    I think it would be cleaner to import them manually - from Variant.Pop1 import mid as pop1_mid, from Variant.Pop2 import mid as pop2_mid and so on. Commented Mar 2, 2020 at 16:36
  • This is a good question. Can't imagine why its downvoted. Commented Mar 2, 2020 at 16:44
  • @tdelaney It may be an interesting question, but there's a very real possibility that it's not the best solution for OP. Commented Mar 2, 2020 at 17:17

4 Answers 4

1

To import a module from a name in a variable, use importlib (see python docs)

For example:

import importlib
import os.path as p
x = p.__name__
q = importlib.import_module(x)

Of course, this example is silly because q ends up as with the same value as p, but it demonstrates the syntax. Please provide more detail if this is not what you want.

Another option is to use exec, as in this other post

Sign up to request clarification or add additional context in comments.

1 Comment

That's awesome! I tried exec and it's work exactly what I want. Thanks a lot !!! @Gordon Hopper
1

I don't know if it will help you, but you could consider the importlib module: it allows to make dynamic import like:

from importlib import import_module

module_names = ["Pop1", "Pop2", ...]

def foo():
    for name in module_names:
        module = import_module(name, "Variant")
        module.mid(...)

Comments

0

It is, but this is not a good example of how to import modules, it's a bad practice.

This is exactly what you want to do, but better.

from Variant.Pop1 import mid as x

def my_func(var):
   # do something

my_func(x)

Example:

from random import choice as x

my_list = [1, 2, 3, 4]

def my_func(var):
    return var(my_list)

print(my_func(x))

Comments

0

You can use importlib. The import specification is like a directory structure using "." to step through module names. A module keeps its "directory name" in __package__. So,

import importlib
import Variant
x = Variant.Pop1
mid = importlib.import_module(".".join(x.__package, "mid"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.