Skip to content

Automatic argument conversion based on Python 3 function annotations #2890

Closed

Description

@pekkaklarck

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

def example(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.

Activity

  1. added this to the v3.1 milestone on Jul 4, 2018
  2. pekkaklarck commented on Jul 4, 2018

    @pekkaklarck
    MemberAuthor

    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

    def example(arg: dict):
        # ...

    would get a dictionary as an argument, not a string looking like a dictionary, when used like

    Example    {'a': 1, 'b': 2}
    
  3. pekkaklarck commented on Jul 4, 2018

    @pekkaklarck
    MemberAuthor

    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?

  4. basic-settings commented on Jul 6, 2018

    @basic-settings

    I think for this case it would make sense to:

    • try to convert to the type
    • if conversion fails, there could be two options:
    1. Raise a warning (Warning: could not convert x to y..) and send the data as string (as before)
    2. Raise an error and fail the test

    I would go with option 1 for the sake of backwards compatibility with already available tests.

  5. pekkaklarck commented on Jul 6, 2018

    @pekkaklarck
    MemberAuthor

    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

    def kw(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.

  6. basic-settings commented on Jul 9, 2018

    @basic-settings

    Convert in any case, as the signature expects a specific format.

  7. jeroenroosen commented on Jul 18, 2018

    @jeroenroosen
    Contributor

    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.

    import inspect
    from typing import List, Dict
    
    
    def f(list_arg: List[int], dict_arg: Dict[str, int], int_arg: int, default_arg):
        pass
    
    signature = inspect.signature(f)
    
    for name in list(signature.parameters.keys()):
        type_ = signature.parameters[name].annotation
        if type_ is inspect._empty:
            print(name, "defaults to", str)
        elif issubclass(type_, list):
            print(name, "is a list of", getattr(type_, "__args__", str))
        elif issubclass(type_, dict):
            print(name, "is a dict of", getattr(type_, "__args__", (str, str)))
        else:
            print(name, "is a", type_)

    Output:

    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'>
    
  8. pekkaklarck commented on Jul 18, 2018

    @pekkaklarck
    MemberAuthor

    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.

  9. pekkaklarck commented on Jul 19, 2018

    @pekkaklarck
    MemberAuthor

    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.

  10. basic-settings commented on Jul 19, 2018

    @basic-settings

    This is but problematic with code that defaults to None, which is allowed in Python.

    Take this for example:

    def spam(eggs: int=None):
        print(eggs, type(eggs))
        
    spam()
    spam(3)
    

    will output:

    None <class 'NoneType'>
    3 <class 'int'>
    

    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.

  11. jeroenroosen commented on Jul 19, 2018

    @jeroenroosen
    Contributor

    I'm not too familiar with RF internals to make a proper judgement of this, but wouldn't this be quite inconsistent? arg=None comes to mind.

    Edit: @basic-settings beat me to it :)

  12. pekkaklarck commented on Jul 19, 2018

    @pekkaklarck
    MemberAuthor

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

  13. pekkaklarck commented on Jul 19, 2018

    @pekkaklarck
    MemberAuthor

    Another design decision related to handling numbers. Let's assume we have keywords

    def int_type(arg: int):
        # ...
    
    def int_default(arg=0):
        arg = float(arg)
        # ...

    and they are used like

    Int type       1.5
    Int default    1.5
    

    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:

    1. Don't do any automatic conversion based on default values. I don't like that.

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

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

    What do others think about this?

  14. 54 remaining items

  15. pekkaklarck commented on Sep 3, 2018

    @pekkaklarck
    MemberAuthor

    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 typing module has changed so that the current implementation doesn't recognize the types it exposes.: https://bugs.python.org/issue34568

    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.

  16. pekkaklarck commented on Sep 26, 2018

    @pekkaklarck
    MemberAuthor

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions