Multiple type annotation type in ** kwargs

I am trying to use Python type annotations with an 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 can contain arguments of several types - float , bool and str .

Now I'm trying to write a type annotation for a function that looks like this:

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

But my PyCharm IDE warns me:

Except for the Integral type, instead, str

and

Can't find get link in bool | str | Float '

Am I doing something wrong?

How to write a type annotation for kwargs if it contains arguments from several types?

+5
source share
1 answer

See this error and this error on the tracker for PyCharm. This is apparently a problem with the PyCharm controller; mypy (another type of check for Python) does not complain when I execute similar code.

It has already been fixed there and is apparently available in build 171.2014.23 . Until then, I assumed that Any would be enough as a temporary workaround to make the controller stop complaining.

+2
source

Source: https://habr.com/ru/post/1268475/


All Articles