How to include external Python code to use in other files?

Python

Python Problem Overview


If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?

So if I have:

[Math.py]
def Calculate ( num )

How do I call it like this:

[Tool.py]
using Math.py

for i in range ( 5 ) :
    Calculate ( i )

Python Solutions


Solution 1 - Python

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

Solution 2 - Python

Just write the "include" command :

import os

def include(filename):
	if os.path.exists(filename): 
		execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Solution 3 - Python

If you use:

import Math

then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.

If you want to import a module's functions without having to prefix them, you must explicitly name them, like:

from Math import Calculate, Add, Subtract

Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

from Math import *

However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

Solution 4 - Python

I've found the python inspect module to be very useful

For example with teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

And from the another script or the python console

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

And now dostuff should be in the local scope and dostuff() will return the console or scripts name whereas executing test.dostuff() will return the python modules name.

Solution 5 - Python

I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5.

Alternative #1

import textwrap 
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))

Alternative #2

with open('myfile.py') as f: exec(f.read())

I prefer Alternative #2 and have been using it in my website development.

Solution 6 - Python

It's easy and simple: you can just do this:

def run_file(path):
    return exec(open(path).read());

run_file("myfile.py");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoan VengeView Question on Stackoverflow
Solution 1 - PythonAndrew HareView Answer on Stackoverflow
Solution 2 - PythonLouisView Answer on Stackoverflow
Solution 3 - PythonryeguyView Answer on Stackoverflow
Solution 4 - PythonwhardierView Answer on Stackoverflow
Solution 5 - PythonStan S.View Answer on Stackoverflow
Solution 6 - PythonAvyukt MoreView Answer on Stackoverflow