You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Automatic argument conversion based on Python 3 function annotations #2890
If a library is implemented using Java, we automatically convert arguments to correct types based on the types in the keyword signature. Similar support would be very handy also with Python based libraries, but Python 2 doesn't have a built-in way to specify type information.
Python 3 supports function annotations that can be used for various purposes, for example, to provide type hints. We could use annotations to get type information and convert arguments based on that. In practice that would mean that keyword like
defexample(argument: int):
# ...
would get the argument as an integer when used like Example 42 in the test data. This would avoid the need to add argument = int(argument) to the keyword or using Example ${42} in the data.
A problem with Python 3 only solution is that those still using Python 2 don't benefit from it, but this kind of very useful feature would also give a good reason to migrate. Python 2 end-of-life is less than 1.5 years from this day, so spending extra effort to support it doesn't feel beneficial either. A bigger problem is that function annotations are not at all compatible with Python 2, so libraries using them will be incompatible with Python 2 as well. This means Robot's own standard libraries cannot start using this functionality.
Once the support for argument conversion has been added to Python based static libraries, we need to think how to add it to the dynamic library API and to the remote library API. The former has already requested by #2068.
I'd really like to see this already in RF 3.1 and add it to it in high priority. May still be descoped if implementation turns out to be complicated.
UPDATE: We are adding type conversion also based on argument default values (#2932) and explicit information passed via the @keyword decorator (#2947). Also the support for dynamic API (#2068) is under development.
One thing to consider is that do we want to handle list and dicts somehow specially. If we implement #2699, we need a utility to parse strings to lists/dicts, and using the same utility if someone uses list/dict as the argument type sounds like a good idea. In practice that would mean that keyword like
defexample(arg: dict):
# ...
would get a dictionary as an argument, not a string looking like a dictionary, when used like
Another thing to consider is how to handle non-string values when a type is specified. Should we validate that the argument is of correct type? If not, should we convert the argument or make it an error?
I think that if we try to convert an argument and it fails, we should make it an error similarly if there are other problems with arguments. I think this is how we handle conversion with Java libraries where this functionality already exists. It's a good point that is backwards incompatible, but I doubt such conflict is common. I actually doubt there are many libraries that use annotations in the first place because they couldn't be used at all until RF 3.0.3 (#2627).
The bigger questions is, what arguments should we try to convert. For example, if we have a keyword
defkw(arg: int):
pass
and it is passed a string, we naturally convert it. But what should we do if it is given a float like 1.5? Should we pass it as-is, convert it to int, or make it an error? I think it would be best to convert also in this case. The user has clearly declared that the argument should be an int, and we should guarantee that.
Regarding the list / dict typing: I've dealt with this before using the List and Dict from the typing module and while you have to use an internal to get the types inside of lists / dicts, it proved to be a workable solution for the project I was working on at the time. I've included a runnable snippet below, perhaps this might offer some inspiration.
p.s. Using that internal actually breaks somewhere between Python 3.3 and 3.5.2, as it moved from __parameters__ to __args__, afaik this module still does not expose these properly - but perhaps I'm just not seeing the proper solution here.
list_arg is a list of (<class 'int'>,)
dict_arg is a dict of (<class 'str'>, <class 'int'>)
int_arg is a <class 'int'>
default_arg defaults to <class 'str'>
Thanks @jeroenroosen, that's very interesting! If we want to do validation for list/dict items we need to do something like this, but at least in the beginning just making sure keywords accepting lists/dicts get correct types might be enough. I've just got named-only argument support finalized and plan to look at this topic next.
Just realized we could do type conversion also based on argument default values. For example, if we have a keyword with a signature def example(good=False), we can see that good is a Boolean and could do type conversion based on that. This would be very handy and work also with Python 2 code, but could also cause backwards compatibility problems. It would also mean we needed to be more careful when designing the rules for conversion.
How to handle None is an important question in general. I think that regardless what type is specified, we need to pass actual Python None object as-is and also convert string None to a None object.
How to handle numbers is another important question. I guess we could argue that if a keyword is defined like spam(eggs: int) and called with a float, converting the float to an integer makes sense. On the other hand, if a keyword is defined just like spam(eggs=0), converting 0.5 to 0 doesn't sound good and would also be badly backwards incompatible. I'm starting to think we shouldn't convert between numerical types.
Perhaps it would be safest to do conversion only if the passed argument is a string. The main motivation of this enhancement is to automatically allow using Spam 42 and not Spam ${42} in the test data. Doing conversion if you explicitly use Spam ${42.5} would probably cause more problems than have benefits. Not doing conversion if the argument is not a string would also avoid problems in cases like def maps(eggs: dict) when used like Maps ${my custom mapping}.
How should this situation be handled? In the former case it feels pretty logical to consider this an error, but with the latter case that would be a backwards incompatible change. Possible solutions I see:
Don't do any automatic conversion based on default values. I don't like that.
Different conversion logic based on is type information got from explicit annotations or from default values. Possible but adds extra code and makes logic somewhat inconsistent.
If type is int, first try to convert the string to an int and then try float if it fails. In other words, both the above examples would work. It can be considered a problem that if there is an explicit annotation arg: int we still pass a float. Personally I don't think that's a big problem because a) Python in general doesn't enforce types, b) I don't see any real problems caused by this, and c) it's easy to add assert isisntance(arg, int) into the keyword if an int is absolutely mandatory.
Unless the old behavior of the typing module is restored or there's some other clean way to recognize these types, it might be easiest just to explicitly document we don't support it.
PEP-563 added from __future__ import annotations in Python 3.7 that changes how annotations are evaluated. We need to take that into account but that can be done after alpha 2. Reopening this to make sure we don't forget about it.
Activity
pekkaklarck commentedon Jul 4, 2018
One thing to consider is that do we want to handle list and dicts somehow specially. If we implement #2699, we need a utility to parse strings to lists/dicts, and using the same utility if someone uses list/dict as the argument type sounds like a good idea. In practice that would mean that keyword like
would get a dictionary as an argument, not a string looking like a dictionary, when used like
pekkaklarck commentedon Jul 4, 2018
Another thing to consider is how to handle non-string values when a type is specified. Should we validate that the argument is of correct type? If not, should we convert the argument or make it an error?
basic-settings commentedon Jul 6, 2018
I think for this case it would make sense to:
Warning: could not convert x to y..) and send the data as string (as before)I would go with option 1 for the sake of backwards compatibility with already available tests.
pekkaklarck commentedon Jul 6, 2018
I think that if we try to convert an argument and it fails, we should make it an error similarly if there are other problems with arguments. I think this is how we handle conversion with Java libraries where this functionality already exists. It's a good point that is backwards incompatible, but I doubt such conflict is common. I actually doubt there are many libraries that use annotations in the first place because they couldn't be used at all until RF 3.0.3 (#2627).
The bigger questions is, what arguments should we try to convert. For example, if we have a keyword
and it is passed a string, we naturally convert it. But what should we do if it is given a float like 1.5? Should we pass it as-is, convert it to int, or make it an error? I think it would be best to convert also in this case. The user has clearly declared that the argument should be an int, and we should guarantee that.
basic-settings commentedon Jul 9, 2018
Convert in any case, as the signature expects a specific format.
jeroenroosen commentedon Jul 18, 2018
Regarding the list / dict typing: I've dealt with this before using the List and Dict from the typing module and while you have to use an internal to get the types inside of lists / dicts, it proved to be a workable solution for the project I was working on at the time. I've included a runnable snippet below, perhaps this might offer some inspiration.
p.s. Using that internal actually breaks somewhere between Python 3.3 and 3.5.2, as it moved from
__parameters__to__args__, afaik this module still does not expose these properly - but perhaps I'm just not seeing the proper solution here.Output:
pekkaklarck commentedon Jul 18, 2018
Thanks @jeroenroosen, that's very interesting! If we want to do validation for list/dict items we need to do something like this, but at least in the beginning just making sure keywords accepting lists/dicts get correct types might be enough. I've just got named-only argument support finalized and plan to look at this topic next.
pekkaklarck commentedon Jul 19, 2018
Just realized we could do type conversion also based on argument default values. For example, if we have a keyword with a signature
def example(good=False), we can see thatgoodis a Boolean and could do type conversion based on that. This would be very handy and work also with Python 2 code, but could also cause backwards compatibility problems. It would also mean we needed to be more careful when designing the rules for conversion.basic-settings commentedon Jul 19, 2018
This is but problematic with code that defaults to
None, which is allowed in Python.Take this for example:
will output:
In cases like these I would expect types to not change if the method is called without arguments, but change if called with something like a float.
jeroenroosen commentedon Jul 19, 2018
I'm not too familiar with RF internals to make a proper judgement of this, but wouldn't this be quite inconsistent?
arg=Nonecomes to mind.Edit: @basic-settings beat me to it :)
pekkaklarck commentedon Jul 19, 2018
How to handle
Noneis an important question in general. I think that regardless what type is specified, we need to pass actual PythonNoneobject as-is and also convert stringNoneto aNoneobject.How to handle numbers is another important question. I guess we could argue that if a keyword is defined like
spam(eggs: int)and called with a float, converting the float to an integer makes sense. On the other hand, if a keyword is defined just likespam(eggs=0), converting0.5to0doesn't sound good and would also be badly backwards incompatible. I'm starting to think we shouldn't convert between numerical types.Perhaps it would be safest to do conversion only if the passed argument is a string. The main motivation of this enhancement is to automatically allow using
Spam 42and notSpam ${42}in the test data. Doing conversion if you explicitly useSpam ${42.5}would probably cause more problems than have benefits. Not doing conversion if the argument is not a string would also avoid problems in cases likedef maps(eggs: dict)when used likeMaps ${my custom mapping}.pekkaklarck commentedon Jul 19, 2018
Another design decision related to handling numbers. Let's assume we have keywords
and they are used like
How should this situation be handled? In the former case it feels pretty logical to consider this an error, but with the latter case that would be a backwards incompatible change. Possible solutions I see:
Don't do any automatic conversion based on default values. I don't like that.
Different conversion logic based on is type information got from explicit annotations or from default values. Possible but adds extra code and makes logic somewhat inconsistent.
If type is
int, first try to convert the string to anintand then tryfloatif it fails. In other words, both the above examples would work. It can be considered a problem that if there is an explicit annotationarg: intwe still pass a float. Personally I don't think that's a big problem because a) Python in general doesn't enforce types, b) I don't see any real problems caused by this, and c) it's easy to addassert isisntance(arg, int)into the keyword if anintis absolutely mandatory.What do others think about this?
54 remaining items
Enum related type conversion fixes/enhancements.
pekkaklarck commentedon Sep 3, 2018
Thought this issue is ready, except for writing documentation and possibly slightly enhanced error reporting, but then executed tests on Python 3.7 and noticed that the
typingmodule has changed so that the current implementation doesn't recognize the types it exposes.: https://bugs.python.org/issue34568Unless the old behavior of the
typingmodule is restored or there's some other clean way to recognize these types, it might be easiest just to explicitly document we don't support it.Type conversion: Workaround typing module changes in Python 3.7
Type conversion: Enhanced error reporting. #2890 #2947
Smallish type conversion changes #2890 #2947
pekkaklarck commentedon Sep 26, 2018
PEP-563 added
from __future__ import annotationsin Python 3.7 that changes how annotations are evaluated. We need to take that into account but that can be done after alpha 2. Reopening this to make sure we don't forget about it.Fix type conversion if annotated argument has None as default.
Test and doc that type conversion works with embedded args.
Type conversion: Allow specifying type as string