Reputation: 43
I have a function that checks if the size of a file, and a known historic size are equal:
def SizeEqual(filePath: str, size: int) -> bool:
return os.path.getsize(filePath) == size
If I pass in a variable of type int
that has a value equal to that of the file size, this function will return True
, but if I pass in a variable of the value represented as a str
, it will return False
.
Example:
os.path.getsize(someFile) # Equal to 5803896
SizeEqual(someFile, 5803896) # Returns True
strVar = '5803896'
SizeEqual(someFile, strVar) # Returns False
I had thought that because I had specified the type in the function parameter, that Python would either prevent the str
type from being passed in, or implicitly convert it to an int
.
What am I missing?
Upvotes: 1
Views: 1297
Reputation: 412
In python the type declaration that the function receives is based on a proposal, the user may or may not follow your instructions, but python will do nothing prevent or change passed parameters. That trait in python is called Duck Typing. If you want to prevent user to pass string you can use somethink like this:
import os
def SizeEqual(filePath: str, size: int) -> bool:
if isinstance(size, int):
return os.path.getsize(filePath) == size
else:
raise Exception("Passed value must be int.")
Upvotes: 1
Reputation: 699
Some versions of python will do all the type management for you (I don't know what those versions are).
The standard Python doesn't do that. It uses Duck Typing. So, when you pass a string, it's going to keep it that way and use it that way.
There are two solutions to this:
def SizeEqual(somefile, size):
try:
size = int(size)
except:
...
SizeEqual(somefile, int(size))
Upvotes: 0