Skip to content

Automatic type conversion for generic types - #4434

Closed
JFoederer wants to merge 26 commits into
robotframework:masterfrom
JFoederer:nested-types
Closed

JFoederer wants to merge 26 commits into
robotframework:masterfrom
JFoederer:nested-types

Conversation

@JFoederer

Copy link
Copy Markdown
Contributor

This PR is related to issue #4433. It adds support for converting nested types like List[int] or Dict[str, bool]. It also resolves the defect where type information is lost by retaining the original type information.

Supports types like List[int] or  Dict[MyEnum,bool].

No support yet for TypedDict and Abstract Base Classes.
Prevents nested types from being converted to their origin types and loosing access to the original type information.

Required updating set type converter.
Added more tests and fixed the open ends they exposed.
@JFoederer

Copy link
Copy Markdown
Contributor Author

I still have 2 open questions about this pull request.

  • There are a few failing tests in the LibDoc suite. It was unclear to me if we need to update the tests, because a limitation was resolved, or that these reflect a requirement and the code needs to change.
  • Some of the invalid tests now have a very long error message in them. I would like to shorten them, but didn't succeed (yet)

Type names are used by LibDoc. LibDoc links to type information, but does not have separate entries for all variations of Generic types.

This commit reverts to using the standard type names. Type info during conversion of sub-types is extended to still provide full details for failure analysis when a test case fails due to conversion.
For now, returning None in case of error. Maybe there is something smarter that can be done?

@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.

Great work but changes are still needed. See comments for details and don't hesitate to ask details here or on Slack.

List () error=Value is tuple, not list.
List with params ooops type=list error=Invalid expression.
List with ints ooops type=list error=Invalid expression.
List with ints [1, ${2}, 3.14, -42] type=list error=Argument 'List[integer]' got value '3.14' (float) that cannot be converted to integer: Conversion would lose precision.

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 error message

Argument 'List[integer]' got value '3.14' (float) that cannot be converted to integer

is a bit misleading because the actual argument is the whole list. Not sure what would be better wording nor do I know how easy it would be to change the code toe provide a better message.

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, this is quite a tricky one. Difficult to make a concise message that still has the good info. In an earlier version I had also included the index of the element for which the conversion failed. I removed that because it felt too lengthy. I ended up with this balance where the user is shown the actual failing conversion, but has to go through the list their selves to see where it is.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Perhaps

Argument 'List[integer]' included value '3.14' (float) that cannot be converted to integer

Using "included" instead of "got" would make it more explicit that it was only one part of the argument that caused the problem.

@pekkaklarck pekkaklarck Sep 27, 2022 •

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.

Yeah, it would be better. We already discussed this elsewhere in these comments and agreed on a small enhancement that basically changes the erro to

Item '1' got value ...

where 1 is the index. This is wrapped into another similar error which ought to make the final message pretty good. Anyway, error reporting can certainly be enhanced once the main functionality is in.

syntax (e.g. `List[int]`) works, but no validation is done for container
contents.
syntax (e.g. `List[int]`) works. When using subscripting, validation and
conversion is extended to the container contents (New in Robot Framework 5.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.

This isn't exactly proper English. Should be changed to something

Starting from Robot Framework 5.1, validation and conversion is extended ...

Alternatively, and probably better, the text could be left as-is and a separate note added about this being new in 5.1. The reST syntax for such notes starts with .. note:: and there ought to examples in the same file you can look at. One benefit of these notes is that they can be very easily deleted later when they aren't anymore applicable.

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.

Feel free to update as you feel fit. Keeping the text as-is does not seem appropriate. It explicitly states that no conversion is done.


def __init__(self, type_, custom_converters=None, languages=None):
super().__init__(type_, languages=languages)
self.nested_types = getattr(type_, '__args__', ())

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.

Custom converters should be passed forward.

Could check that __args__ is either empty or contains exactly one argument already here.

return cls(cls.STANDARD, converter.type_name,
STANDARD_TYPE_DOCS[converter.type], converter.value_types)
else:
return 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.

Why are these changes needed?

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.

Due to a defect in the existing code. While testing I ran into a KeyError in what is now line 63. The code assumed that if there is a converter and it has a type, that it must be in STANDARD_TYPE_DOCS. At one point it wasn't.

To be honest, I am not sure anymore if this was only to improve error reporting during work in progress, or that there are still active paths in the running code that reach this point. Anyway, the KeyError was not very helpful, so I kept the improvement regardless.

@pekkaklarck pekkaklarck Sep 22, 2022 •

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.

If it's a recognized converted, Libdoc should have docs for it and return None is thus risky. I agree KeyError isn't good either convenient (that occurred recently after I added pathlib.Path converter and forgot to add docs), but it would be better to use something like raise ValueError(f'No documentation for {type(converter).__name__}.') instead of return None

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.

I would have to reproduce the issue to really remember what was going on. If I recall correctly it had something to do with new composed types being created at runtime from existing types, for which Libdoc didn't find the docs. Returning None had in that case identical behavior as when there isn't any converter (line 57). I think it still showed the name, but no link to the type's details.

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.

In that case it would probably be best to replace return None with some meaningful exception. Most likely it occurs only if there's a bug in our code (all recognized converters should have docs!) and a good exception makes understanding the situation better. If there are in fact legitimate cases where a converter shouldn't have docs, then this code is fine but there should be a unit test validating it.

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.

I was able to reproduce the issue. Using return None does indeed cause Libdoc to finish without exceptions. From the generated output I am able to see that one of the type links is broken. When raising the exception, no clues are given about what is going wrong. With my limited experience using Libdoc I really don't know what is going wrong.

From what I understand it should simply use the docstring from the class that defines the type, right?

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.

I am clearly missing something obvious. This very basic example already fails to show the type link. It also doesn't raise the exception though.

attempt.py

class MyStuff:
    """bla bla"""

class attempt:
    def dummy(self, x: MyStuff):
        pass

It shows Keyword dummy with argument x <MyStuff>, but it does not link to show 'bla bla'

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.

Libdoc doesn't work like this. It shows type info only for types it converts. That means std types like int and custom types that are separately registered.

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.

The real issue here seems to be that I was using the same construct as inside Robot in an external library. So, using @TypeConverter.register instead of ROBOT_LIBRARY_CONVERTERS= or @library(converters=. Functionally it works, but it somehow has a side effect when using Libdoc. On the other hand, I am unable to reach the nested_type info when using the custom converter approach.

@pekkaklarck

Copy link
Copy Markdown
Member

New tests for generics with custom converters like List[UsDate] should probably be added to the custom_converters.robot suite. The CustomConverters.py library used there contains converts that can be used.

@JFoederer

Copy link
Copy Markdown
Contributor Author

Thanks @pekkaklarck, good review! I did what I could within the time I had available now. Not all review comments are processed yet. I hope I can spend some more time on it later this week.

@pekkaklarck

pekkaklarck commented Sep 21, 2022 •

Copy link
Copy Markdown
Member

Don't have time to look at the changes now and probably not before Friday, but a quick comment about the syntax we support. I somewhat strongly believe we should allow only one type with lists and sets and require two types with dicts. With tuples we can allow any number of types, but the tuple used as an argument should then have that amount of values. Python doesn't seem to care so you can use list[int, str, bool] and even dict[int, str, bool], but I believe we should be stricter. We should allow using list[int|str|bool], though, and that usage probably should get its own test.

return list(value)
if not is_list_like(value):
raise ValueError
return self.__nested_conversion(value, explicit_type)

@pekkaklarck pekkaklarck Sep 22, 2022 •

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.

If I remember this logic right, this method isn't called if this converter doesn't handle the value and in that case is_list_like check would be unnecessary. That would allow moving all code from __nested_conversion here. Then _convert would need to be changed to call this method instead of the helper.

@pekkaklarck

Copy link
Copy Markdown
Member

Converters could probably create converters for their values already in __init__ similarly as CombinedConverter initializes self.converters.

With lists and sets it could be something like this:

types = getattr(type_, '__args__', ())
if not types:
    self.item_converter = None
elif len(types) == 1:
    self.item_converter = TypeConverter.converter_for(types[0], custom_converters, languages)
else:
    raise TypeError    # Or some other exception. This would need own tests as well.

Dicts would need to initialize both self.key_converter and self.value_converter. Tuples would need to store all:

types = getattr(type_, '__args__', ())
if not types:
    self.item_converters = None
else:
    self.item_converters = [TypeConverter.converter_for(t, custom_converters, languages) for t in types]

@pekkaklarck

Copy link
Copy Markdown
Member

I prototyped converting TypedDict items (#4477) and had a similar problem as here with properly reporting errors when converting an individual item fails. My solution was adding new kind='Argument' argument to convert() and passing it to _handle_error where f"Argument '{name}' was then changed to f"{kind} '{name}'. After that I just needed to pass kind='Item' to convert() when converting items. The resulting error messages look like this:

ValueError: Argument 'argument' got value '{'x': 'bad'}' that cannot be converted to Example: Item 'x' got value 'bad' that cannot be converted to integer.

In my opinion that error is pretty ok and most likely same approach could be used with generics as well.

@JFoederer

Copy link
Copy Markdown
Contributor Author

That does indeed look ok. Good addition! Maybe be a bit careful in duplicating the dictionary or list. They can get large and draw attention away from the item actually causing the failure. Especially now that those details are also properly included. Not sure if we have all the information available at the right time to make such decision from code. If not, this looks totally fine to me.

@JFoederer

Copy link
Copy Markdown
Contributor Author

Converters could probably create converters for their values already in __init__ similarly as CombinedConverter initializes self.converters.

I was unsure how dynamic the types and converters could be and when in time the constructors are actually called. I put them in the convert method to be on the safe side. But to be honest, without checking the potential performance impact.

@pekkaklarck

Copy link
Copy Markdown
Member

Ok, let's go with the simple error reporting enhancement I proposed above. That's something that can be enhanced in future versions if needed. Right now we need to concentrate on getting the main functionality working well and good enough error messages are, well, good enough. Changes to the actual conversion logic in the future would have backwards compatibility concerns, but enhancing error reporting is totally safe. All this said, it will be interesting to test how this works with nested collections.

@pekkaklarck

pekkaklarck commented Sep 26, 2022 •

Copy link
Copy Markdown
Member

Creating converters in __init__ obviously makes it slower to create the higher level converter which slows down importing libraries. Then again, if the keyword is used multiple times, there's no need to recreate converters so the overall effect may be positive. This is impossible to know without profiling and it could be that the absolutely best approach also depends on the context.

In this situation I believe it's best to go with the simplest code and I believe creating converters in __init__ is simpler than storing type info and creating converters later. It would also be consistent with how unions are handled. This could then be profiled afterwards when we know the feature works correctly. Refactoring is easier when we have tests as our safety net. Refactoring unions would also have the highest priority as they are likely used more often than typed collections.

@pekkaklarck

Copy link
Copy Markdown
Member

Due to there being hurry to get the next release out, @JFoederer and I agreed that I continue with this PR. I checked it out locally, but unfortunately there were some issues with older Python versions, especially Python 3.6, and I couldn't easily figure out what caused them. In the end I started a new branch where I implemented this functionality based on this PR and the discussion we had above. That turned out to work well and in the end it didn't anymore make sense to try updating this PR.

I have now committed my changes to master which makes this PR outdated. The PR was very helpful and I'd like to thank @JFoederer for his excellent work. I hope you can test how the new implementation works to see are there any holes that we'd still need to fill.

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.

4 participants