Repository navigation
Conversation
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.
|
I still have 2 open questions about this pull request.
|
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
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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). |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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__', ()) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Why are these changes needed?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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'
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
New tests for generics with custom converters like |
|
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. |
|
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 |
| return list(value) | ||
| if not is_list_like(value): | ||
| raise ValueError | ||
| return self.__nested_conversion(value, explicit_type) |
There was a problem hiding this comment.
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.
|
Converters could probably create converters for their values already in 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 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] |
|
I prototyped converting
In my opinion that error is pretty ok and most likely same approach could be used with generics as well. |
|
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. |
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. |
|
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. |
|
Creating converters in In this situation I believe it's best to go with the simplest code and I believe creating converters in |
|
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. |
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.