2

Say I have a function which takes two arguments: arg1, arg2. I want the function to then call arg1_arg2.py. Of course, the actual file wouldn't be called arg1_arg2.py. So, if the user inputs hello, hi as the arguments, the function will call hello_hi.py (more specifically, it instantiates a class located in hello_hi.py, but that is not important). I can't do this using %s, since I am dealing with files, not strings.

Philip Geske
  • 47
  • 3
  • 10

2 Answers2

4

You can use importlib:

import importlib

hello = importlib.import_module("hello_hi.py")
Aamir Rind
  • 36,955
  • 19
  • 118
  • 157
0

It sounds like you want to use importlib shown here. Something like

import importlib
importlib.import_module("{}.py".format(your_str))

I think there's almost certainly a better way to do this though -- why not just put a toplevel __init__.py in your directory -- assume the directory is myclasses -- and then instantiate getattr(myclasses, your_str).ClassName() instead. importlib seems like the wrong way to go.

Community
  • 1
  • 1
Patrick Collins
  • 9,805
  • 4
  • 26
  • 66