Skip to content

Improve error handling for args in Thread to prevent confusion with iterable arguments that are not a list or tuple (such as a string) #131540

@MattiHayes

Description

@MattiHayes

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:

  1. args is an iterable, and
  2. 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

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions