Problem with str()

Question: At line 31, the pyright shows me an error with the ‘+’ operator, which doesn’t support STR elements. How can I resolve this?

Operator “+” not supported for types “Literal[‘(’]” and “str | Unknown | None”

Repl link:

If you run the code, does it work? Some of pyright’s errors are more of suggestions of things to fix than anything.

1 Like

Yes, but I’d like to understand where the error is coming from. But I’ve just modified the code with another method and it seems that pyright no longer displays the suggestion.

Could you share a snippet of your original code so we could see what pyright was mad about?

def exprime(arbre):
  if arbre.filsG is None and arbre.filsD is None:
    return str(arbre.donnee)
  elif arbre.donnee == '+':
    return '(' + exprime(arbre.filsG) + '+' + exprime(arbre.filsD) + ')'
    #            ^^^^^^^^^^^^^^^^^^^^

*text in bold is the suggestion of pyright

Please surround your code with triple backticks (```), to make it easier for us to read :slightly_smiling_face:

Pyright is trying to infer the types of your variables and function. It thinks that there might be an error because the inferred type is not what you intended. You have to help tell pyright what the types are.

Let’s look at the error message. It mentions a literal string and str | Unknown | None, with the second thing meaning it thinks the variable is a str, None, or an Unknown type. Obviously if you try to do "(" + None there will be an error which is what pyright is saying, but you know that it won’t be None.

Make sure your function never returns None implicitly. Annotating the function return type might also help. If there are still errors, you might need to annotate the types of the attributes of arbre in the class. (Note: you can actually chain is comparisons. Also consider using f-strings.)

def exprime(arbre) -> str:
  if arbre.filsG is arbre.filsD is None:
    return str(arbre.donnee)
  elif arbre.donnee == '+':
    return f'({exprime(arbre.filsG)}+{exprime(arbre.filsD)})'
  raise ValueError('bad')

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.