storen
storen

Reputation: 1035

How to interprete python function's parameter in its documents?

For example:

class multiprocessing.pool 's function:

apply_async(func[, args[, kwds[, callback]]])

What are the square brackets mean? In the following code, when using function apply_async, why args=(i,) if args=i, then it cann't work.

from __future__ import print_function
from  multiprocessing import Pool
import os
import random
import time

def appear(name):
    print("{0} running {1} task".format(name, os.getpid()))
    start=time.time()
    time.sleep(random.random() * 3)
    end=time.time()
    print("{0} running for {1} seconds".format(name, (end - start)))

def f(a):
    return a * a

p=Pool()

for i in range(5):
    p.apply_async(appear, args=(i,))

print("waiting for all subprocess done..")
p.close()
p.join()
print("all done")

The Python's module functions have many parameters. It's really hard to understand them.

Upvotes: 0

Views: 33

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121614

The square brackets just mean the arguments are optional. You can call the method without specifying the arguments in brackets.

The documentation points to the apply() function; you want to read the documentation for that function too. It explains what the different arguments mean; like args for instance:

the args argument must be a sequence.

args=i would not be a sequence, while args=(i,) would be; (i,) is a one-element tuple, and a tuple is a sequence.

Upvotes: 3

Related Questions