0
votes

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?

2
Comparing different types of values will return False. E.g. "123" == 123 is False. - arsho
@arsho Even though I've declared the parameter as an int? - Progeny42

2 Answers

1
votes

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.")
0
votes

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:

  1. Type check in the function

def SizeEqual(somefile, size):
    try:
        size = int(size)
    except:
        ...
  1. Just convert the parameter to int when you're passing (I prefer this way)
SizeEqual(somefile, int(size))