0

Recently I had a problem reading information from a .ini file to a int type variable:

var:int = config['example']['var']

The .ini file is something like this:

.ini file

Using configparser to read the value pass it as '3' instead of 3.

I must add that I know I can convert it to int by using int(var) (that's how I fixed it by the way), but that is not the point of this question.

The variable type is a int and the configparser read the value from the file as a string and successfully changes the variable type to a string, the code worked for multiple days until I had a bug, the interpreter indicates I was trying to compare a string type with an int type, by this point I was so far into the code I wasted 10 minutes pinpointing the source of the bug.

Here's a example code:

class testclass:
    def __init__(self, var:int): #Specifying that var should be a int
        self._storage:int = var #specifiying that _storage should be a int

    @property
    def get(self) -> int: #specifiying that get method should return a int
        return self._storage

#Expected behaviour
correct = 1
test1 = testclass(correct)

#Passing a string when it should be a integer
wrong = '1'
test2 = testclass(wrong)

print('test1 type = ' + str(type(test1.get)))
print('test2 type = ' + str(type(test2.get)))

And it's output:

    test1 type = <class 'int'>
    test2 type = <class 'str'>

As you can see I made sure to specify the type of every single method and variable so I couldn't unknowingly pass the wrong type by mistake (which is exactly what I did), but it did not make any difference, whats is the point of :int and -> int and what should I do the lock arguments/variables/methods etc. to a variable type so I can't shoot myself on the foot in the future?

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    Type hints are not checked are runtime. You need to _statically_ verify them with a type checker, such as mypy. See also [What are type hints in Python 3.5?](https://stackoverflow.com/q/32557920/11082165) – Brian61354270 Jul 05 '22 at 20:57
  • The examples in the post you've mentioned are exactly the problem I had, coming from a statically typed language (C++) I took knowing variable types and not needing to make sure I wasn't passing something wrong for granted. – Fábio Gandini Jul 05 '22 at 21:11

1 Answers1

1

Python doesn't force types. You can pass other types even if you specified a type. However, you can use a Python Linter such as mypy and it will warn you when you pass the wrong type.

Note: The program will run, even if you use mypy, but you will see a warning while writing the code.

Ben
  • 21
  • 4