In Python 3.4 and later, you can import from a source file directly (link to documentation). This is not the simplest solution, but I'm including this answer for completeness.
Here is an example. First, the file to be imported, named foo.py:
def announce(): print("Imported!")
The code that imports the file above, inspired heavily by the example in the documentation:
import importlib.util def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module foo = module_from_file("foo", "/path/to/foo.py") if __name__ == "__main__": print(foo) print(dir(foo)) foo.announce()
The output:
<module 'foo' from '/path/to/foo.py'> ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce'] Imported!
Note that the variable name, the module name, and the filename need not match. This code still works:
import importlib.util def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module baz = module_from_file("bar", "/path/to/foo.py") if __name__ == "__main__": print(baz) print(dir(baz)) baz.announce()
The output:
<module 'bar' from '/path/to/foo.py'> ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce'] Imported!
Programmatically importing modules was introduced in Python 3.1 and gives you more control over how modules are imported. Refer to the documentation for more information.
applicationnorapp1,app2,folder,some_folderare packages, and do not contain__init__.py, right? If you're going to be doing a lot of this, time to make them a package.appandapp2as two logically separate projects/packages or not. If they are separate (for example theappis a common utility for several appsapp2,app3, ...) then you can install theappfrom its Github repository intoapp2's (virtual) environment as a dependency usingpipand then use it the same way you use any other third-party package.