Home  >  Article  >  Backend Development  >  Why Does Multiprocessing Example Result in \'AttributeError\' with Built-in Functions?

Why Does Multiprocessing Example Result in \'AttributeError\' with Built-in Functions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 19:48:30435browse

Why Does Multiprocessing Example Result in 'AttributeError' with Built-in Functions?

Why Multiprocessing Example Gives AttributeError

In an attempt to delve into multiprocessing, an individual encountered an AttributeError while adapting the introductory example from the documentation:

<code class="python">from multiprocessing import Pool
def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))</code>

The error: "AttributeError: can't get attribute 'f' on " perplexed the user.

To resolve this issue, it's important to understand that multiprocessing.Pool has a peculiar design feature. As noted in Python issue #25053, Pool sometimes falters when working with objects not defined in imported modules. As a workaround, you can define your function in a separate file and import the module.

Here's an example:

defs.py:

<code class="python">def f(x):
    return x*x</code>

run.py:

<code class="python">from multiprocessing import Pool
import defs

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(defs.f, [1, 2, 3]))</code>

This modification should resolve the AttributeError. However, it's worth noting that the given example in the documentation might not be the most suitable for beginners due to this potential issue.

The above is the detailed content of Why Does Multiprocessing Example Result in \'AttributeError\' with Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn