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:
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?