It seems they canceled in Python 3 all the easy way to quickly load a script by removing execfile()
Is there an obvious alternative I\'m missing?
Avoid exec()
if you can. For most applications, it's cleaner to make use of Python's import system.
This function uses built-in importlib to execute a file as an actual module:
from importlib import util
def load_file_as_module(name, location):
spec = util.spec_from_file_location(name, location)
module = util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
Let's have a file foo.py
:
def hello():
return 'hi from module!'
print('imported from', __file__, 'as', __name__)
And import it as a regular module:
>>> mod = load_file_as_module('mymodule', './foo.py')
imported from /tmp/foo.py as mymodule
>>> mod.hello()
hi from module!
>>> type(mod)
This approach doesn't pollute namespaces or messes with your $PATH
whereas exec()
runs code directly in the context of the current function, potentially causing name collisions. Also, module attributes like __file__
and __name__
will be set correctly, and code locations are preserved. So, if you've attached a debugger or if the module raises an exception, you will get usable tracebacks.
Note that one minor difference from static imports is that the module gets imported (executed) every time you run load_file_as_module()
, and not just once as with the import
keyword.