Progeny42
Progeny42

Reputation: 43

Comparing Two Equal Values in a Function Returns False When Parameter is Integer Represented as a String

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

Answers (2)

Uros Pocek
Uros Pocek

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

zerecees
zerecees

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:

  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))

Upvotes: 0

Related Questions