I want to pass my program a file and get a function out of it.
For example, I have a file, foo.py, who's location is not known until run time (it will be passed to to code by the command line or something like that), can be anywhere on my system and looks like this:
def bar():
return "foobar"
how can I get my code to run the function bar?
If the location was known before run time I could do this:
import sys
sys.path.append("path_to_foo")
import foo
foo.bar()
I could create an init.py file in the folder where foo.py is and use importlib or imp but it seems messy. I can't use __import__ as I get ImportError: Import by filename is not supported.
importlib[...] but it seems messy." You have to resort to messy solutions when you have messy problems. Why isn'timportlibsufficient?__init__.pyfile at all. In Py3, the more powerfulimportlibfunctions are the correct way to import arbitrary files. In earlier Python, you can just add the folder containingfoo.pytosys.path, then runimport foowithout using a special importing function at all.import fooas I don't know the file name until run time.init.pyfile and leave it lying around, I could clean it up afterwards. I don't know how I can be sure to get rid of it but that's another topic. It just seems perverse that I have to create an empty file to do something.