130

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 )
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Joan Venge
  • 315,713
  • 212
  • 479
  • 689

6 Answers6

163

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.

nelsonda
  • 1,170
  • 1
  • 10
  • 21
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
54

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()))
Louis
  • 2,854
  • 2
  • 19
  • 24
  • 3
    Is there any reason to do this over `from module import *`? Also, if the file you're calling has code in the body, that code will be run, if you do this. – naught101 Feb 10 '15 at 00:15
  • 4
    @naught101 : That's the goal : to run the code, which does not happen with an import. Ususally it's just defining variables. – Louis Feb 10 '15 at 07:19
  • This does not work for me. in include(filename) 1 def include(filename): 2 if os.path.exists(filename): ----> 3 exec(filename) 4 in () NameError: name 'test' is not defined Running ipython 3.4. – CoderGuy123 Aug 12 '15 at 17:57
  • 2
    @Deleet python 3 doesn't have `execfile` – bfieck Sep 15 '16 at 22:29
  • 9
    Actually python 3 has another signature for `compile()` than mentioned. So the correct Python 2 and 3: alternative 2 will be: `exec(compile(source=open('myfile.py').read(), filename='myfile.py', mode='exec'))` – TriAnMan Dec 15 '16 at 22:31
  • 3
    The 'include' helper function doesn't work if you want to have variables in the included file in scope in the caller of 'include' – paulj Mar 04 '17 at 13:04
  • It's incorrect to say that code is not run on import. It is. Try making a sample module yourself and see. Further, `exec` seems to me to be a security vulnerability waiting to happen, in the vein of running `subprocess` with `shell=True`. – Daniel R. Livingston May 30 '19 at 20:51
  • 1
    `exec(compile(source=textwrap.dedent(open('myfile.py').read()), filename='myfile.py', mode='exec'))` 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. If the python version support pathlib, use `exec(textwrap.dedent(pathlib.Path('myfile.py').read_text()))`. By the way, `exec(compile(open('myfile.py').read()))` does not run in my testrun (Python 3.6 Win10) . – mikey Sep 27 '19 at 09:05
  • @Louis an import of a Python module actually does execute the code. (Variable/function/class definitions are all executable statements in Python.) – toolforger Dec 20 '22 at 22:55
34

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.

ryeguy
  • 65,519
  • 58
  • 198
  • 260
2

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

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

run_file("myfile.py");
1

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.

whardier
  • 665
  • 5
  • 8
1

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Stan S.
  • 237
  • 7
  • 22