Search code examples
pythonstringmodulepython-module

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?


Solution

  • 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)