Search code examples
pythonpygithub

In PyGitHub, how do you set set_labels?


I am building a GitHub action that,

  1. gets existing issue labels
  2. adds correct priority labels
  3. sets all labels

The relevant part is,

def required_labels(current_labels, required_priority):
    if current_labels is None:
        return [required_priority]
    labels_out = []
    for label in current_labels:
        if label not in possible_priorities:
            labels_out.append(label)
            continue
        if label != required_priority:
            continue
    labels_out.append(required_priority)
    return labels_out

out_labels = required_labels(existing_labels, body_priority_label)
issue.set_labels(out_labels)

The set_labels docs say that it requires

list of github.Label.Label or strings

I, therefore, expected that a list of strings, labels_out, would work, however, set_labels returns

File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/github/Issue.py", line 545, in set_labels
    assert all(
AssertionError: (['enhancement', 'P2'],)

I also tried making a union of this list but saw no change.

set().union(out_labels)

I also tried using the repo label object.

for label in labels_names:
    labels_out.append(repo.get_label(name=label).name)

This returned,

  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/github/Repository.py", line 2631, in get_label
    assert isinstance(name, str), name
AssertionError: ['enhancement', 'P2']

When I provide many strings to set_labels, it works as expected.

    issue.set_labels("Separate", "Strings", "Work", "As", "Expected")

Clearly, one will not know how many labels an issue might have. How should I provide the required labels to set_labels?


Solution

  • The documentation describes the following function signature:

    set_labels(*labels)
    

    The 'star' in front of labels in the function signature indicates a variadic argument which takes zero, one, or more labels.

    So, you can unpack your list before passing it to set_labels, as follows:

    issue.set_labels(*out_labels)
    

    You can read more about arguments and argument unpacking in Sections 4.7.3 and 4.7.4 of the tutorial.