Skip to content

5373 type hints string - #5554

Merged
pekkaklarck merged 14 commits into
robotframework:masterfrom
silentw0lf:5373_type_hints_string
Dec 1, 2025
Merged

pekkaklarck merged 14 commits into
robotframework:masterfrom
silentw0lf:5373_type_hints_string

Conversation

@silentw0lf

Copy link
Copy Markdown
Contributor

No description provided.

@silentw0lf
silentw0lf force-pushed the 5373_type_hints_string branch from 8ce5dcc to 4533d40 Compare November 20, 2025 15:18
@silentw0lf silentw0lf closed this Nov 20, 2025
@silentw0lf silentw0lf reopened this Nov 20, 2025
@silentw0lf

Copy link
Copy Markdown
Contributor Author

Rebased upstream/master

@pekkaklarck pekkaklarck left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I only looked at the code changes and they mostly looks good.

Keywords that don't currently work properly with strings and bytes should be listed in #5548 that I'll reopen. I can then go through them myself after this PR has been merged. Their initial typing as part of this PR can be either str or str | bytes depending on the context.

Comment thread src/robot/libraries/String.py Outdated
"[ARABIC]": "".join(chr(c) for c in range(0x0600, 0x0700)),
"[POLISH]": ascii_lowercase + ascii_uppercase + "ąćęłńóśźżĄĆĘŁŃÓŚŹŻ",
}
Error = Union[Literal["strict", "ignore", "replace"], str]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure is it a good idea to list some of the possible error handlers separate. Using just str as the type would be simpler.

@silentw0lf silentw0lf Nov 30, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Used just str

Comment thread src/robot/libraries/String.py Outdated
@keyword(types=None)
def convert_to_title_case(self, string, exclude=None):
# TODO(@pekkaklarck): some paramters could be string, some bytes -> risk of incompatibilies
# TODO(@pekkaklarck): there are some tests indicating that it should only work with str/ not bytes (at least in the past) e.g. Should Be Title Case Does Not Work With ASCII Bytes

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current explicit check for bytes is due to the keyword otherwise anyway failing with them. For example, re.split(r"(\s+)", string) fails if string is actually bytes because the pattern is str. It could be fixed by using br"(\s+)" instead with bytes, but there are also other places that needed to be adjusted. If the signature is changed to string: str, then automatic argument conversion will convert bytes to str and the keyword will kind of work. It would return a str instead of bytes, though, which in my opinion would be wrong.

We have several options how to handle this:

  1. Just use str as the type.
  2. Use str | bytes as the type, but explicitly reject bytes like nowadays. It would be a bit odd if the signature would say that bytes are fine but the keyword would fail with them, but at least the behavior would be explicit.
  3. Enhance the keyword so that it actually works with bytes. Looking at the code, it shouldn't be overly complicated as str and bytes APIs are mostly the same. We already did this with various BuiltIn and Collections keywords (Enhanced and explicit bytes support in BuiltIn, String and Collections #5548) so this would be a logic change also in this case.

Considering that options 1. and 2. have some drawbacks, I believe the option 3. is the way to go. This is what I propose we do in practice:

  1. Use typing str | bytes as part of this PR. Preserve the current TypeError when used with bytes.
  2. Re-open Enhanced and explicit bytes support in BuiltIn, String and Collections #5548 with a note that Convert To Title Case needs to be updated as well. If there are other similar keywords that don't actually work with bytes in String, they can be mentioned in that issue as well.
  3. Merge this PR when it's otherwise ready.
  4. Enhance Convert To Title Case, and possible other keywords, separately to get Enhanced and explicit bytes support in BuiltIn, String and Collections #5548 closed again. I can take care of this.

@silentw0lf silentw0lf Nov 30, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Used typing str | bytes as part of this PR. Preserve the current TypeError
  • left a note referencing this comment in 5548

Comment thread src/robot/libraries/String.py Outdated
return bytes.decode(encoding, errors)

def format_string(self, template, /, *positional, **named):
# TODO(@pekkaklarck): some paramters could be string, some bytes -> risk of incompatibilies

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is similar to Convert To Title Case where I think enhancing the keyword so that it actually works with bytes would make sense. In this case that would be harder, though, because there's no bytes.format method. I guess we could to something like this to support bytes, though:

if isinstance(template, bytes):
    template = template.decode('latin-1')
    return_bytes = True
else:
    return_bytes = False
# current implementation
return result if not return_bytes else result.decode('latin-1')

I'm not sure is this really worth the effort, but the alternatives have the same problems as with Convert To Title Case. In this case I believe we should do this:

  1. Use just str as the typing initially.
  2. Mention this in Enhanced and explicit bytes support in BuiltIn, String and Collections #5548 and decide later should bytes support be added or not.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • use just str
  • left a note referencing this comment in 5548

Comment thread src/robot/libraries/String.py Outdated
return count

def split_to_lines(self, string, start=0, end=None):
# does not work with bytes: ${{b'hello\nworld'}} -> Length of '["b'hello\\nworld'"]' should be 2 but is 1.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You seem to have str as the typing but it should be str | bytes.

@silentw0lf silentw0lf Nov 30, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I left a comment there (which I now removed in new commits):

Testing showed:

does not work with bytes  (when using `str | bytes`): ${{b'hello\nworld'}} -> Length of '["b'hello\\nworld'"]' should be 2 but is 1.

This seems to be broken.
Is also mentioned in #5548.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left a note referencing this comment in 5548

Comment thread src/robot/libraries/String.py Outdated
self,
string: str,
start: "int | str | None" = 0,
end: "int | str | None" = None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is one of the keywords that are affected by #5558. Please use Literal[''] instead of str with start and end.

@silentw0lf silentw0lf Nov 30, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the correct link? #5558 is just a link to "Add annotations to String", also there you reference 5558?

Could you help me out? I can not see the explanation for Literal['']

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: I think I understand the problem and fixed it for now.


def fetch_from_right(self, string, marker):
# TODO(@pekkaklarck): some paramters could be string, some bytes -> risk of incompatibilies
def fetch_from_right(self, string: str, marker: str) -> str:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be mentioned in #5548.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done. (listed all)

Comment thread src/robot/libraries/String.py Outdated

@keyword(types=None)
def strip_string(self, string, mode="both", characters=None):
# TODO(@pekkaklarck): some paramters could be string, some bytes -> risk of incompatibilies

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be mentioned in #5548.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done. (listed all)

Comment thread src/robot/libraries/String.py Outdated

@keyword(types=None)
def should_be_title_case(self, string, msg=None, exclude=None):
# TODO(@pekkaklarck): some paramters could be string, some bytes -> risk of incompatibilies

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be mentioned in #5548.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done. (listed all)

Comment thread src/robot/libraries/String.py Outdated
Error = Union[Literal["strict", "ignore", "replace"], str]
Flags = Union[
Literal["IGNORECASE", "MULTILINE", "VERBOSE", "IGNORECASE | VERBOSE"], str, None
]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think listing these explicitly makes sense. We cannot anyway enumerate all possible combinations.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.

Comment thread src/robot/libraries/String.py Outdated
]
Markers = Union[
Literal["[LOWER]", "[UPPER]", "[LETTERS]", "[NUMBERS]", "[ARABIC]", "[POLISH]"], str
]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly as above, I don't think listing these explicitly is a good idea. These markers can also be used like [NUMBERS]abcdef which doesn't match any of the literal values. Using str allows that, but I believe all this still makes the signature unnecessarily complicated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.

@pekkaklarck

Copy link
Copy Markdown
Member

At least some of the failures on CI are due to the use of parameterized types like list[int] without quotes. Quoting like "list[int]" is needed because we still support Python 3.8.

@silentw0lf

Copy link
Copy Markdown
Contributor Author

I only looked at the code changes and they mostly looks good.

Keywords that don't currently work properly with strings and bytes should be listed in #5548 that I'll reopen. I can then go through them myself after this PR has been merged. Their initial typing as part of this PR can be either str or str | bytes depending on the context.

done.

@silentw0lf

silentw0lf commented Nov 30, 2025 •

Copy link
Copy Markdown
Contributor Author

@pekkaklarck I took time to answer your review notes and finished most of them.
for the autotmatic tests: I have no access to the details of a test fail after 20 s

image

How is it possible to see the errors?

Update:
In the artifacts I could see this only this error multiple times:

FAIL: String.Convert To.Convert To Title Case with excludes
Status of 'Convert To Title Case with excludes' should have been PASS but it was FAIL.

Error message:
Several failures occurred:
1) error: unterminated character set at position 0
2) error: unterminated character set at position 0

I tried to reproduce this error and figured out that Iterable[str] is causing this problem for python3.8, while i figures out that list[str] fixes this error

e.g.

    def convert_to_title_case(
        self,
        string: "str | bytes",
        exclude: "Iterable[str] | str | None" = None,
    ) -> str:

Tests are passed when using exclude: "list[str] | str | None" = None

What should we do here? I remember , you hat the idea to use Iterable[str]
Any thaugts?

@pekkaklarck

Copy link
Copy Markdown
Member

I'd be surprised if list[str] would cause these failures. They look more like issues with tests themselves. Did you run tests locally? Do they pass?

@silentw0lf

silentw0lf commented Nov 30, 2025 •

Copy link
Copy Markdown
Contributor Author

I'd be surprised if list[str] would cause these failures. They look more like issues with tests themselves. Did you run tests locally? Do they pass?

I made a mistake, writing it down.

Local Tests with python3.8 (focus on parameter exclude: "Iterable[str] | str | None" = None,

fail with exclude: "Iterable[str] ...." (error: unterminated character set at position 0)
pass with exclude: "list[str] ...."

@pekkaklarck

Copy link
Copy Markdown
Member

Do all tests pass for you locally with Python 3.8? I can try that myself as well. Have you pushed all changes?

@pekkaklarck

Copy link
Copy Markdown
Member

I tested this locally and can confirm that four tests fail with Python 3.8 and 3.9 when using typing "Iterable[str] | str | None", but not when using "list[str] | str | None". I believe the reason is this:

  1. Python 3.8 and 3.9 don't support the x | y typing syntax (that's why the type is in quotes to begin with).
  2. Robot initially gets types with typing.get_type_hints(). It handles stringified types so that "x | y" syntax is evaluated, but because Python 3.8 and 3.9 don't support the x | y syntax, evaluation fails and typing.get_type_hints() raises an exception.
  3. As a backup Robot parses the stringifies type itself using its own type hint parser. The parser apparently doesn't recognize Iterable and thus the typing is the same as Unknown | str | None. This only happens with Python 3.8 and 3.9, the newer see the typing correctly.
  4. None of the types in Unknown | str | None match a list of strings and thus lists are converted. The first valid type is str, so the a list like ['a', 'an', 'the', 'to', 'is'] that's used in one of the failing tests is converted to a string.
  5. The resulting string ['a', 'an', 'the', 'to', 'is'] is then split to excluded words from ,. The list of excludes will become ["['a'", " 'an'", " 'the'", " 'to'", " 'is']"].
  6. These excludes support regexps, so they are compiled like exclude = [re.compile(e) for e in exclude].
  7. The first item in the exclude list is string ['a'. [ is a special character in regexp and compiling this pattern fails:
    >>> re.compile("['a'")
    Traceback (most recent call last):
      ...
    re.error: unterminated character set at position 0

@pekkaklarck

pekkaklarck commented Nov 30, 2025 •

Copy link
Copy Markdown
Member

The above explains why tests fail. There are three ways we can make them pass:

  1. Enhance the stringified type parser so that it recognizes Iterable.
  2. Change the typing to Union[Iterable[str], str, None] instead.
  3. Use "list[str] | str | None".

I believe the last option is the best one. I don't remember what I have earlier said about using Iterable, but at least now that I think about this, I don't see benefits with accepting iterables instead of lists. Automatic argument conversion anyway converts other sequences like tuples to lists and I see no reason to use any non-sequence iterables. Another benefit of list[str] over Iterable[str] is that users ought to be familiar with the term "list", but they may not understand "iterable".

@pekkaklarck pekkaklarck left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very good. Only very minor changes needed. I can do them myself as well if you don't have time.

# @{result} = Split To Lines ${BYTES TEXT IN COLUMNS}
# Length Should Be ${result} 2
# Should be equal ${result}[0] ${BYTES FIRST LINE}
# Should be equal ${result}[1] ${BYTES SECOND LINE}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Splitting bytes to lines should work. Is the typing of the keyword correct?

@pekkaklarck

Copy link
Copy Markdown
Member

When reviewing this PR, I noticed that our str conversion doesn't handle bytes too well at the moment. I submitted #5567 about this and have already implemented it. This may affect String library tests so merging master is a good idea.

It could now be a good idea to add tests for Encode String To Bytes with bytes values. That can be done as part of #5548 as well, though.

@silentw0lf

Copy link
Copy Markdown
Contributor Author

Looks very good. Only very minor changes needed. I can do them myself as well if you don't have time.

Yes you can do the minor changes. I would at earliest have time tommorow evening.

@pekkaklarck

Copy link
Copy Markdown
Member

This is such a good shape that I'll fix the issues myself and merge this. I can then continue with other issues that are related to String.

@pekkaklarck
pekkaklarck merged commit fcb0f80 into robotframework:master Dec 1, 2025
@pekkaklarck

Copy link
Copy Markdown
Member

I changed Iterable to list and all tests passed. I merged the PR and will look at possible other changes as part of #5548.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants