-
-
Notifications
You must be signed in to change notification settings - Fork 33.1k
Description
Feature or enhancement
Proposal:
Improve error handling for args
in Thread
to prevent confusion with iterable arguments that are not a list
or tuple
Hey! This isn’t a major change, just something I noticed recently while working with threading.Thread
.
If you accidentally pass a string into the args
parameter , it leads to confusing runtime errors that could be caught earlier.
Example
import threading
def greet(name):
print(f"Hello, {name}!")
# Common mistake: passing a string instead of a tuple
t = threading.Thread(target=greet, args="World")
t.start()
Will produce:
TypeError: greet() takes 1 positional argument but 5 were given
But the following code
import threading
def greet(name):
print(f"Hello, {name}!")
# Common mistake: passing a string instead of a tuple
t = threading.Thread(target=greet, args=1)
t.start()
Will produce this error message
TypeError: __main__.greet() argument after * must be an iterable, not int
Suggested Improvement
Add an explicit check in threading.Thread.__init__
to verify that:
args
is aniterable
, and- it's not a string or bytes-like object.
I was thinking something like
if isinstance(args, (str, bytes)) or not hasattr(args, '__iter__'):
raise TypeError(f"'args' must be a non-string iterable like tuple or list, not {type(args).__name__}")
I think this could help improve clarity and catch beginner mistakes while also being backward-compatible with existing valid usage.
Contribution
I’d be happy to submit a pull request for this change, along with a test case. Please let me know if this enhancement would be welcome—or if it makes sense to consider adding similar checks for other Thread constructor parameters.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response