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

Posted on

Question :

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

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:

def Calculate ( num )

How do I call it like this:


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

Answer #1:

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.

Answered By: Andrew Hare

Answer #2:

Just write the “include” command :

import os

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


@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


Python 2 and 3: alternative 2

Answered By: Louis

Answer #3:

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.

Answered By: ryeguy

Answer #4:

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

For example with

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":


And from the another script or the python console

import teststuff



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.

Answered By: whardier

Answer #5:

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. Happy coding!

Alternative #1

import textwrap 
from pathlib import Path

Alternative #2

with open('') as f: exec(
Answered By: Stan S.

Leave a Reply

Your email address will not be published. Required fields are marked *