Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do classes in the Python threading module expose factory functions instead of constructors?

Tags:

python

In the threading module, names like RLock, Semaphore and Event are all factory functions, while the name of implementation classes are prefixed by underscores.

The factory functions just pass all arguments they received to the underlying constructors.

So what's the benefit of doing this?

like image 343
satoru Avatar asked Jul 25 '13 09:07

satoru


People also ask

How does Python threading work?

Multithreading (sometimes simply "threading") is when a program creates multiple threads with execution cycling among them, so one longer-running task doesn't block all the others. This works well for tasks that can be broken down into smaller subtasks, which can then each be given to a thread to be completed.

What is threading module in Python?

The thread Module. This method starts a new thread and return its identifier. The thread executes the function "function" (function is a reference to a function) with the argument list args (which must be a list or a tuple). The optional kwargs argument specifies a dictionary of keyword arguments.

Does Python use native threads?

Sometimes, we may need to create additional threads within our Python process to execute tasks concurrently. Python provides real native (system-level) threads via the threading. Thread class.

Are Python threads OS threads?

Python threads are implemented using OS threads in all implementations I know (C Python, PyPy and Jython). For each Python thread, there is an underlying OS thread.


2 Answers

The thread-sig archives seem to have disappeared from the Internet (*), but I'm pretty sure it's prevent you from subclassing things that aren't designed to be subclassed (you really don't want to break synchronization primitives by accident), and the module is old enough that you couldn't do that with new-style class trickery when it was added.

Also note that e.g. RLock has multiple implementation classes.

*) Well, I found some remnants on an FTP server in Greece, but that didn't have the original spec.

like image 197
Fredrik Avatar answered Oct 27 '22 02:10

Fredrik


There is no real advantage.

Guido added the module 1998; the first revision already includes those factory functions. Perhaps he had plans for those factory functions, perhaps he was looking at the Java implementation and copied over some idioms, perhaps he wanted to make things pluggable with a C re-implementation in the back of his head.

We can only guess, or ask Guido directly.

like image 37
Martijn Pieters Avatar answered Oct 27 '22 04:10

Martijn Pieters