This question already has answers here:
How do I call a function from another .py file? [duplicate]
(19 answers)
Closed 6 years ago.
I'm new to Python, coming from Matlab like many. I'm used to defining my functions as standalone .m files and calling them easily from a second script as long as the function is saved somewhere within the defined Matlab path.
I've learned how to define a (user-defined) function in Python (def my_function() etc.), but I'm coming up short in my Google searches on a way to define the function in a a separate .py file A, and how to call it in another script B. All help files I can find give support on how to define the function within the same script. When I try calling the function (which I've defined as a .py file in the same folder I'm using for script A) my script doesn't recognize it. Do I need to be declaring the function at the beginning of my script? I'm getting the sense that Python is very different in the way it handles these things than Matlab--perhaps I can't do this?
Cheers
You have to use imports
for example, you have the function doSomething() in functions.py and want to work in main.py
in main.py
from functions import doSomething
var = doSomething()
Related
This question already has answers here:
How to get local variables updated, when using the `exec` call?
(3 answers)
Closed 4 years ago.
In my main script, I import one of my own module which contains global variables. This main script execute another script with the function exec (exec(compile(open(Seq_1, "rb").read(), Seq_1, 'exec')) and this other script import the same module.
So my question is: does these scripts have access to the same global variables (that means if I modify one global variable, the other script will be impacted) or not?
Python will run your file when you first import it. On the second import python won't re-run the file.
In practice, python functions and variables directly on modules (not wrapped in classes) works like singletons.
This answer explains more about it. You can directly refer to the docs, also suggested on linked answer.
This question already has answers here:
Import folder of modules in Python
(3 answers)
Closed 7 years ago.
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.
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 by fundefs.fun1, fundefs.fun2 etc.
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 shorthand to access your functions as shorthand.fun1, shorthand.fun2 etc. (in the obvious case if your definitions are in the file very_long_and_descriptive_module_name.py)
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.
This question already has answers here:
How can I access environment variables in Python?
(16 answers)
Closed 9 years ago.
I'm new to Python and would like reproduce a convenience I used when working in Perl.
When calling a Perl script I usually set some $ENV variables (like VERBOSE, DEVELOP and DEBUG). Inside the called script I recover their values using
my $verbose=$ENV{VERBOSE};
my $develop=$ENV{DEVELOP};
my $debug=$ENV{DEBUG};
This allow print stmts conditional on these variables.
Can I do the same thing in Python? I know thanks to previous responses (Thank you!) to use os.environ[var] within the script to access the values. But I have not been able to figure out how to assign a value to a variable when I call the script from the command line as I could when callinbg a Perl script
Can values be set for such variables on the commandline invoking a python script?
TIA
They are accessible via the os.environ dictionary.
os.environ['VERBOSE']
This question already has answers here:
Does python optimize modules when they are imported multiple times?
(6 answers)
Closed 8 years ago.
I'm wondering about a few things concerning importing modules.
I have a module that contains nothing but a list of variables, so that I can use these across 3 or 4 scripts that run either once or daily.
This same module I would like to use in another script of mine, but I only need to load it once, and afterwards, I don't need the module anymore, because I would copy the variables to a list in my script(for comparison purposes).
My questions:
1. if I import the module in a method, is it discarded when the function ends?
2. what is the memory-impact on importing a module?
Good to know is that the function is one-shot.
Greetings
A reference to the module is stored in sys.modules, so no it's not released.
Consider using execfile or similar if you don't want to load the module
You can actually unload a module from python, it will be garbage collected if it is not referenced anymore :
del sys.modules["mymodule"]
del mymodule
This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 6 months ago.
I occasionally notice something like the following in Python scripts:
if __name__ == "__main__":
# do stuff like call main()
What's the point of this?
Having all substantial Python code live inside a function (i.e., not at module top level) is a crucial performance optimization as well as an important factor in good organization of code (the Python compiler can optimize access to local variables in a function much better than it can optimize "local" variables which are actually a module's globals, since the semantics of the latter are more demanding).
Making the call to the function conditional on the current module being run as the "main script" (rather than imported from another module) makes for potential reusability of nuggets of functionality contained in the module (since other modules may import it and just call the appropriate functions or classes), and even more importantly it supports solid unit testing (where all sort of mock-ups and fakes for external subsystems may generally need to be set up before the module's functionality is exercised and tested).
This allows a python script to be imported or run standalone is a sane way.
If you run a python file directly, the __name__ variable will contain __main__. If you import the script that will not be the case. Normally, if you import the script you want to call functions or reference classes from the file.
If you did not have this check, any code that was not in a class or function would run when you import.
The sole purpose of this, assuming it is in main.py, is so other files can import main to include classes and functions that are in your "main" program, but without running the source code.
Without this condition, code that is in the global scope will be executed when it is imported by other scripts.
It's a great place to put module tests. This will only run when a module is run directly from the shell but it will not run if imported.