daniel
daniel

Reputation: 73

How do I import something from a module in a folder with a string?

How do you import something from a module in a folder using a string. I have tried to use the __import__ statement. And also the library: importlib. I just don't really understand how to use it. Here's what I'm trying to do:

/folder
    questions.py

__init__.py
app.py

In the questions.py there is a dictionary called math_questions with it's questions and answers. How do I import questions.py from app.py using a string?

Upvotes: 0

Views: 51

Answers (1)

alexisdevarennes
alexisdevarennes

Reputation: 5632

Welcome to SO!

Create an empty __init__.py file in your folder directory.

Then in app.py do: from folder import questions or import folder.questions as questions

Suppose questions.py has a method or variable called foo, you can then use it as follows:

print(questions.foo())

or if its a variable:

print(questions.foo)

For python3: if you want to import a file using a string, you could use exec (make sure that you trust the input)

lib_to_import = input('Which module to import?')
exec('import %s' lib_to_import)

For python2:

import importlib
lib_to_import = input('Which module to import?')
mod = importlib.import_module(lib_to_import)

Upvotes: 2

Related Questions