I know this question has been asked before but I can't make heads or tails of what the answer means.
I am making the transition from MATLAB to Python. In MATLAB I can write my own functions and use them in my code. I know I can do the same thing in Python. But I am having a hard time figuring out how to do it.
What I would like to do it create a file with multiple function definitions and then import it into Python like any other module.
First, is this the proper way of thinking it about it? Or do I just need to create multiple definition files for each function?
Second, if it is the proper way of thinking about it how do I access the file? I know you have to set the PYTHONPATH. I have looked at it and where it is looking makes no sense to me.
As an Example: I created a folder called User. In it I have a python function called ted.py. I put said file where the rest of the library files are located (as in numpy or scipy). I want to import the file called User. How can I do this?
After working with Python for awhile I get it. As long as the file is in the same directory and you use the import properly you can use one , some or all of the function definitions in the file.
2 Answers 2
You have an un-matlab-like (matlab-unlike? dis-matlab-like?) option of putting multiple function definitions into the same .py file. Once the file -- say, fundefs.py -- is on your path, possibly through having issued import sys; sys.path.append('path/to/fundefs');, you can import it
- through
import fundefs, after which you can access the functions therein byfundefs.fun1,fundefs.fun2etc. - through
from fundefs import *, which will throw all the functions into your current namespace. This is generally discouraged (and frowned upon) for larger modules as it will pollute your namespace, but for a few functions of your own this might just be what you're after. See also this very informative answer (and also comments therein). - as a middle ground through
import very_long_and_descriptive_module_name as shorthandto access your functions asshorthand.fun1,shorthand.fun2etc. (in the obvious case if your definitions are in the filevery_long_and_descriptive_module_name.py)
Comments
You don't import User. What you want is to import ted. Typically, you would put ted.py in the same folder as your main python file, not in a separate folder.
pyfile can be imported as a module. Just writefrom filename import functionNameand you are done.import sys; sys.path.append('dirname')to adddirnameto your python path for importing.