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 )
You will need to import the other file as a module like this:
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 *
Just write the “include” command :
import os def include(filename): if os.path.exists(filename): execfile(filename) include('myfile.py')
@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
If you use:
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.
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.
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!
import textwrap from pathlib import Path exec(textwrap.dedent(Path('myfile.py').read_text()))
with open('myfile.py') as f: exec(f.read())