1

So, i using mypy to learn how to code in python using type check from the beginning. I'm using this code to train:

def stars(*args: int, **kwargs: float) -> None:
    
    for arg in args:
        print(arg)
    for key, value in kwargs:
        print(key, value)

stars(1.3,1.3)

I'm getting this typeerror:

learning_mypy.py:6: error: Unpacking a string is disallowed
learning_mypy.py:7: error: Cannot determine type of 'key'
learning_mypy.py:7: error: Cannot determine type of 'value'
learning_mypy.py:9: error: Argument 1 to "stars" has incompatible type "float"; expected "int"
learning_mypy.py:9: error: Argument 2 to "stars" has incompatible type "float"; expected "int"
Found 5 errors in 1 file (checked 1 source file)  

So my questions are:

  • Why error mypy.py:6 is happening?
  • How do i define the type the value for key and value?
  • Why error mypy.py:9 is hapening?
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46

1 Answers1

2

If you do the below changes, mypy does not show anything.

def stars(*args: float, **kwargs: float) -> None:
    
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

stars(1.3,1.3)
  • Why error mypy.py:6 is happening?

    for key, value in kwargs: for this line, you should see the kwargs as a Python dictionary. If you iterate the kwargs in the for loop, it will iterate ONLY the key of the dictionary. Look at the below code.

    d = {'1': 'one', '2': 'two', '3': 'three'}
    for key in d:
        print(key)
    

    The output is:

    1
    2
    3
    

    If you want to print the values as well, you can use dict.items method.

    d = {'1': 'one', '2': 'two', '3': 'three'}
    for key, value in d.items():
        print(key, value)
    

    The output is:

    1 one
    2 two
    3 three
    

    or, you can access the value of the key over the dictionary.

    for key in d:
        print(key, d[key])
    

    In line 6, since ONLY the keys are generated and also keys are a str; you are trying to unpack a string. Consider the below code:

    var1, var2 = "test_variable"
    

    This is exactly what your second for loop does.

  • How do i define the type the value for key and value?

    You cannot define the type of the keys for kwargs but you can define the type of the values. (You already done it: kwargs: float)

  • Why error mypy.py:9 is hapening?

    You defined the *args as int. But you passed float. If you change *args: float, this error will be gone.

ErdoganOnal
  • 800
  • 6
  • 13
  • Great answer @ErdogonOnal! I became my journey to learn python about a month ago and a few days ago i have discovered static typing and type checking. Do you think is a good practice to develop from the beginning or start to use as i am more mature in the knowledge of the langue? – Gabriel Padilha Jun 08 '21 at 22:04