Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type annotation with multiple types in **kwargs

I'm trying out using Python's type annotations with abstract class. My __init__ function looks like this:

from abc import ABCMeta

class SomeClass(object, metaclass=ABCMeta):
    def __init__(self, *args, **kwargs):
        print("Initiating %s object.", self.__class__.__name__)

        self.username = kwargs['data']
        assert isinstance(self.username, str)

        is_premioum = kwargs.get('premioum', False)

        self.money_investmant = kwargs.get('investmant')
        if isinstance(self.money_investmant, str):
            self.money_investmant = float(self.money_investmant)

As you can see, kwargs could contain arguments from a several number of types- float, bool and str.

Now, I am trying to write the type annotation for the function, that looks like this:

def __init__(self, *args, **kwargs: Union[bool, str, float]) -> None:

But my PyCharm IDE alerts me:

Except type 'Integral', got 'str' instead

And:

Cannot find referance 'get' in bool | str | float'

Am I doing something wrong?

How should I write the type annotation for kwargs if it contains arguments from multiple types?

like image 732
Yuval Pruss Avatar asked Jun 02 '17 13:06

Yuval Pruss


People also ask

What datatype are the * Kwargs stored?

*args collects the positional arguments that are not explicitly defined and store them in a tuple. **kwargs does the same as *args but for keyword arguments. They are stored in a dictionary because keyword arguments are stored as name-value pairs.

What is the type of * args in Python?

*args allows us to pass a variable number of non-keyword arguments to a Python function. In the function, we should use an asterisk ( * ) before the parameter name to pass a variable number of arguments.

Are type annotations Pythonic?

Type Annotations or type hints in Python (or any other language) are used to indicate the data types of variables and inputs/outputs of functions and methods.

How do I add type hints?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.


1 Answers

See this bug and this bug on the issue tracker for PyCharm. This is apparently an issue with PyCharm's checker; mypy (another type checker for Python) does not complain when I execute similar code.

There's already a fix for this and, it's apparently available in build 171.2014.23. Until then, I'd suppose Any would suffice as a temporary workaround to get the checker to stop complaining.

like image 105
Dimitris Fasarakis Hilliard Avatar answered Oct 04 '22 00:10

Dimitris Fasarakis Hilliard