Reputation: 45
I oftentimes see classes containing def execute(self)
and def run()
Does python automatically pick this up like int main() in C++?
Upvotes: 1
Views: 16313
Reputation: 901
The run()
method is used by the Thread and Process classes (in the threading
and multiprocessing
modules) and is the entry point to the object when you call the it's .start()
method.
If you've seen it outside of that usage then I would think that it's probably either contextual or coincidental.
I'm not aware of any canonical execute()
method.
Upvotes: 1
Reputation: 101
This can occur in airflow where you create a custom Operator. The name execute is an exclusive name:
Execute - The code to execute when the runner calls the operator. The method contains the airflow context as a parameter that can be used to read config values.
https://airflow.readthedocs.io/en/stable/howto/custom-operator.html
Upvotes: 0
Reputation: 29
I'm a python newb, so take with a grain of salt, but there is a "common practice" with the run() method https://docs.python.org/3/library/threading.html I cant give more in depth explanation, since I'm also still putting 2+2 together, but I guess someone else might shed some light.
The Thread class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the init() and run() methods of this class.
Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.
Upvotes: 2
Reputation: 2072
Python is an interpreted language, by default it will read line by line until end of file. Functions can be defined and called, etc. but there is no point of entry like in C.
However typically in python code people include something like the following:
if __name__ == "__main__":
doSomeFunCodeIHave()
The purpose of this is to only execute if the source file is being executed, rather than being imported. This is also a useful way to include testing code for a module which can be excluded when you later use it in a project.
Upvotes: 2
Reputation: 11460
No, those methods are not "automatically" run. There is nothing special about them, probably execute
and run
is quite common names for methods and you've seen them multiple times by coincidence.
However, there is a way to execute a "main" method as soon as you run your script. You do this in the following manner:
# script.py
def foo():
print "Hello World!"
if __name__== "__main__":
foo()
If you run python script.py
then Hello World
will be printed to the console.
Upvotes: 1
Reputation: 533
No. Not unless your script is loaded inside some wrapper code that in turn executes your file's run or execute function.
Upvotes: 1