In Blender 2.80 and higher, you can use
In the above example, an unsaved text editor shows this code:
print('This is my test function, running')
print('This is my test module, running')
Then, in the Blender Python console on the left, you can import this:
myModule = bpy.data.texts.as_module()
Note that since this is my only text file, I've used
texts to reference it. If you had multiple, you would reference by name, such as
texts["Text"] or similar.
Note that anytime the source code changes, you will have to re-run the
as_module() command again to pick up the changes.
Finally, I can call functions from the module I imported, like so:
This uses the variable name that was assigned by the
as_module() line, and looks for a named function within that module to call.