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

Question

Asked By – Joan Venge

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 )

Now we will see solution for issue: How to include external Python code to use in other files?


Answer

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.

This question is answered By – Andrew Hare

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0