Python – Declaring a strict data type for a variable in Python


In python, is there a command (or a directive) that raises warning when a variable is assigned a value that differs from the previously assigned type?

x = int()   # "x" declared as integery = float() # "y" declared as floatx = 5       # "x" assigned an integery = 2.75    # "y" assigned a floatprint(x)    # prints "5"print(y)    # prints "2.75"x = y       # !!! "x" is assigned a float; no warning raised !!!print(x)    # prints 2.75

Best Solution

You can't control assignment of global or local variables, but you can override assignment of class object attributes. Here is a class that uses setattr to enforce type. It has a method to assign static type (use int not int() for example) and can also assign type on first assignment of a variable. It is very strict about type but can be changed to allow inherited types.

class BabySitter(object):    def __init__(self):        object.__setattr__(self, "_types", {})    # if you want static assignment    def set_type(self, name, _type):        self._types[name] = _type    def __setattr__(self, name, value):        _type = self._types.get(name)        if _type:            if type(value) is not _type: # or `if not isinstance(value, _type)`                raise ValueError(                    "BabySitter type conflict assigning '{}': was {} is {}".format(                    name, _type, type(value)))        # if you want dynamic assignment        else:            self._types[name] = type(value)        object.__setattr__(self, name, value)var = BabySitter()var.set_type("x", int)     # static "x" declared as integervar.set_type("y", float)   # static "y" declared as floatvar.z = 123     # dynamic "z" int because of first assignmentvar.x = 5       # "x" assigned an integervar.y = 2.75    # "y" assigned a floatprint(var.x)        # prints "5"print(var.y)        # prints "2.75"var.x = var.y           # <== exception is raisedprint(var.x)        # prints 2.75