Search code examples
pythonmutation

Type mutations work strange in python, why?


I need to make a simple check for right variable types of my input vars. So I made such function:

def is_good_value(some_value, value_type="numeric"):
        """Check if value is of right type"""

        allowed_types = {
            "numeric" : [float, int],
            "string"  : [str],
            "file"    : [os.path.isfile]
        }

        for each_type in allowed_types[value_type]:
            try:
                each_type(some_value)
            except: exit(print(f"Wrong type: {some_value}, should be {allowed_types[value_type]}"))

If I try to check:

is_good_value("1")

I get the exception. Obviosly, it's because I pass the string "1".

But if I make int("1") or float("1") mutation everything's fine as this value is convertible to these types.

How can I modify my def to get the same result as in simple mutation operations?


Solution

  • It sounds like you're looking for isinstance (and isfile for that file case)...

    allowed_types = {
        "numeric": lambda v: isinstance(v, (float, int)) and not isinstance(v, bool),
        "string": lambda v: isinstance(v, str),
        "file": os.path.isfile,
    }
    def is_good_value(some_value, value_type="numeric"):
        return allowed_types[value_type](some_value)