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 integer
y = float() # "y" declared as float
x = 5 # "x" assigned an integer
y = 2.75 # "y" assigned a float
print(x) # prints "5"
print(y) # prints "2.75"
x = y # !!! "x" is assigned a float; no warning raised !!!
print(x) # prints 2.75
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 integer
var.set_type("y", float) # static "y" declared as float
var.z = 123 # dynamic "z" int because of first assignment
var.x = 5 # "x" assigned an integer
var.y = 2.75 # "y" assigned a float
print(var.x) # prints "5"
print(var.y) # prints "2.75"
var.x = var.y # <== exception is raised
print(var.x) # prints 2.75
Python versions 3.6 and higher support type checking. Check out this article:
How to Use Static Type Checking in Python 3.6
It was written by Adam GeitGey - back in 2017. No need to use a different language!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With