tags:

views:

2859

answers:

6

Kinda in relation to this question...

what does the if __name__=="__main__": part do?

# Threading example
import time, thread

def myfunction(string,sleeptime,lock,*args):
    while 1:
        lock.acquire()
        time.sleep(sleeptime)
        lock.release()
        time.sleep(sleeptime)
if __name__=="__main__":
    lock=thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

Also, what does *args mean in this example?

+2  A: 

if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python myscript.py.

*args allows you to give the function more arguments than are explicitly required in the function definition.

Harley
I'm new to Python, but I thought *args was a list, and **kwargs was a dictionary?
Josh Smeaton
Yep, that's correct. Also worth pointing that the names (args and kwargs) aren't important either, it's the stars (* and **) that matter.
Harley
+23  A: 

Expanding a bit on Harley's answer...

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to a different value.

In the case of your script, let's assume that it's executing as the main function, e.g. you said something like

python threading_example.py

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.

One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

See this page for some extra details.

Mr Fooz
+8  A: 

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran. Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluate to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If that code is being imported into another module, the various function and class definitions will be imported, but the main() code won't get run. As a basic example, consider the following two scripts:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")

# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

Now, if you invoke the interpreter as

python one.py

The output will be

top-level in one.py
one.py is being run directly

If you run two.py instead:

python two.py

You get

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.

Adam Rosenfield
+8  A: 

The syntax *args in a function declaration lets you accept an arbitrary number of parameters (other than those explicitly named, like string, sleeptime,and lock in your example):

def printStuff(*args):
    for arg in args:
     print arg

printStuff(1, 2, "Hello World")

1
2
Hello World

The syntax *args in a function call lets you call with the items of the list args as further arguments:

args = [4, 5, "Goodbye"]
printStuff(2, 3, *args)

2
3
4
5
Goodbye
Federico Ramponi
+5  A: 

The simplest explanation (imho) is the following:

Create the following files.

# a.py
import b

and

# b.py
print "Hello World from %s!" % __name__

if __name__ == '__main__':
    print "Hello World from %s!" % __name__

Running them will get you this output:

$ python a.py
Hello World from b!

$ python b.py
Hello World from __main__!
Hello World from __main__!
pi
+2  A: 

*args and **kwargs mean:

 def on_the_menu(arg, *args, **kwargs):
       print arg
       print args
       print kwargs

  >>> on_the_menu(5, "spam", "eggs", "ham", sausage="and spam", spam="plenty")
  5
  ('spam', 'eggs', 'ham')
  {'sausage': 'and spam', 'spam': 'plenty'}

And args and kwargs are only variable names. Name them as you like. For example sausage or spam. On the other hand, don't. :)

pi