Wie behebe ich AttributeError bei der Verwendung von Multiprocessing mit benutzerdefinierten Funktionen?

Barbara Streisand
Freigeben: 2024-10-17 19:45:02
Original
254 Leute haben es durchsucht

How to Resolve AttributeError When Using Multiprocessing with Custom Functions?

Multiprocessing Issue: Resolving the AttributeError

When attempting to implement multiprocessing in code using the example provided in the official documentation, some users may encounter the following error:

AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>
Nach dem Login kopieren

This error stems from a design feature specific to multiprocessing.Pool, where it may encounter difficulties working with functions defined within the main Python script.

Solution:

To resolve this issue, it is necessary to separate the function definition into a separate file and import the module containing the function.

  1. Create a new file, e.g., defs.py, and define the function in that file:
<code class="python"># defs.py
def f(x):
    return x*x</code>
Nach dem Login kopieren
  1. In the main script, import the module containing the function:
<code class="python"># run.py
from multiprocessing import Pool
import defs

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

Note:

If you had utilized a standard built-in function, such as print, instead of a user-defined function, the original example should have functioned properly. This indicates that the error arises from the design of multiprocessing.Pool in handling custom functions defined within the main script.

Das obige ist der detaillierte Inhalt vonWie behebe ich AttributeError bei der Verwendung von Multiprocessing mit benutzerdefinierten Funktionen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!